### Setup Buffer-Specific Configuration for nvim-cmp Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Configure nvim-cmp differently for specific filetypes like markdown or help. This example sets up sources for these filetypes. ```lua cmp.setup.filetype({ 'markdown', 'help' }, { sources = { { name = 'path' }, { name = 'buffer' }, } }) ``` -------------------------------- ### Setup Functions Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Functions for setting up nvim-cmp globally, per filetype, per buffer, or for command-line interfaces. ```APIDOC ## cmp.setup ### Description Setup global configuration. See configuration options. ### Function Signature `cmp.setup(config: cmp.ConfigSchema)` ``` ```APIDOC ## cmp.setup.filetype ### Description Setup filetype-specific configuration. ### Function Signature `cmp.setup.filetype(filetype: string, config: cmp.ConfigSchema)` ``` ```APIDOC ## cmp.setup.buffer ### Description Setup configuration for the current buffer. ### Function Signature `cmp.setup.buffer(config: cmp.ConfigSchema)` ``` ```APIDOC ## cmp.setup.cmdline ### Description Setup cmdline configuration for the specific type of command. See |getcmdtype()|. NOTE: nvim-cmp does not support the `=` command type. ### Function Signature `cmp.setup.cmdline(cmdtype: string, config: cmp.ConfigSchema)` ``` -------------------------------- ### Create a Custom nvim-cmp Source Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Example demonstrating how to create a custom completion source for nvim-cmp. It includes required and optional methods for source behavior. ```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) ``` -------------------------------- ### Setup nvim-cmp with Rust and rust-tools.nvim Source: https://github.com/hrsh7th/nvim-cmp/wiki/Language-Server-Specific-Samples This configuration sets up nvim-cmp for autocompletion, integrating with rust-analyzer via rust-tools.nvim. It includes mappings for completion, documentation scrolling, and snippet expansion. Ensure packer.nvim and other listed plugins are installed. ```lua vim.opt.completeopt = "menu,menuone,noinsert" require("packer").startup({{ { "wbthomason/packer.nvim" }, { "hrsh7th/nvim-cmp" }, { "hrsh7th/cmp-buffer" }, { "hrsh7th/cmp-nvim-lua" }, { "hrsh7th/cmp-nvim-lsp" }, { "hrsh7th/cmp-nvim-lsp-signature-help" }, { "hrsh7th/cmp-path" }, { "neovim/nvim-lspconfig" }, { "L3MON4D3/LuaSnip" }, { "saadparwaiz1/cmp_luasnip" }, { "simrat39/rust-tools.nvim" }, }}, config = {{}})` -- Setup cmp local cmp = require("cmp") cmp.setup({ mapping = cmp.mapping.preset.insert({ -- Preset: ^n, ^p, ^y, ^e, you know the drill.. [""] = cmp.mapping.scroll_docs(-4), [""] = cmp.mapping.scroll_docs(4), }), snippet = { expand = function(args) require("luasnip").lsp_expand(args.body) end, }, sources = cmp.config.sources({ { name = "nvim_lsp" }, { name = "nvim_lsp_signature_help" }, { name = "nvim_lua" }, { name = "luasnip" }, { name = "path" }, }, { { name = "buffer", keyword_length = 3 }, }), }) -- Setup buffer-local keymaps / options for LSP buffers local capabilities = require("cmp_nvim_lsp").default_capabilities() local lsp_attach = function(client, buf) -- Example maps, set your own with vim.api.nvim_buf_set_keymap(buf, "n", , , { desc = }) -- or a plugin like which-key.nvim -- -- "K" vim.lsp.buf.hover "Hover Info" -- "qf" vim.lsp.diagnostic.setqflist "Quickfix Diagnostics" -- "[d" vim.diagnostic.goto_prev "Previous Diagnostic" -- "]d" vim.diagnostic.goto_next "Next Diagnostic" -- "e" vim.diagnostic.open_float "Explain Diagnostic" -- "ca" vim.lsp.buf.code_action "Code Action" -- "cr" vim.lsp.buf.rename "Rename Symbol" -- "fs" vim.lsp.buf.document_symbol "Document Symbols" -- "fS" vim.lsp.buf.workspace_symbol "Workspace Symbols" -- "gq" vim.lsp.buf.formatting_sync "Format File" vim.api.nvim_buf_set_option(buf, "formatexpr", "v:lua.vim.lsp.formatexpr()") vim.api.nvim_buf_set_option(buf, "omnifunc", "v:lua.vim.lsp.omnifunc") vim.api.nvim_buf_set_option(buf, "tagfunc", "v:lua.vim.lsp.tagfunc") end -- Setup rust_analyzer via rust-tools.nvim require("rust-tools").setup({ server = { capabilities = capabilities, on_attach = lsp_attach, } }) -- Keymaps for Luasnip local ls = require("luasnip") vim.keymap.set({ "i", "s" }, "", function() if ls.expand_or_jumpable() then ls.expand_or_jump() end end, { silent = true }) vim.keymap.set({ "i", "s" }, "", function() if ls.jumpable(-1) then ls.jump(-1) end end, { silent = true }) vim.keymap.set("i", "", function() if ls.choice_active() then ls.change_choice(1) end end) ``` -------------------------------- ### nvim-cmp Command-line Setup Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Configures nvim-cmp for command-line completion using '/' and ':'. The '/' command-line uses the 'buffer' source, while ':' is left for further configuration. ```lua -- `/` cmdline setup. cmp.setup.cmdline('/', { mapping = cmp.mapping.preset.cmdline(), sources = { { name = 'buffer' } } }) -- `:` cmdline setup. cmp.setup.cmdline(':', { ``` -------------------------------- ### Install Plugins with vim-plug Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt This snippet shows how to install nvim-cmp and its related plugins using vim-plug. Ensure you have a snippet engine configured if needed. ```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 ``` -------------------------------- ### Recommended nvim-cmp Configuration with vim-plug Source: https://github.com/hrsh7th/nvim-cmp/blob/main/README.md This configuration uses vim-plug to install nvim-cmp and its associated plugins. It sets up completion sources and mappings for insert mode. Ensure you have the specified snippet engine installed and configured. ```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 ultisnips users. " Plug 'SirVer/ultisnips' " Plug 'quangnguyen30192/cmp-nvim-ultisnips' " For snippy users. " Plug 'dcampos/nvim-snippy' " Plug 'dcampos/cmp-snippy' call plug#end() lua <'] = cmp.mapping.scroll_docs(-4), [''] = cmp.mapping.scroll_docs(4), [''] = cmp.mapping.complete(), [''] = cmp.mapping.abort(), [''] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. }), sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'vsnip' }, -- For vsnip users. -- { name = 'luasnip' }, -- For luasnip users. -- { name = 'ultisnips' }, -- For ultisnips users. -- { name = 'snippy' }, -- For snippy users. }, { { name = 'buffer' }, }) }) -- To use git you need to install the plugin petertriho/cmp-git and uncomment lines below -- Set configuration for specific filetype. --[[ cmp.setup.filetype('gitcommit', { sources = cmp.config.sources({ { name = 'git' }, }, { { name = 'buffer' }, }) }) require("cmp_git").setup() ]]-- -- Use buffer source for `/` and `?` (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline({ '/', '?' }, { mapping = cmp.mapping.preset.cmdline(), sources = { { name = 'buffer' } } }) -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline(':', { mapping = cmp.mapping.preset.cmdline(), sources = cmp.config.sources({ { name = 'path' } }, { { name = 'cmdline' } }), matching = { disallow_symbol_nonprefix_matching = false } }) -- Set up lspconfig. local capabilities = require('cmp_nvim_lsp').default_capabilities() -- Replace with each lsp server you've enabled. vim.lsp.config('', { capabilities = capabilities }) vim.lsp.enable('') EOF ``` -------------------------------- ### Setup Commandline Completion Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Configures nvim-cmp for command-line completions, including path and cmdline sources. It also sets up lspconfig for language server integration. ```lua 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%) ``` -------------------------------- ### Integrate lspkind-nvim for Icons Source: https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance Set up nvim-cmp to use lspkind-nvim for displaying fancy icons with completion items. Requires lspkind-nvim to be installed. ```lua local cmp = require('cmp') local lspkind = require('lspkind') cmp.setup { formatting = { format = lspkind.cmp_format(), }, } ``` -------------------------------- ### Configure LSP Capabilities with cmp_nvim_lsp Source: https://context7.com/hrsh7th/nvim-cmp/llms.txt Pass LSP capabilities to language servers for richer completion responses. This example registers capabilities for multiple servers and shows how to disable the completionProvider for a specific server. ```lua local lsp_caps = require('cmp_nvim_lsp').default_capabilities() -- Register capabilities for every language server you use local servers = { 'lua_ls', 'pyright', 'ts_ls', 'rust_analyzer', 'clangd' } for _, server in ipairs(servers) do vim.lsp.config(server, { capabilities = lsp_caps }) vim.lsp.enable(server) end -- Disable completionProvider for a specific server (e.g., to use another source) vim.lsp.config('ts_ls', { capabilities = lsp_caps, on_attach = function(client) client.server_capabilities.completionProvider = false end, }) ``` -------------------------------- ### nvim-cmp Global Setup Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Configures nvim-cmp globally, including snippet expansion, window borders, key mappings, and sources. Requires a snippet engine like vsnip, luasnip, or native Neovim snippets. ```lua local cmp = require'cmp' -- 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({ [''] = cmp.mapping.scroll_docs(-4), [''] = cmp.mapping.scroll_docs(4), [''] = cmp.mapping.complete(), [''] = 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' }, }) }) ``` -------------------------------- ### Lazy Loading nvim-cmp with Cmdline Event Source: https://github.com/hrsh7th/nvim-cmp/wiki/Example-mappings Example configuration for Lazy.nvim to load nvim-cmp, ensuring the 'CmdlineEnter' event is included for proper command-line completion functionality. ```lua { "hrsh7th/nvim-cmp", event = { "InsertEnter", "CmdlineEnter" }, -- Rest of your plugin spec }, ``` -------------------------------- ### Configure nvim-cmp with Go (gopls) Source: https://github.com/hrsh7th/nvim-cmp/wiki/Language-Server-Specific-Samples This snippet shows the setup for nvim-cmp, including mappings for Tab and Shift-Tab, and integration with nvim-lspconfig for Go development using gopls. It configures specific gopls settings and enables placeholder support. ```lua require('packer').startup(function(use) --packer use 'wbthomason/packer.nvim' --lsp use 'neovim/nvim-lspconfig' --auto complete use 'hrsh7th/cmp-nvim-lsp' use 'hrsh7th/cmp-buffer' use 'hrsh7th/cmp-path' use 'hrsh7th/cmp-cmdline' use 'hrsh7th/nvim-cmp' -- use 'hrsh7th/cmp-vsnip' use 'hrsh7th/vim-vsnip' vim.opt.completeopt = { "menu", "menuone", "noselect" } end) 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 local cmp = require('cmp') cmp.setup({ snippet = { expand = function(args) vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users. end, }, mapping = { -- [''] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. [""] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif vim.fn["vsnip#available"](1) == 1 then feedkey("(vsnip-expand-or-jump)", "") elseif has_words_before() then cmp.complete() else fallback() -- The fallback function sends a already mapped key. In this case, it's probably ``. end end, { "i", "s" }), [""] = cmp.mapping(function() if cmp.visible() then cmp.select_prev_item() elseif vim.fn["vsnip#jumpable"](-1) == 1 then feedkey("(vsnip-jump-prev)", "") end end, { "i", "s" }), }, sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'vsnip' }, -- For vsnip users. }, { { name = 'buffer' }, }) }) local capabilities = require('cmp_nvim_lsp').default_capabilities() --nvim-cmp local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') end -- Setup lspconfig. local nvim_lsp = require('lspconfig') -- setup languages -- GoLang vim_lsp['gopls'].setup{ cmd = {'gopls'}, -- on_attach = on_attach, capabilities = capabilities, settings = { gopls = { experimentalPostfixCompletions = true, analyses = { unusedparams = true, shadow = true, }, staticcheck = true, }, }, init_options = { usePlaceholders = true, } } ``` -------------------------------- ### Customize Completion Menu Appearance with formatting.format Source: https://context7.com/hrsh7th/nvim-cmp/llms.txt Hook into `formatting.format` to modify how completion entries are rendered. This example prepends kind icons and tags the source name in the menu column. ```lua local cmp = require('cmp') local kind_icons = { Text = "", Method = "󰆧", Function = "󰊕", Constructor = "", Field = "󰇽", Variable = "󰂡", Class = "󰠱", Interface = "", Module = "", Property = "󰜢", Unit = "", Value = "󰎠", Enum = "", Keyword = "󰌋", Snippet = "", Color = "󰏘", File = "󰈙", Reference = "", Folder = "󰉋", EnumMember = "", Constant = "󰏿", Struct = "", Event = "", Operator = "󰆕", TypeParameter = "󰅲", } cmp.setup({ formatting = { expandable_indicator = true, fields = { 'abbr', 'kind', 'menu' }, format = function(entry, vim_item) -- Prepend kind icon vim_item.kind = string.format('%s %s', kind_icons[vim_item.kind] or '', vim_item.kind) -- Tag the source name in the menu column vim_item.menu = ({ nvim_lsp = '[LSP]', luasnip = '[Snip]', buffer = '[Buf]', path = '[Path]', })[entry.source.name] or entry.source.name return vim_item end, }, }) ``` -------------------------------- ### Conditionally Add Sources Based on Buffer Size Source: https://github.com/hrsh7th/nvim-cmp/wiki/Advanced-techniques Dynamically configure nvim-cmp sources using `cmp.setup.buffer` within an `BufReadPre` autocmd. This example prevents adding the 'treesitter' source for large files to improve performance. ```lua -- default sources for all buffers local default_cmp_sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'nvim_lsp_signature_help' }, }, { { name = 'vsnip' }, { name = 'path' } }) -- If a file is too large, I don't want to add to it's cmp sources treesitter, see: -- https://github.com/hrsh7th/nvim-cmp/issues/1522 vim.api.nvim_create_autocmd('BufReadPre', { callback = function(t) local sources = default_cmp_sources if not bufIsBig(t.buf) then sources[#sources+1] = {name = 'treesitter', group_index = 2} end cmp.setup.buffer { sources = sources } end }) ``` ```lua bufIsBig = function(bufnr) local max_filesize = 100 * 1024 -- 100 KB local ok, stats = pcall(vim.loop.fs_stat, vim.api.nvim_buf_get_name(bufnr)) if ok and stats and stats.size > max_filesize then return true else return false end end ``` -------------------------------- ### Integrate nvim-cmp with copilot.vim Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Manage copilot.vim's key mappings and features within nvim-cmp's configuration. This example disables copilot.vim's tab fallback and integrates its accept feature. ```vim let g:copilot_no_tab_map = v:true imap (vimrc:copilot-dummy-map) copilot#Accept("\") ``` ```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. } } ``` -------------------------------- ### cmp.setup.cmdline(cmdtype, config) Source: https://context7.com/hrsh7th/nvim-cmp/llms.txt Registers a separate completion configuration for Neovim command-line modes. `cmdtype` maps to `:h getcmdtype()`: use `':'` for Ex commands, `'/'` and `'?'` for search. ```APIDOC ## `cmp.setup.cmdline(cmdtype, config)` — command-line completion Registers a separate completion configuration for Neovim command-line modes. `cmdtype` maps to `:h getcmdtype()`: use `':'` for Ex commands, `'/'` and `'?'` for search. ### Example Usage: ```lua local cmp = require('cmp') -- Search forward/backward: complete from buffer words cmp.setup.cmdline({ '/', '?' }, { mapping = cmp.mapping.preset.cmdline(), sources = { { name = 'buffer' }, }, }) -- Ex command line: paths first, then cmdline history cmp.setup.cmdline(':', { mapping = cmp.mapping.preset.cmdline(), sources = cmp.config.sources({ { name = 'path' }, }, { { name = 'cmdline' }, }), matching = { disallow_symbol_nonprefix_matching = false }, -- Disable for IncRename and similar interactive commands enabled = function() local disabled_cmds = { IncRename = true } local cmd = vim.fn.getcmdline():match('%S+') return not disabled_cmds[cmd] or cmp.close() end, }) ``` ``` -------------------------------- ### cmp.setup(config) Source: https://context7.com/hrsh7th/nvim-cmp/llms.txt Initializes nvim-cmp with a global configuration. This function must be called once during Neovim startup and accepts a deeply-merged Lua configuration table to control all behavioral aspects of the completion engine. ```APIDOC ## cmp.setup(config: cmp.ConfigSchema) ### Description Initializes nvim-cmp with a global configuration. All options can be overridden per-filetype or per-buffer later. Must be called once during Neovim startup. The `snippet.expand` field is required; every other field has a sensible default. ### Method `cmp.setup(config)` ### Parameters #### Request Body - **config** (cmp.ConfigSchema) - Required - A Lua table containing the configuration options for nvim-cmp. - **snippet** (table) - Required - Configuration for the snippet engine. - **expand** (function) - Required - A function that expands snippets. Example: `function(args) vim.snippet.expand(args.body) end`. - **performance** (table) - Optional - Performance tuning options. - **debounce** (number) - Optional - Groups completions from sources (milliseconds). - **throttle** (number) - Optional - Delay before filtering/displaying (milliseconds). - **fetching_timeout** (number) - Optional - Wait for highest-priority source (milliseconds). - **max_view_entries** (number) - Optional - Cap visible candidates. - **enabled** (function) - Optional - A function that returns a boolean indicating whether completion should be enabled. - **mapping** (table) - Optional - Key mappings for completion interactions. Can use `cmp.mapping.preset.insert()`. - **sources** (table) - Optional - A list of completion sources in priority order. ### Request Example ```lua local cmp = require('cmp') cmp.setup({ snippet = { expand = function(args) vim.snippet.expand(args.body) end, }, performance = { debounce = 60, throttle = 30, fetching_timeout = 500, max_view_entries = 200, }, enabled = function() local buftype = vim.api.nvim_get_option_value('buftype', { buf = 0 }) return buftype ~= 'prompt' and vim.fn.reg_recording() == '' and vim.fn.reg_executing() == '' end, mapping = cmp.mapping.preset.insert({ [''] = cmp.mapping.scroll_docs(-4), [''] = cmp.mapping.scroll_docs(4), [''] = cmp.mapping.complete(), [''] = cmp.mapping.abort(), [''] = cmp.mapping.confirm({ select = true }), }), sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'luasnip' }, }, { { name = 'buffer' }, { name = 'path' }, }), }) ``` ``` -------------------------------- ### Highlighting Custom Item Kind Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Example of how to override the highlight group for a specific completion item kind, such as 'Method'. ```vim highlight CmpItemKindMethod guibg=NONE guifg=Orange ``` -------------------------------- ### Configure Command-Line Completion for Search Source: https://context7.com/hrsh7th/nvim-cmp/llms.txt Sets up completion for search commands ('/' and '?') using buffer words. Requires the 'buffer' source. ```lua local cmp = require('cmp') -- Search forward/backward: complete from buffer words cmp.setup.cmdline({ '/', '?' }, { mapping = cmp.mapping.preset.cmdline(), sources = { { name = 'buffer' }, }, }) ``` -------------------------------- ### Navigate Completion Menu with cmp.select_next_item/cmp.select_prev_item Source: https://context7.com/hrsh7th/nvim-cmp/llms.txt Configure keybindings to move through the completion menu. Use `behavior = cmp.SelectBehavior.Select` for highlighting and `count` for page-up/page-down. ```lua local cmp = require('cmp') cmp.setup({ mapping = { [''] = cmp.mapping.select_next_item({ behavior = cmp.SelectBehavior.Select }), [''] = cmp.mapping.select_prev_item({ behavior = cmp.SelectBehavior.Select }), -- Page down / page up through a large list [''] = cmp.mapping.select_next_item({ count = 8 }), [''] = cmp.mapping.select_prev_item({ count = 8 }), }, }) ``` -------------------------------- ### Filter LSP Entries by Kind Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Use the entry_filter to hide specific completion items from a source. This example hides entries of kind 'Text' from the nvim_lsp source. ```lua { name = 'nvim_lsp', entry_filter = function(entry, ctx) return require('cmp.types').lsp.CompletionItemKind[entry:get_kind()] ~= 'Text' end } ``` -------------------------------- ### Configure Command-Line Completion for Ex Commands Source: https://context7.com/hrsh7th/nvim-cmp/llms.txt Sets up completion for Ex commands (':') prioritizing paths, then command-line history. Includes a custom 'enabled' function to disable for specific interactive commands like IncRename. ```lua local cmp = require('cmp') -- Ex command line: paths first, then cmdline history cmp.setup.cmdline(':', { mapping = cmp.mapping.preset.cmdline(), sources = cmp.config.sources({ { name = 'path' }, }, { { name = 'cmdline' }, }), matching = { disallow_symbol_nonprefix_matching = false }, -- Disable for IncRename and similar interactive commands enabled = function() local disabled_cmds = { IncRename = true } local cmd = vim.fn.getcmdline():match('%S+') return not disabled_cmds[cmd] or cmp.close() end, }) ``` -------------------------------- ### Enable Near Cursor Menu Direction Source: https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance Configure the custom completion menu to display entries starting from the cursor's position, useful when the menu opens above the cursor. ```lua view = { entries = {name = 'custom', selection_order = 'near_cursor' } }, ``` -------------------------------- ### Configure Wildmenu for Cmdline Source: https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance Set up the 'wildmenu' type for the completion menu in command-line mode, specifying a separator for items. ```lua cmp.setup.cmdline('/', { view = { entries = {name = 'wildmenu', separator = '|' } }, }) ``` -------------------------------- ### Configure Path and Cmdline Sources for ':' Command Source: https://github.com/hrsh7th/nvim-cmp/wiki/Example-mappings Set up the command-line completion for the ':' command to use both 'path' and 'cmdline' sources. This provides autocompletion for file paths and command-line commands. ```lua -- Use cmdline & path source for ':' cmp.setup.cmdline(':', { completion = { autocomplete = false }, sources = cmp.config.sources({ { name = 'path' } }, { { name = 'cmdline' } }) }) ``` -------------------------------- ### Configure Ultisnips with nvim-cmp Source: https://github.com/hrsh7th/nvim-cmp/wiki/Example-mappings This configuration sets up Ultisnips as the snippet engine for nvim-cmp. It defines triggers for expanding snippets and jumping between snippet placeholders. Ensure Ultisnips and vim-snippets are installed. ```lua -- within packer init {{{use {'SirVer/ultisnips', requires = {{'honza/vim-snippets', rtp = '.'}}, config = function() vim.g.UltiSnipsExpandTrigger = '(ultisnips_expand)' vim.g.UltiSnipsJumpForwardTrigger = '(ultisnips_jump_forward)' vim.g.UltiSnipsJumpBackwardTrigger = '(ultisnips_jump_backward)' vim.g.UltiSnipsListSnippets = '' vim.g.UltiSnipsRemoveSelectModeMappings = 0 end } -- }}} ``` ```lua local t = function(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end local cmp = require('cmp') cmp.setup { snippet = { expand = function(args) vim.fn["UltiSnips#Anon"](args.body) end }, -- ... Your other configuration ... mapping = { [""] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Insert }) else cmp.complete() end end, i = function(fallback) if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Insert }) elseif vim.fn["UltiSnips#CanJumpForwards"]() == 1 then vim.api.nvim_feedkeys(t("(ultisnips_jump_forward)"), 'm', true) else fallback() end end, s = function(fallback) if vim.fn["UltiSnips#CanJumpForwards"]() == 1 then vim.api.nvim_feedkeys(t("(ultisnips_jump_forward)"), 'm', true) else fallback() end end }), [""] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Insert }) else cmp.complete() end end, i = function(fallback) if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Insert }) elseif vim.fn["UltiSnips#CanJumpBackwards"]() == 1 then return vim.api.nvim_feedkeys( t("(ultisnips_jump_backward)"), 'm', true) else fallback() end end, s = function(fallback) if vim.fn["UltiSnips#CanJumpBackwards"]() == 1 then return vim.api.nvim_feedkeys( t("(ultisnips_jump_backward)"), 'm', true) else fallback() end end }), [''] = cmp.mapping(cmp.mapping.select_next_item({ behavior = cmp.SelectBehavior.Select }), {'i'}) [''] = cmp.mapping(cmp.mapping.select_prev_item({ behavior = cmp.SelectBehavior.Select }), {'i'}) [''] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t(''), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), [''] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t(''), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), [''] = cmp.mapping(cmp.mapping.scroll_docs(-4), {'i', 'c'}) [''] = cmp.mapping(cmp.mapping.scroll_docs(4), {'i', 'c'}) [''] = cmp.mapping(cmp.mapping.complete(), {'i', 'c'}) } } ``` -------------------------------- ### Configure lspkind-nvim with Mode and Menu Source: https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance Customize lspkind-nvim integration to show item kind names and specify sources for completion items. ```lua formatting = { format = lspkind.cmp_format({ mode = "symbol_text", menu = ({ buffer = "[Buffer]", nvim_lsp = "[LSP]", luasnip = "[LuaSnip]", nvim_lua = "[Lua]", latex_symbols = "[Latex]", }) }), }, ``` -------------------------------- ### Disable Language Server Completion Provider Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Disables a specific language server's completion provider by setting `completionProvider` to `false` in its `lspconfig` setup. This is useful for fine-grained control over completions. ```lua lspconfig[%SERVER_NAME%].setup { on_attach = function(client) client.server_capabilities.completionProvider = false end } ``` -------------------------------- ### Context-Aware Completion Toggling Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Use `cmp.config.context` to conditionally enable or disable completion based on the current syntax group. This example disables completion when the cursor is within a 'Comment' syntax group. ```lua cmp.setup { enabled = function() -- disable completion if the cursor is `Comment` syntax group. return not cmp.config.context.in_syntax_group('Comment') end } ``` -------------------------------- ### Configure Sources with Helper Source: https://github.com/hrsh7th/nvim-cmp/blob/main/doc/cmp.txt Use the cmp.config.sources helper function to configure multiple sources, maintaining their defined order. ```lua cmp.setup { sources = cmp.config.sources({ { name = 'nvim_lsp' }, }, { { name = 'buffer' }, }) } ``` -------------------------------- ### Define VS Code Codicon Mappings Source: https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance Define a Lua table mapping nvim-cmp kind names to VS Code Codicon characters for display in the completion menu. Ensure the 'codicon.ttf' font is installed. ```lua local cmp_kinds = { Text = ' ', Method = ' ', Function = ' ', Constructor = ' ', Field = ' ', Variable = ' ', Class = ' ', Interface = ' ', Module = ' ', Property = ' ', Unit = ' ', Value = ' ', Enum = ' ', Keyword = ' ', Snippet = ' ', Color = ' ', File = ' ', Reference = ' ', Folder = ' ', EnumMember = ' ', Constant = ' ', Struct = ' ', Event = ' ', Operator = ' ', TypeParameter = ' ', } ``` -------------------------------- ### Configure Buffer Source for '/' Command Source: https://github.com/hrsh7th/nvim-cmp/wiki/Example-mappings Set up the command-line completion for the '/' command to use the buffer source. This allows autocompletion of words present in the current buffer. ```lua -- Use buffer source for `/`. cmp.setup.cmdline('/', { completion = { autocomplete = false }, sources = { -- { name = 'buffer' } { name = 'buffer', opts = { keyword_pattern = [=[[^[:blank:]].*]=] } } } }) ``` -------------------------------- ### cmp.setup.filetype(filetype, config) Source: https://context7.com/hrsh7th/nvim-cmp/llms.txt Applies a configuration only when the current buffer's filetype matches. This is useful for customizing completion sources or behavior for specific file types like gitcommit or markdown. ```APIDOC ## cmp.setup.filetype(filetype, config) ### Description Applies a configuration only when the current buffer's filetype matches. Useful for giving markdown, gitcommit, or help buffers different source lists without affecting every buffer. ### Method `cmp.setup.filetype(filetype, config)` ### Parameters #### Path Parameters - **filetype** (string or table) - Required - The filetype(s) to apply the configuration to. Can be a single string or a table of strings. - **config** (table) - Required - A Lua table containing the configuration options for this specific filetype. - **sources** (table) - Optional - A list of completion sources for this filetype. - **window** (table) - Optional - Window-specific configurations. - **documentation** (function) - Optional - Configuration for the documentation window. Can be `cmp.config.disable`. ### Request Example ```lua local cmp = require('cmp') -- Git commit messages: Git log + buffer text only cmp.setup.filetype('gitcommit', { sources = cmp.config.sources({ { name = 'git' }, }, { { name = 'buffer' }, }), }) -- Markdown / help: path + buffer, no LSP noise cmp.setup.filetype({ 'markdown', 'help' }, { sources = { { name = 'path' }, { name = 'buffer' }, }, window = { documentation = cmp.config.disable, }, }) ``` ```