nvim-cmp Documentation

A completion plugin for neovim coded in Lua.

9,483 stars Lua Lua 1 file ยท ~9,781 tokens #nvim-cmp
RAW Doc

Technical Documentation: hrsh7th/nvim-cmp

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

nvim-cmp

A completion engine plugin for neovim written in Lua.
Completion sources are installed from external repositories and "sourced".

https://github.com/hrsh7th/nvim-cmp/assets/22756295/afa70011-9121-4e42-aedd-0153b630eeab

Readme!

  1. There is a GitHub issue that documents breaking changes for nvim-cmp. Subscribe to the issue to be notified of upcoming breaking changes.
  2. This is my hobby project. You can support me via GitHub sponsors.
  3. Bug reports are welcome, but don't expect a fix unless you provide minimal configuration and steps to reproduce your issue.
  4. The cmp.mapping.preset.* is pre-defined configuration that aims to mimic neovim's native like behavior. It can be changed without announcement. Please manage key-mapping by yourself.

Concept

  • Full support for LSP completion related capabilities
  • Powerful customizability via Lua functions
  • Smart handling of key mappings
  • No flicker

Setup

This example configuration uses vim-plug as the plugin manager and vim-vsnip as a snippet plugin.

text
/* Detailed source-code truncated for AI context efficiency. */

Where can I find more completion sources?

Have a look at the Wiki and the nvim-cmp GitHub topic.

Where can I find advanced configuration examples?

See the Wiki.


Doc Cmp (`doc/cmp.txt`)

nvim-cmp cmp

A completion plugin for neovim coded in Lua.

==============================================================================
CONTENTS cmp-contents

Abstract |cmp-abstract|
Concept |cmp-concept|
Usage |cmp-usage|
Function |cmp-function|
Mapping |cmp-mapping|
Command |cmp-command|
Highlight |cmp-highlight|
FileType |cmp-filetype|
Autocmd |cmp-autocmd|
Config |cmp-config|
Config Helper |cmp-config-helper|
Develop |cmp-develop|
FAQ |cmp-faq|

==============================================================================
Abstract cmp-abstract

This is nvim-cmp's document.

  1. This help file uses the type definition notation like {lsp,cmp,vim}.*
  • You can find it in ../lua/cmp/types/init.lua.
  1. Advanced configuration is described in the wiki.

==============================================================================
Concept cmp-concept

  • Full support for LSP completion related capabilities
  • Powerful customization abilities via Lua functions
  • Smart handling of key mappings
  • No flicker

==============================================================================
Usage cmp-usage

A recommended configuration can be found below.
NOTE:
1. You must provide a snippet.expand function.
2. cmp.setup.cmdline won't work if you use the native completion menu.
3. You can disable the default options by specifying cmp.config.disable value.

vim
call plug#begin(s:plug_dir)
Plug 'neovim/nvim-lspconfig'
Plug 'hrsh7th/cmp-nvim-lsp'
Plug 'hrsh7th/cmp-buffer'
Plug 'hrsh7th/cmp-path'
Plug 'hrsh7th/cmp-cmdline'
Plug 'hrsh7th/nvim-cmp'

" For vsnip users.
Plug 'hrsh7th/cmp-vsnip'
Plug 'hrsh7th/vim-vsnip'

" For luasnip users.
" Plug 'L3MON4D3/LuaSnip'
" Plug 'saadparwaiz1/cmp_luasnip'

" For mini.snippets users.
" Plug 'echasnovski/mini.snippets'
" Plug 'abeldekat/cmp-mini-snippets'

" For snippy users.
" Plug 'dcampos/nvim-snippy'
" Plug 'dcampos/cmp-snippy'

" For ultisnips users.
" Plug 'SirVer/ultisnips'
" Plug 'quangnguyen30192/cmp-nvim-ultisnips'

call plug#end()

set completeopt=menu,menuone,noselect

lua <<EOF
local cmp = require'cmp'

