Skip to content

Advanced techniques

v0phan1ee edited this page Jan 10, 2023 · 15 revisions

This page contains advanced techniques.

Show devicons as kind.

Requirements: nvim-web-devicons and path source.

cmp.setup {
  formatting = {
    format = function(entry, vim_item)
      if vim.tbl_contains({ 'path' }, entry.source.name) then
        local icon, hl_group = require('nvim-web-devicons').get_icon(entry:get_completion_item().label)
        if icon then
          vim_item.kind = icon
          vim_item.kind_hl_group = hl_group
          return vim_item
        end
      end
      return require('lspkind').cmp_format({ with_text = false })(entry, vim_item)
    end
  }
}

Managing completion timing completely

nvim-cmp has a programmatic API. So you can manage the completion behavior by yourself.

See https://github.com/hrsh7th/nvim-cmp/issues/519#issuecomment-1091109258

Disabling completion in certain contexts, such as comments

See https://github.com/hrsh7th/nvim-cmp/pull/676#issuecomment-1002532096

cmp.setup({
    enabled = function()
      -- disable completion in comments
      local context = require 'cmp.config.context'
      -- keep command mode completion enabled when cursor is in a comment
      if vim.api.nvim_get_mode().mode == 'c' then
        return true
      else
        return not context.in_treesitter_capture("comment") 
          and not context.in_syntax_group("Comment")
      end
    end
})

Add parentheses after selecting function or method item

nvim-autopairs

-- If you want insert `(` after select function or method item
local cmp_autopairs = require('nvim-autopairs.completion.cmp')
local cmp = require('cmp')
cmp.event:on(
  'confirm_done',
  cmp_autopairs.on_confirm_done()
)
Clone this wiki locally