用lazyvim管理nvim-cmp 时设置tab键和shift-tab键上下选择补全项,enter键选中补全项
将下属代码填到~/.config/nvim/lua/plugins/nvim-cmp.lua
return {
"hrsh7th/nvim-cmp",
dependencies = {
"L3MON4D3/LuaSnip", -- 关键修正:必须显式声明依赖 LuaSnip
"hrsh7th/cmp-emoji",
},
---@param opts cmp.ConfigSchema
opts = function(_, opts)
local cmp = require("cmp")
local luasnip = require("luasnip") -- 有了上面的依赖,这里就不会报错了
-- 辅助函数:检查光标前是否有文字
local has_words_before = function()
unpack = unpack or table.unpack
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
opts.mapping = vim.tbl_extend("force", opts.mapping, {
-- TAB 键逻辑
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
cmp.complete()
else
fallback()
end
end, { "i", "s" }),
-- SHIFT+TAB 键逻辑
["<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" }),
-- ENTER 键逻辑
["<CR>"] = cmp.mapping.confirm({ select = true }),
})
end,
}