text
-- Global setup.
cmp.setup({
  snippet = {
    expand = function(args)
      vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users.
      -- require('luasnip').lsp_expand(args.body) -- For `luasnip` users.
      -- require'snippy'.expand_snippet(args.body) -- For `snippy` users.
      -- vim.fn["UltiSnips#Anon"](args.body) -- For `ultisnips` users.
      -- vim.snippet.expand(args.body) -- For native neovim snippets (Neovim v0.10+)

      -- For `mini.snippets` users:
      -- local insert = MiniSnippets.config.expand.insert or MiniSnippets.default_insert
      -- insert({ body = args.body }) -- Insert at cursor
      -- cmp.resubscribe({ "TextChangedI", "TextChangedP" })
      -- require("cmp.config").set_onetime({ sources = {} })
    end,
  },
  window = {
    -- completion = cmp.config.window.bordered(),
    -- documentation = cmp.config.window.bordered(),
  },
  mapping = cmp.mapping.preset.insert({
    ['<C-d>'] = cmp.mapping.scroll_docs(-4),
    ['<C-f>'] = cmp.mapping.scroll_docs(4),
    ['<C-Space>'] = cmp.mapping.complete(),
    ['<CR>'] = cmp.mapping.confirm({ select = true }),
  }),
  sources = cmp.config.sources({
    { name = 'nvim_lsp' },
    { name = 'vsnip' }, -- For vsnip users.
    -- { name = 'luasnip' }, -- For luasnip users.
    -- { name = 'snippy' }, -- For snippy users.
    -- { name = 'ultisnips' }, -- For ultisnips users.
  }, {
    { name = 'buffer' },
  })
})

-- `/` cmdline setup.
cmp.setup.cmdline('/', {
  mapping = cmp.mapping.preset.cmdline(),
  sources = {
    { name = 'buffer' }
  }
})

-- `:` cmdline setup.
cmp.setup.cmdline(':', {
  mapping = cmp.mapping.preset.cmdline(),
  sources = cmp.config.sources({
    { name = 'path' }
  }, {
    { name = 'cmdline' }
  }),
  matching = { disallow_symbol_nonprefix_matching = false }
})

-- Setup lspconfig.
local capabilities = require('cmp_nvim_lsp').default_capabilities()
vim.lsp.config(%YOUR_LSP_SERVER%, {
  capabilities = capabilities
})
vim.lsp.enable(%YOUR_LSP_SERVER%)

EOF <

Function cmp-function

NOTE: <Cmd>lua require('cmp').complete()<CR> can be used to call these functions in a mapping.

cmp.setup (config: cmp.ConfigSchema)
Setup global configuration. See configuration options.

cmp.setup.filetype (filetype: string, config: cmp.ConfigSchema)
Setup filetype-specific configuration.

cmp.setup.buffer (config: cmp.ConfigSchema)
Setup configuration for the current buffer.

cmp.setup.cmdline (cmdtype: string, config: cmp.ConfigSchema)
Setup cmdline configuration for the specific type of command.
See |getcmdtype()|.
NOTE: nvim-cmp does not support the = command type.

cmp.get_registered_sources ()
Get all registered sources.

cmp.visible ()
Return a boolean showing whether the completion menu is visible or not.

cmp.visible_docs ()
Return a boolean showing whether the docs window is visible or not.

cmp.get_entries ()
Return all current entries.

cmp.get_selected_entry ()
Return currently selected entry (including preselected).

cmp.get_active_entry ()
Return currently selected entry (excluding preselected).

cmp.close ()
Close the completion menu.

cmp.abort ()
Closes the completion menu and restore the current line to the state before the current completion was started.

cmp.select_next_item (option: { behavior = cmp.SelectBehavior, count = 1 })
Select the next item. Set count with large number to select pagedown.
behavior can be one of:

  • cmp.SelectBehavior.Insert: Inserts the text at cursor.
  • cmp.SelectBehavior.Select: Only selects the text, potentially adds ghost_text at
    cursor.

lua
cmp.setup {
mapping = {
[""] = cmp.mapping.select_next_item({ behavior = cmp.SelectBehavior.Select }),
}
}
<

