local cmp = require 'cmp'
local lspkind = require 'lspkind'

local has_words_before = function()
    local line, col = unpack(vim.api.nvim_win_get_cursor(0))
    return col ~= 0 and
        vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col,
            col)
        :match("%s") == nil
end

local feedkey = function(key, mode)
    vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true),
        mode, true)
end

vim.o.completeopt = "menu,menuone,noselect"

-- completion items
require('cmp').register_source('vCard', require('completion_vcard').setup_cmp(
    '~/documents/contacts/myconts'))
vim.g.vsnip_snippet_dir = (vim.env.XDG_DATA_HOME or "~/.local/share") ..
    "/nvim/snippets"
cmp.setup({
    snippet = { expand = function(args) vim.fn["vsnip#anonymous"](args.body) end },
    mapping = {
        ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }),
        ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }),
        ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }),
        ['<C-y>'] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping.
        ['<C-e>'] = cmp.mapping({
            i = cmp.mapping.abort(),
            c = cmp.mapping.close()
        }),
        -- Accept currently selected item. If none selected, `select` first item.
        -- Set `select` to `false` to only confirm explicitly selected items.
        ['<CR>'] = cmp.mapping.confirm({ select = false }),
        ["<C-n>"] = cmp.mapping(function(fallback)
            if cmp.visible() then
                cmp.select_next_item()
            elseif vim.fn["vsnip#available"](1) == 1 then
                feedkey("<Plug>(vsnip-expand-or-jump)", "")
            elseif has_words_before() then
                cmp.complete()
            else
                fallback()
            end
        end, { "i", "s" }),

        ["<C-p>"] = cmp.mapping(function()
            if cmp.visible() then
                cmp.select_prev_item()
            elseif vim.fn["vsnip#jumpable"](-1) == 1 then
                feedkey("<Plug>(vsnip-jump-prev)", "")
            end
        end, { "i", "s" })
    },
    formatting = {
        format = lspkind.cmp_format({
            with_text = false,
            menu = ({
                buffer = "B",
                nvim_lua = "NLua",
                tmux = "τ",
                vCard = "VCARD"
            })
        })
    },
    sources = cmp.config.sources({
        { name = 'path' }, { name = 'nvim_lsp' }, { name = 'treesitter' },
        { name = 'tmux' }, { name = 'vsnip' }, { name = 'latex_symbols' },
        { name = 'vCard' }, { name = 'nvim_lua' }
    }, { { name = 'buffer' }, { name = 'spell' } })
})

if vim.o.ft == 'clap_input' and vim.o.ft == 'guihua' and vim.o.ft ==
    'guihua_rust' then require 'cmp'.setup.buffer { completion = { enable = false } } end

-- Use buffer source for `/` search
cmp.setup.cmdline('/', {
    mapping = cmp.mapping.preset.cmdline(),
    sources = cmp.config.sources({ { name = 'buffer' } })
})

-- Use cmdline & path source for ':' in vim
cmp.setup.cmdline(':', {
    mapping = cmp.mapping.preset.cmdline(),
    sources = cmp.config.sources({ { name = 'path' } }, { { name = 'cmdline' } })
})

require('cmp_nvim_lsp').default_capabilities(vim.lsp.protocol
    .make_client_capabilities())
