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

-- https://github.com/hrsh7th/nvim-cmp/issues/180#issuecomment-915405589
luasnip.config.set_config { history = true }
require('luasnip.loaders.from_vscode').load {}

cmp.setup {
  preselect  = cmp.PreselectMode.None,
  completion = {
    completeopt = 'menu,menuone,noinsert',
  },
  formatting = {
    fields = { 'kind', 'abbr', 'menu' },
    format = function(entry, vim_item)
      vim_item.menu = ({
        buffer   = '[Buffer]',
        nvim_lsp = '[Lsp]',
        nvim_lua = '[Lua]',
        path     = '[Path]',
        luasnip  = '[Snippet]',
      })[entry.source.name]
      vim_item.kind = lspkind.presets.default[vim_item.kind]
      return vim_item
    end,
  },
  snippet = {
    expand = function (args)
      luasnip.lsp_expand(args.body)
    end
  },
  documentation = {
    border = 'rounded'
  },
  mapping = {
    ['<C-d>'] = cmp.mapping.scroll_docs(-4),
    ['<C-f>'] = cmp.mapping.scroll_docs(4),
    ['<CR>'] = cmp.mapping.confirm({
      behavior = cmp.ConfirmBehavior.Replace,
      select = false
    }),
  },
  sources = {
    {
      name = 'nvim_lsp',
      priority = 100
    },
    {
      name = 'luasnip',
      priority = 80
    },
    {
      name = 'nvim_lua',
      priority = 50
    },
    {
      name = 'buffer',
      priority = 20
    },
    {
      name = 'path',
      priority = 5
    },
  },
  experimental = {
    native_menu = false,
    ghost_text  = { hl_group = 'Hint' },
  }
}