cmp.select_prev_item (option: { behavior = cmp.SelectBehavior, count = 1 })
Select the previous item. Set count with large number to select pageup.
behavior can be one of:

  • cmp.SelectBehavior.Insert: Inserts the text at cursor.
  • cmp.SelectBehavior.Select: Only selects the text, potentially adds ghost_text at
    cursor.

lua
cmp.setup {
mapping = {
[""] = cmp.mapping.select_prev_item({ behavior = cmp.SelectBehavior.Select }),
}
}
<
cmp.open_docs ()
Open docs view.

cmp.close_docs ()
Close docs view.

cmp.scroll_docs (delta: number)
Scroll the documentation window if visible.

cmp.complete (option: { reason = cmp.ContextReason, config = cmp.ConfigSchema })
Invoke completion.

The following configuration defines a key mapping to show completion only for vsnip snippets.

lua
cmp.setup {
mapping = {
[''] = cmp.mapping.complete({
config = {
sources = {
{ name = 'vsnip' }
}
}
})
}
}
< >vim
inoremap lua require('cmp').complete({ config = { sources = { { name = 'vsnip' } } } })
<
NOTE: config in that case means a temporary setting, but config.mapping remains permanent.

cmp.complete_common_string ()
Complete common string (similar to shell completion behavior).

lua
cmp.setup {
mapping = {
[''] = cmp.mapping(function(fallback)
if cmp.visible() then
return cmp.complete_common_string()
end
fallback()
end, { 'i', 'c' }),
}
}
<
cmp.confirm (option: cmp.ConfirmOption, callback: function)
Accepts the currently selected completion item.
If you didn't select any item and the option table contains select = true,
nvim-cmp will automatically select the first item.

You can control how the completion item is injected into
the file through the behavior option:

behavior=cmp.ConfirmBehavior.Insert: inserts the selected item and
moves adjacent text to the right (default).
behavior=cmp.ConfirmBehavior.Replace: replaces adjacent text with
the selected item.

lua
cmp.setup {
mapping = {
[""] = cmp.mapping.confirm({ select = true, behavior = cmp.ConfirmBehavior.Replace }),
}
}
<
cmp.event:on (%EVENT_NAME%, callback)
Subscribe to nvim-cmp's event. Events are listed below.

  • complete_done: emit after current completion is done.
  • confirm_done: emit after confirmation is done.
  • menu_opened: emit after opening a new completion menu. Called with a table holding a key
    named window, pointing to the completion menu implementation.
  • menu_closed: emit after completion menu is closed. Called with a table holding a key
    named window, pointing to the completion menu implementation.

==============================================================================
Mapping cmp-mapping

Nvim-cmp's mapping mechanism is complex but flexible and user-friendly.

You can specify a mapping function that receives a fallback function as an argument.
The fallback function can be used to call an existing mapping.

