Autocompletion & Snippets
nvim-cmp Setup
-- lua/plugins/completion.lua
return {
'hrsh7th/nvim-cmp',
event = 'InsertEnter',
dependencies = {
-- Snippet engine
'L3MON4D3/LuaSnip',
'saadparwaiz1/cmp_luasnip',
-- Completion sources
'hrsh7th/cmp-nvim-lsp', -- LSP completions
'hrsh7th/cmp-buffer', -- Buffer words
'hrsh7th/cmp-path', -- File paths
'hrsh7th/cmp-cmdline', -- Command-line completions
-- Snippet collection
'rafamadriz/friendly-snippets',
},
config = function()
local cmp = require('cmp')
local luasnip = require('luasnip')
-- Load friendly-snippets
require('luasnip.loaders.from_vscode').lazy_load()
cmp.setup({
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
mapping = cmp.mapping.preset.insert({
['<C-b>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
['<C-Space>'] = cmp.mapping.complete(),
['<C-e>'] = cmp.mapping.abort(),
['<CR>'] = cmp.mapping.confirm({ select = true }),
-- Tab to cycle through completions
['<Tab>'] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
else
fallback()
end
end, { 'i', 's' }),
['<S-Tab>'] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, { 'i', 's' }),
}),
sources = cmp.config.sources({
{ name = 'nvim_lsp' }, -- LSP (highest priority)
{ name = 'luasnip' }, -- Snippets
{ name = 'path' }, -- File paths
}, {
{ name = 'buffer' }, -- Buffer words (fallback)
}),
formatting = {
format = function(entry, vim_item)
-- Show source name
vim_item.menu = ({
nvim_lsp = '[LSP]',
luasnip = '[Snip]',
buffer = '[Buf]',
path = '[Path]',
})[entry.source.name]
return vim_item
end,
},
})
-- Completions for command-line
cmp.setup.cmdline(':', {
mapping = cmp.mapping.preset.cmdline(),
sources = {
{ name = 'cmdline' },
{ name = 'path' },
},
})
-- Completions for search
cmp.setup.cmdline('/', {
mapping = cmp.mapping.preset.cmdline(),
sources = {
{ name = 'buffer' },
},
})
end,
}Key Bindings Reference
Key
Action
LuaSnip: Snippets
Using Snippets
Creating Custom Snippets
Loading VS Code Snippets
Completion Sources
Source
Plugin
Description
Summary
Exercises
Last updated
Was this helpful?