For example, typical pair-wise plugins automatically define mappings for <CR> and (.
Nvim-cmp will overwrite it if you provide a mapping. To call the existing mapping,
you would need to invoke the fallback function.

lua
cmp.setup {
mapping = {
[''] = function(fallback)
if cmp.visible() then
cmp.confirm()
else
fallback() -- If you use vim-endwise, this fallback will behave the same as vim-endwise.
end
end
}
}
< >lua
cmp.setup {
mapping = {
[''] = function(fallback)
if cmp.visible() then
cmp.select_next_item()
else
fallback()
end
end
}
}
<

It is possible to specify the modes the mapping should be active in (i = insert mode, c = command mode, s = select mode):

lua
cmp.setup {
mapping = {
[''] = cmp.mapping(your_mapping_function, { 'i', 'c' })
}
}
<
You can also specify different mappings for different modes by passing a table:
lua
cmp.setup {
mapping = {
[''] = cmp.mapping({
i = your_mapping_function_a,
c = your_mapping_function_b,
})
}
}
<
There are also builtin mapping helper functions you can use:

cmp.mapping.close ()
Same as |cmp.close|.

cmp.mapping.abort ()
Same as |cmp.abort|.

cmp.mapping.select_next_item (option: { behavior = cmp.SelectBehavior, count = 1 })
Same as |cmp.select_next_item|.

cmp.mapping.select_prev_item (option: { behavior = cmp.SelectBehavior, count = 1 })
Same as |cmp.select_prev_item|.

cmp.mapping.open_docs ()
Same as |cmp.open_docs|.

cmp.mapping.close_docs ()
Same as |cmp.close_docs|.

cmp.mapping.scroll_docs (delta: number)
Same as |cmp.scroll_docs|.

cmp.mapping.complete (option: cmp.CompleteParams)
Same as |cmp.complete|.

cmp.mapping.complete_common_string ()
Same as |cmp.complete_common_string|.

cmp.mapping.confirm (option: cmp.ConfirmOption)
Same as |cmp.confirm|.

Built-in mapping helpers are only available as a configuration option.
If you want to call nvim-cmp features directly, please use |cmp-function| instead.

==============================================================================
Command cmp-command

CmpStatus
Describes statuses and states of sources.
Sometimes unknown will be printed - this is expected.
For example, cmp-nvim-lsp registers itself on InsertEnter autocommand
so the status will be shown as unknown when running the command.

==============================================================================
Highlight cmp-highlight

CmpItemAbbr
Highlight group for unmatched characters of each completion field.

CmpItemAbbrDeprecated
Highlight group for unmatched characters of each deprecated completion field.

CmpItemAbbrMatch
Highlight group for matched characters of each completion field. Matched characters
must form a substring of a field which share a starting position.

CmpItemAbbrMatchFuzzy
Highlight group for fuzzy-matched characters of each completion field.

CmpItemKind
Highlight group for the kind of the field.

NOTE: kind is a symbol after each completion option.

*CmpItemKindIcon
Highlight group for the icons used for each lsp.CompletionItemKind.

CmpItemKind%KIND_NAME%
Highlight group for the kind of the field for a specific lsp.CompletionItemKind.
If you only want to overwrite the method kind's highlight group, you can do this:

vim
highlight CmpItemKindMethod guibg=NONE guifg=Orange

*CmpItemKind%KIND_NAME%Icon
Highlight group for the icon shown for a specific lsp.CompletionItemKind.
Can be overriden the same way as shown above OR with a custom function
in your format table (e.g.):

text
local function set_colors(str)
    local color = vim.api.nvim_get_hl(args...)
    vim.api.nvim_set_hl(args...)
  end

<
CmpItemMenu
The menu field's highlight group.

==============================================================================
FileType cmp-filetype

cmp_menu
The completion menu buffer's filetype.

cmp_docs
The documentation window buffer's filetype.

==============================================================================
Autocmd cmp-autocmd

You can create custom autocommands for certain nvim-cmp events by defining
autocommands for the User event with the following patterns:

CmpReady
Invoked when nvim-cmp gets sourced from plugin/cmp.lua.

CmpRegisterSource
Invoke when source was registered.

CmpUnregisterSource
Invoke when source was un-registered.

==============================================================================
Config cmp-config

You can use the following options via cmp.setup { ... } .

text
*cmp-config.enabled*

enabled~
boolean | fun(): boolean
Toggles the plugin on and off.

text
*cmp-config.performance.debounce*

performance.debounce~
number
Sets debounce time
This is the interval used to group up completions from different sources
for filtering and displaying.

text
*cmp-config.performance.throttle*

performance.throttle~
number
Sets throttle time
This is used to delay filtering and displaying completions.

text
*cmp-config.performance.fetching_timeout*

performance.fetching_timeout~
number
Sets the timeout of candidate fetching process.
The nvim-cmp will wait to display the most prioritized source.

text
*cmp-config.performance.filtering_context_budget*

performance.filtering_context_budget~
number
Sets the filtering context budget in ms.
If filtering takes longer than this, it will be deferred.

text
*cmp-config.performance.confirm_resolve_timeout*

performance.confirm_resolve_timeout~
number
Sets the timeout for resolving item before confirmation.

text
*cmp-config.performance.async_budget*

performance.async_budget~
number
Maximum time (in ms) an async function is allowed to run during
one step of the event loop.

text
*cmp-config.performance.max_view_entries*

performance.max_view_entries~
number
Maximum number of items to show in the entries list.

text
*cmp-config.preselect*

preselect~
cmp.PreselectMode

  1. cmp.PreselectMode.Item
    nvim-cmp will preselect the item that the source specified.
  2. cmp.PreselectMode.None
    nvim-cmp will not preselect any items.

    cmp-config.mapping

mapping~
table<string, fun(fallback: function)
See |cmp-mapping| section.

text
*cmp-config.snippet.expand*

snippet.expand~
fun(option: cmp.SnippetExpansionParams)
The snippet expansion function. That's how nvim-cmp interacts with a
particular snippet engine.

text
*cmp-config.completion.keyword_length*

completion.keyword_length~
number
The number of characters needed to trigger auto-completion.

text
*cmp-config.completion.keyword_pattern*

completion.keyword_pattern~
string
The default keyword pattern.

text
*cmp-config.completion.autocomplete*

completion.autocomplete~
cmp.TriggerEvent[] | false
The event to trigger autocompletion. If set to false, then completion is
only invoked manually (e.g. by calling cmp.complete).

text
*cmp-config.completion.completeopt*

completion.completeopt~
string
Like vim's completeopt setting. See 'completeopt'.
In general, you don't need to change this.

text
*cmp-config.confirmation.get_commit_characters*

confirmation.get_commit_characters~
fun(commit_characters:string[]):string[]
You can append or exclude commitCharacters via this configuration option
function. The commitCharacters are defined by the LSP spec.

text
*cmp-config.formatting.expandable_indicator*

formatting.expandable_indicator~
cmp.expandable_indicator
Boolean to show the ~ expandable indicator in cmp's floating window.

text
*cmp-config.formatting.fields*

formatting.fields~
cmp.ItemField[]
An array of completion fields to specify their order.

text
*cmp-config.formatting.format*

formatting.format~
fun(entry: cmp.Entry, vim_item: vim.CompletedItem): vim.CompletedItem
The function used to customize the appearance of the completion menu. See
|complete-items|. This value can also be used to modify the dup property.
NOTE: The vim.CompletedItem can contain the special properties
abbr_hl_group, icon_hl_group, kind_hl_group and menu_hl_group.

text
*cmp-config.matching.disallow_fuzzy_matching*

matching.disallow_fuzzy_matching~
boolean
Whether to allow fuzzy matching.

text
*cmp-config.matching.disallow_fullfuzzy_matching*

matching.disallow_fullfuzzy_matching~
boolean
Whether to allow full-fuzzy matching.

text
*cmp-config.matching.disallow_partial_fuzzy_matching*

matching.disallow_partial_fuzzy_matching~
boolean
Whether to allow fuzzy matching without prefix matching.
cmp-config.matching.disallow_partial_matching
matching.disallow_partial_matching~
boolean
Whether to allow partial matching.

text
*cmp-config.matching.disallow_prefix_unmatching*

matching.disallow_prefix_unmatching~
boolean
Whether to allow prefix unmatching.

text
cmp-config.matching.disallow_symbol_nonprefix_matching

matching.disallow_symbol_nonprefix_matching
boolean
Whether to allow symbols in matches if the match is not a prefix match.

text
*cmp-config.sorting.priority_weight*

sorting.priority_weight~
number
Each item's original priority (given by its corresponding source) will be
increased by #sources - (source_index - 1) and multiplied by priority_weight.
That is, the final priority is calculated by the following formula:

lua
final_score = orig_score + ((#sources - (source_index - 1)) * sorting.priority_weight)
<
cmp-config.sorting.comparators
sorting.comparators~
(fun(entry1: cmp.Entry, entry2: cmp.Entry): boolean | nil)[]
The function to customize the sorting behavior.
You can use built-in comparators via cmp.config.compare.*.

text
*cmp-config.sources*

sources~
cmp.SourceConfig[]
List of the sources and their configurations to use.
The order of the sources determines their order in the completion results.

text
*cmp-config.sources[n].name*

sources[n].name~
string
The name of the source.

text
*cmp-config.sources[n].option*

sources[n].option~
table
Any specific options defined by the source itself.

text
*cmp-config.sources[n].keyword_length*

sources[n].keyword_length~
number
The source-specific keyword length to trigger auto completion.

text
*cmp-config.sources[n].keyword_pattern*

sources[n].keyword_pattern~
string
The source-specific keyword pattern.

text
*cmp-config.sources[n].trigger_characters*

sources[n].trigger_characters~
string[]
A source-specific keyword pattern.

text
*cmp-config.sources[n].priority*

sources[n].priority~
number
The source-specific priority value.

text
*cmp-config.sources[n].max_item_count*

sources[n].max_item_count~
number
The source-specific maximum item count option
Note: This is applied before sorting, so items that aren't well-matched may be selected.

text
*cmp-config.sources[n].group_index*

sources[n].group_index~
number
The source group index.

For instance, you can set the buffer's source group_index to a larger number
if you don't want to see buffer source items while nvim-lsp source is available:

lua
cmp.setup {
sources = {
{ name = 'nvim_lsp', group_index = 1 },
{ name = 'buffer', group_index = 2 },
}
}

<
You can also achieve this by using the built-in configuration helper like this:
lua
cmp.setup {
sources = cmp.config.sources({
{ name = 'nvim_lsp' },
}, {
{ name = 'buffer' },
})
}

<

text
*cmp-config.sources[n].entry_filter*

sources[n].entry_filter~
function
A source-specific entry filter, with the following function signature:

function(entry: cmp.Entry, ctx: cmp.Context): boolean
<

Returning true will keep the entry, while returning false will remove it.

This can be used to hide certain entries from a given source. For instance, you
could hide all entries with kind Text from the nvim_lsp filter using the
following source definition:

lua
{
name = 'nvim_lsp',
entry_filter = function(entry, ctx)
return require('cmp.types').lsp.CompletionItemKind[entry:get_kind()] ~= 'Text'
end
}
<
Using the ctx parameter, you can further customize the behaviour of the
source.

text
*cmp-config.view*

view~
{ docs: cmp.DocsViewConfig }
{ entries: cmp.EntriesViewConfig|string }
The view class used to customize nvim-cmp's appearance.
Currently available configuration options are:

text
*cmp-config.view.docs.auto_open*

view.docs.auto_open~
boolean

Specify whether to show the docs_view when selecting an item.

text
*cmp-config.view.entries.selection_order*

view.entries.selection_order~
string

Specify whether to select the option in the pmenu that is at
the top (top_down) or nearest to the cursor (near_cursor).
Useful if pmenu is above cursor and you want to change default
selection direction. Custom view only. top_down by default.

text
*cmp-config.view.entries.follow_cursor*

view.entries.follow_cursor~
boolean

Specify whether the pmenu should follow the current position of the cursor
as the user types. Custom view only. false by default.

text
*cmp-config.window.{completion,documentation}.border*

window.{completion,documentation}.border~
string | string[] | nil
Border characters used for the completion popup menu when |experimental.native_menu| is disabled.
See |nvim_open_win|.

text
*cmp-config.window.{completion,documentation}.winhighlight*

window.{completion,documentation}.winhighlight~
string | cmp.WinhighlightConfig
Specify the window's winhighlight option.
See |nvim_open_win|.

text
*cmp-config.window.{completion,documentation}.winblend*

window.{completion,documentation}.winblend~
string | cmp.WinhighlightConfig
Specify the window's winblend option.
See |nvim_open_win|.

text
*cmp-config.window.{completion,documentation}.zindex*

window.{completion,documentation}.zindex~
number
The completion window's zindex.
See |nvim_open_win|.

text
*cmp-config.window.{completion,documentation}.scrolloff*

window.completion.scrolloff~
number
Specify the window's scrolloff option.
See |'scrolloff'|.

text
*cmp-config.window.{completion,documentation}.col_offset*

window.completion.col_offset~
number
Offsets the completion window relative to the cursor.
Offsets the documentation window relative to the completion window.

text
*cmp-config.window.completion.side_padding*

window.completion.side_padding~
number
The amount of padding to add on the completion window's sides

text
*cmp-config.window.completion.scrollbar*

window.completion.scrollbar~
boolean
Whether the scrollbar should be enabled if there are more items that fit

text
*cmp-config.window.completion.max_height*

window.completion.max_height~
number | nil
The completion window's max height, can be set to 0 to use all available
space. To use vim.o.pumheight set this to nil.
See |'pumheight'|.

text
*cmp-config.window.documentation.max_width*

window.documentation.max_width~
number
The documentation window's max width, can be set to 0 to use all available
space.

text
*cmp-config.window.documentation.max_height*

window.documentation.max_height~
number
The documentation window's max height, can be set to 0 to use all available
space.

text
*cmp-config.experimental.ghost_text*

experimental.ghost_text~
boolean | { hl_group = string }
Whether to enable the ghost_text feature.

==============================================================================
Config Helper cmp-config-helper

You can use the following configuration helpers:

cmp.config.compare~

TBD

cmp.config.context~

The cmp.config.context can be used for context-aware completion toggling.

lua
cmp.setup {
enabled = function()
-- disable completion if the cursor is Comment syntax group.
return not cmp.config.context.in_syntax_group('Comment')
end
}

<
cmp.config.context.in_syntax_group (group)
You can specify the vim's built-in syntax group.
If you use tree-sitter, you should use cmp.config.context.in_treesitter_capture instead.

cmp.config.context.in_treesitter_capture (capture)
You can specify the treesitter capture name.
If you don't use the nvim-treesitter plugin, this helper will not work correctly.

cmp.config.mapping~

See |cmp-mapping|.

cmp.config.sources~

cmp.config.sources (...sources)
You can specify multiple source arrays. The sources are grouped in the
order you specify, and the groups are displayed as a fallback, like chain
completion.

lua
cmp.setup {
sources = cmp.config.sources({
{ name = 'nvim_lsp' },
}, {
{ name = 'buffer' },
})
}

<
cmp.config.window~

cmp.config.window.bordered (option)
Make the completion window bordered.
The option is described in cmp.ConfigSchema.

lua
cmp.setup {
window = {
completion = cmp.config.window.bordered(),
documentation = cmp.config.window.bordered(),
}
}

<
==============================================================================
Develop cmp-develop

Creating a custom source~

NOTE:

  1. The complete method is required. Others can be omitted.
  2. The callback function must always be called.
  3. You can use only require('cmp') in custom source.
  4. If the LSP spec was changed, nvim-cmp may implement it without any announcement (potentially introducing breaking changes).
  5. You should read ./lua/cmp/types and https://microsoft.github.io/language-server-protocol/specifications/specification-current.
  6. Please add your source to the list of sources in the Wiki (https://github.com/hrsh7th/nvim-cmp/wiki/List-of-sources)
    and if you publish it on GitHub, add the nvim-cmp topic so users can find it more easily.

Here is an example on how to create a custom source:

lua
local source = {}

---Return whether this source is available in the current context or not (optional).
---@return boolean
function source:is_available()
return true
end

---Return the debug name of this source (optional).
---@return string
function source:get_debug_name()
return 'debug name'
end

---Return LSP's PositionEncodingKind.
---@NOTE: If this method is omitted, the default value will be utf-16.
---@return lsp.PositionEncodingKind
function source:get_position_encoding_kind()
return 'utf-16'
end

---Return the keyword pattern for triggering completion (optional).
---If this is omitted, nvim-cmp will use a default keyword pattern. See |cmp-config.completion.keyword_pattern|.
---@return string
function source:get_keyword_pattern()
return [[\k+]]
end

---Return trigger characters for triggering completion (optional).
function source:get_trigger_characters()
return { '.' }
end

---Invoke completion (required).
---@param params cmp.SourceCompletionApiParams
---@param callback fun(response: lsp.CompletionResponse|nil)
function source:complete(params, callback)
callback({
{ label = 'January' },
{ label = 'February' },
{ label = 'March' },
{ label = 'April' },
{ label = 'May' },
{ label = 'June' },
{ label = 'July' },
{ label = 'August' },
{ label = 'September' },
{ label = 'October' },
{ label = 'November' },
{ label = 'December' },
})
end

---Resolve completion item (optional). This is called right before the completion is about to be displayed.
---Useful for setting the text shown in the documentation window (completion_item.documentation).
---@param completion_item lsp.CompletionItem
---@param callback fun(completion_item: lsp.CompletionItem|nil)
function source:resolve(completion_item, callback)
callback(completion_item)
end

---Executed after the item was selected.
---@param completion_item lsp.CompletionItem
---@param callback fun(completion_item: lsp.CompletionItem|nil)
function source:execute(completion_item, callback)
callback(completion_item)
end

---Register your source to nvim-cmp. require('cmp').register_source('month', source) <

FAQ cmp-faq

Why does cmp automatically select a particular item? ~
How to disable the preselect feature? ~

Nvim-cmp respects the LSP (Language Server Protocol) specification.
The LSP spec defines the preselect feature for completion.

You can disable the preselect feature like this:

lua
cmp.setup {
preselect = cmp.PreselectMode.None
}
<
How to disable only specific language-server's completion?~

You can disable completionProvider in lspconfig configuration.

lua
lspconfig[%SERVER_NAME%].setup {
on_attach = function(client)
client.server_capabilities.completionProvider = false
end
}
<

How to disable commitCharacters?~

You can disable the commitCharacters feature (which is defined in LSP spec):

lua
cmp.setup {
confirmation = {
get_commit_characters = function(commit_characters)
return {}
end
}
}
<

How to disable automatic display of docs view?~

You can add the view.docs.auto_open = false for configuration.

lua
cmp.setup {
...
view = {
docs = {
auto_open = false
}
}
...
}
<

additionally, if you want to open/close docs view via your key mapping, you
can define keymapping as the following.

lua
cmp.setup {
...
mapping = {
[''] = function()
if cmp.visible_docs() then
cmp.close_docs()
else
cmp.open_docs()
end
end
}
...
}
<

How to disable auto-completion?~
How to use nvim-cmp as omnifunc?~

You can disable auto-completion like this:

lua
cmp.setup {
...
completion = {
autocomplete = false
}
...
}
<
Then you will need to invoke completion manually.
vim
inoremap lua require('cmp').complete()
<

How to disable nvim-cmp for a specific buffer?~
How to setup nvim-cmp for a specific buffer?~

You can setup buffer-specific configuration like this:

lua
cmp.setup.filetype({ 'markdown', 'help' }, {
sources = {
{ name = 'path' },
{ name = 'buffer' },
}
})
<

How to disable the documentation window?~

Simply use the following config:

lua
cmp.setup.filetype({ 'markdown', 'help' }, {
window = {
documentation = cmp.config.disable
}
})
<

I'm using clangd. The menu items are mis-indented.~

It's caused by clangd. You can specify --header-insertion-decorators for
clangd's command-line arguments. See #999.

How to integrate with copilot.vim?~

Copilot.vim and nvim-cmp both have a key-mapping fallback mechanism.
Therefore, you should manage those plugins by yourself.

Fortunately, the copilot.vim has a feature that disables the fallback mechanism.

vim
let g:copilot_no_tab_map = v:true
imap (vimrc:copilot-dummy-map) copilot#Accept("<Tab>")
<
You can manage copilot.vim's accept feature inside nvim-cmp's key-mapping function:
lua
cmp.setup {
mapping = {
[''] = cmp.mapping(function(fallback)
vim.api.nvim_feedkeys(vim.fn['copilot#Accept'](vim.api.nvim_replace_termcodes('', true, true, true)), 'n', true)
end)
},
experimental = {
ghost_text = false -- this feature conflict with copilot.vim's preview.
}
}
<
nvim-cmp does not work as expected.~

There are some known issues. Please check the following.

  • nvim-cmp does not work with set paste option.
  • Command line mode key mapping is unified regardless of :, /, ?. Therefore, it is impossible to apply the mapping only to :.

How to customize the menu appearance?~

Have a look at the wiki (https://github.com/hrsh7th/nvim-cmp/wiki).

==============================================================================
vim:tw=78:ts=2:et:ft=help:norl:


--- METRICS ---