hrsh7th / nvim-cmp

A completion plugin for neovim coded in Lua.
MIT License
7.99k stars 397 forks source link

[SOLVED] the custom keybinds are not working (NeoVIm, with Lazy.nvim plugin manager). #2059

Closed MiraiMindz closed 1 week ago

MiraiMindz commented 1 week ago

FAQ

Announcement

Minimal reproducible full config

if has('vim_starting')
  set encoding=utf-8
endif
scriptencoding utf-8

if &compatible
  set nocompatible
endif

let s:plug_dir = expand('/tmp/plugged/vim-plug')
if !filereadable(s:plug_dir .. '/plug.vim')
  execute printf('!curl -fLo %s/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim', s:plug_dir)
end

execute 'set runtimepath+=' . s:plug_dir
call plug#begin(s:plug_dir)
Plug 'hrsh7th/nvim-cmp'
Plug 'hrsh7th/cmp-buffer'
Plug 'hrsh7th/cmp-nvim-lsp'
Plug 'hrsh7th/vim-vsnip'
Plug 'neovim/nvim-lspconfig'
Plug 'hrsh7th/cmp-path',
Plug 'L3MON4D3/LuaSnip',
Plug 'saadparwaiz1/cmp_luasnip',
Plug 'rafamadriz/friendly-snippets',
Plug 'onsails/lspkind.nvim'
call plug#end()
PlugInstall | quit

" Setup global configuration. More on configuration below.
lua << EOF
local cmp = require("cmp")
        local luasnipc = require("luasnip")
        local lspkindc = require("lspkind")

        require("luasnip.loaders.from_vscode").lazy_load()
        cmp.setup({
            completion = {
                completeopt = "menu,menuone,preview,noselect",
            },
            snippet = {
                expand = function(args) 
                    luasnipc.lsp_expand(args.body) 
                end,
            },
            mappings = cmp.mapping.preset.insert({
                ['<Down>'] = function(fallback)
                    if cmp.visible() then
                        cmp.select_next_item()
                    else
                        fallback()
                    end
                end,
                ['<Up>'] = function(fallback)
                    if cmp.visible() then
                        cmp.select_prev_item()
                    else
                        fallback()
                    end
                end,
                ["<CR>"] = cmp.mapping.confirm({
                    behavior = cmp.ConfirmBehavior.Insert,
                    select = true
                }),
                ["<C-Up>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
                ["<C-Down>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
                ["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
                ["<Esc>"] = cmp.mapping {
                    i = cmp.mapping.abort(),
                    c = cmp.mapping.close(),
                },
                ["<C-l>"] = cmp.mapping(function()
                    if luasnip.expand_or_locally_jumpable then
                        luasnip.expand_or_jump()
                    end
                end, { "i", "s" }),
                ["<C-h>"] = cmp.mapping(function()
                    if luasnip.locally_jumpable(-1) then
                        luasnip.jump(-1)
                    end
                end, { "i", "s" }),
            }),

            sources = cmp.config.sources({
                { name = "nvim_lsp" },
                { name = "luasnip" },
                { name = "buffer" },
                { name = "path" },
            }),

            formatting = {
                format = lspkindc.cmp_format({
                    maxwidth = 50,
                    ellipsis_char = "...",
                }),
            },
        })
EOF

lua << EOF
local capabilities = require('cmp_nvim_lsp').default_capabilities()

require'lspconfig'.cssls.setup {
  capabilities = capabilities,
}
EOF

Description

https://github.com/user-attachments/assets/72de1f2b-ef07-4a30-b8f6-129445b7d6d9

This video show what is happening.

I've used the Minimal reproducible full config too, and it doesn't work as well, both the default keys and my custom defined keys don't work, but the menu shows up.

I don't how to fix this bc I've came back to neovim after a while and everything I knew about nvim-cmp doesn't seem to be working.

I just want to use the <Up>/<Down> keys to select the entry and use <Tab>/<CR>(Enter) to select it.

this is the output of nvim -V1 -v:

NVIM v0.11.0-dev-941+gcd8e15e337
Build type: Release
LuaJIT 2.1.1725453128

How could I fix this?

Steps to reproduce

just use this minimal lazy.nvim lua config, open a C source file and try to auto-complete something:

vim.g.mapleader = " "
vim.g.maplocalleader = "\\"

-- Bootstrap lazy.nvim
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not (vim.uv or vim.loop).fs_stat(lazypath) then
  local lazyrepo = "https://github.com/folke/lazy.nvim.git"
  local out = vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable", lazyrepo, lazypath })
  if vim.v.shell_error ~= 0 then
    vim.api.nvim_echo({
      { "Failed to clone lazy.nvim:\n", "ErrorMsg" },
      { out, "WarningMsg" },
      { "\nPress any key to exit..." },
    }, true, {})
    vim.fn.getchar()
    os.exit(1)
  end
end
vim.opt.rtp:prepend(lazypath)

-- Setup lazy.nvim
require("lazy").setup({
  spec = {
    {
        "nvim-treesitter/nvim-treesitter",
        build = ":TSUpdate",
        config = function () 
          local configs = require("nvim-treesitter.configs")

          configs.setup({
              ensure_installed = { "c", "lua", "vim", "vimdoc" },
              sync_install = true,
              highlight = { enable = true },
              indent = { enable = true },  
            })
        end
    },
    {
        "williamboman/mason.nvim",
        opts = {
            ui = {
                icons = {
                    package_installed = "✓",
                    package_pending = "➜",
                    package_uninstalled = "✗"
                }
            },
            ensure_installed = {
                "clangd",
                "clang-tidy",
            },
        },
    },
    {"williamboman/mason-lspconfig.nvim"},
    {
        "neovim/nvim-lspconfig",
        dependencies = {
            "williamboman/mason.nvim",
            "williamboman/mason-lspconfig.nvim"
        },
        config = function()
            require("mason").setup()
            require("mason-lspconfig").setup()
            -- I've opted for a manual configuration here to have more control
            -- of the lsps settings.
            require("lspconfig").clangd.setup({
                cmd = {
                    "clangd",
                    "--background-index",
                    "-j=8",
                    "--query-driver=/usr/bin/**/clang-*,/bin/clang,/bin/clang++,/usr/bin/gcc,/usr/bin/g++",
                    "--clang-tidy",
                    "--clang-tidy-checks=*",
                    "--all-scopes-completion",
                    "--cross-file-rename",
                    "--completion-style=detailed",
                    "--header-insertion-decorators",
                    "--header-insertion=iwyu",
                    "--pch-storage=memory",
                }
            })
        end,
    },
    {
        "mfussenegger/nvim-lint",
        event = {
            "BufReadPre",
            "BufNewFile",
        },
        config = function()
            nlint = require("lint")

            nlint.linters_by_ft = {
                c = { "cpplint" },
            }

            local nlint_augroup = vim.api.nvim_create_augroup("lint", { clear = true })

            vim.api.nvim_create_autocmd({ "BufEnter", "BufWritePost", "InsertLeave" }, {
                group = nlint_augroup,
                callback = function()
                    nlint.try_lint()
                end,
            })
        end,
    },
    {
        "stevearc/conform.nvim",
        event = {
            "BufReadPre",
            "BufNewFile",
        },
        config = function()
            local conformf = require("conform")

            conformf.setup({
                formatters_by_ft = {
                    c = { "clangd" },
                },
                format_on_save = {
                    timeout_ms = 500,
                    lsp_fallback = true,
                    async = false,
                },
            })

            vim.api.nvim_create_autocmd("BufWritePre", {
                callback = function(args)
                    require("conform").format({
                        bufnr = args.buf, 
                        timeout_ms = 500,
                        lsp_fallback = true,
                        async = false,
                    })
                end,
            })
        end,
    },
    {
        "hrsh7th/nvim-cmp",
        event = "InsertEnter",
        dependencies = {
            "hrsh7th/cmp-buffer",
            "hrsh7th/cmp-path",
            "L3MON4D3/LuaSnip",
            "saadparwaiz1/cmp_luasnip",
            "rafamadriz/friendly-snippets",
            "onsails/lspkind.nvim",
        },
        config = function()
            local cmp = require("cmp")
            local luasnipc = require("luasnip")
            local lspkindc = require("lspkind")

            require("luasnip.loaders.from_vscode").lazy_load()
            cmp.setup({
                completion = {
                    completeopt = "menu,menuone,preview,noselect",
                },
                snippet = {
                    expand = function(args) 
                        luasnipc.lsp_expand(args.body) 
                    end,
                },
                mappings = cmp.mapping.preset.insert({
                    ['<Down>'] = function(fallback)
                        if cmp.visible() then
                          cmp.select_next_item()
                        else
                          fallback()
                        end
                    end,
                    ['<Up>'] = function(fallback)
                        if cmp.visible() then
                          cmp.select_prev_item()
                        else
                          fallback()
                        end
                    end,
                    ["<CR>"] = cmp.mapping.confirm({
                        behavior = cmp.ConfirmBehavior.Insert,
                        select = true
                    }),
                    ["<C-Up>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
                    ["<C-Down>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
                    ["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
                    ["<Esc>"] = cmp.mapping {
                      i = cmp.mapping.abort(),
                      c = cmp.mapping.close(),
                    },
                    ["<C-l>"] = cmp.mapping(function()
                        if luasnip.expand_or_locally_jumpable then
                            luasnip.expand_or_jump()
                        end
                    end, { "i", "s" }),
                    ["<C-h>"] = cmp.mapping(function()
                        if luasnip.locally_jumpable(-1) then
                            luasnip.jump(-1)
                        end
                    end, { "i", "s" }),
                }),

                sources = cmp.config.sources({
                    { name = "nvim_lsp" },
                    { name = "luasnip" },
                    { name = "buffer" },
                    { name = "path" },
                }),

                formatting = {
                    format = lspkindc.cmp_format({
                        maxwidth = 50,
                        ellipsis_char = "...",
                    }),
                },
            })
        end,
    },
  },
  -- Configure any other settings here. See the documentation for more details.
  -- colorscheme that will be used when installing plugins.
  install = { },
  -- automatically check for plugin updates
  checker = { enabled = true },
})

vim.keymap.set("n", "<Esc>", "<cmd>nohlsearch<cr>", { desc = "Clears search highlight with ESC" })

Expected behavior

The autocompletion works as expected, with the defined keys.

Actual behavior

It's only showing the menu and is not navigating to the entries nor selecting them.

Additional context

here is my full config in a single lua file (Is kinda minimal tbh):

vim.g.mapleader = " "
vim.g.maplocalleader = "\\"

-- Ensures syntax is enabled
vim.cmd("syntax on")

-- Show relative line numbers
vim.opt.number = true
vim.opt.relativenumber = true
vim.opt.signcolumn = "number"
vim.wo.number = true

-- I do not have a nerd font.
vim.g.have_nerd_font = false

-- Enables the mouse
vim.opt.mouse = "a"

-- Disables showing the mode (because it's on the status line)
vim.opt.showmode = false

-- Sync OS & nvim clipboards
vim.opt.clipboard = "unnamedplus"

-- Set highlight on search
vim.o.hlsearch = false

-- Enable break indent
vim.o.breakindent = true

-- Case-insensitive searching UNLESS \C or capital in search
vim.o.ignorecase = true
vim.o.smartcase = true

-- Keep signcolumn on by default
vim.wo.signcolumn = "yes"

-- Decrease update time
vim.o.updatetime = 250
vim.o.timeoutlen = 300

-- Set completeopt to have a better completion experience
vim.o.completeopt = "menuone,noselect"

-- This enables 4 spaces tabs
vim.opt.tabstop = 4
vim.opt.softtabstop = 4
vim.opt.shiftwidth = 4
vim.opt.expandtab = true

-- Smart identation
vim.opt.smartindent = true

-- Enables SwapFiles
vim.opt.swapfile = true

-- Disables Backups
vim.opt.backup = false

-- Enables Undo-dir
vim.opt.undodir = os.getenv("HOME") .. "/.vim/undodir"
vim.opt.undofile = true

-- Enables incremental highlight
vim.opt.incsearch = true

-- Ensures that has at least 8 lines at bottom or top of screen.
vim.opt.scrolloff = 8
vim.opt.signcolumn = "yes"
vim.opt.isfname:append("@-@")

vim.opt.colorcolumn = "80,160"

-- Shows the command
vim.opt.showcmd = false

-- Remove bottom command line
vim.opt.cmdheight = 0

-- Auto Resizes window
vim.api.nvim_create_autocmd("VimResized", { pattern = "*", command = "tabdo wincmd =" })

-- Make the arrow keys go to next or previous line.
-- vim.cmd([[set whichwrap+=<,>,[,] ]])

-- This enables inlay_hints on LSP in case it fails to load on the plugin conf.
vim.g.inlay_hints_visible = true

-- Enables autosaving excluding certain buffer types
function Is_excluded_buffer(buftype)
    Autosave_excluded_buftypes = {
        "terminal",
        "nofile",
        "help",
        "quickfix",
        "nowrite",
        "acwrite",
    }

    for _, excluded_type in ipairs(Autosave_excluded_buftypes) do
        if buftype == excluded_type then
            return true
        end
    end
    return false
end

vim.cmd("set autowriteall")
vim.api.nvim_create_autocmd("TextChanged", {
    pattern = "<buffer>",
    callback = function()
        local buftype = vim.bo.buftype
        if not Is_excluded_buffer(buftype) then
            vim.cmd("silent write")
        end
    end,
})
vim.api.nvim_create_autocmd("TextChangedI", {
    pattern = "<buffer>",
    callback = function()
        local buftype = vim.bo.buftype
        if not Is_excluded_buffer(buftype) then
            vim.cmd("silent write")
        end
    end,
})

-- disables the tilde at the end of buffer
vim.opt.fillchars = { eob = " " }

-- Sync current directory and browsing directory
vim.g.netrw_browse_split = 0

-- Disables banner
vim.g.netrw_banner = 0

-- Sets the window to be 30% of screen
vim.g.netrw_winsize = 30

-- Changes the copy command to be recursive
vim.g.netrw_localcopydircmd = "cp -r"

-- Enable filetype plugins
vim.cmd("filetype plugin on")

-- Enables OmniFunction AutoComplete
vim.opt.omnifunc = "syntaxcomplete#Complete"

-- Enables blinking cursor in insert mode
vim.api.nvim_command("set guicursor+=a:blinkon1")

-- Enables current line number coloring
vim.opt.cursorline = true
vim.opt.cursorlineopt = "number"

-- Configure how new splits should be opened
vim.opt.splitright = true
vim.opt.splitbelow = true

-- Sets how neovim will show the spaces.
vim.opt.list = true
vim.opt.listchars = { tab = "> ", trail = "·", nbsp = "␣" }

-- Realtime substitution preview
vim.opt.inccommand = "split"

-- AUTOCOMMANDS

-- Highlight when yanking (copying) text
vim.api.nvim_create_autocmd("TextYankPost", {
    desc = "Highlight when yanking (copying) text",
    group = vim.api.nvim_create_augroup("kickstart-highlight-yank", { clear = true }),
    callback = function()
        vim.highlight.on_yank()
    end,
})

-- Bootstrap lazy.nvim
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not (vim.uv or vim.loop).fs_stat(lazypath) then
  local lazyrepo = "https://github.com/folke/lazy.nvim.git"
  local out = vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable", lazyrepo, lazypath })
  if vim.v.shell_error ~= 0 then
    vim.api.nvim_echo({
      { "Failed to clone lazy.nvim:\n", "ErrorMsg" },
      { out, "WarningMsg" },
      { "\nPress any key to exit..." },
    }, true, {})
    vim.fn.getchar()
    os.exit(1)
  end
end
vim.opt.rtp:prepend(lazypath)

-- Setup lazy.nvim
require("lazy").setup({
  spec = {
    {
        "nvim-treesitter/nvim-treesitter",
        build = ":TSUpdate",
        config = function () 
          local configs = require("nvim-treesitter.configs")

          configs.setup({
              ensure_installed = { "c", "lua", "vim", "vimdoc" },
              sync_install = true,
              highlight = { enable = true },
              indent = { enable = true },  
            })
        end
    },
    {
        "williamboman/mason.nvim",
        opts = {
            ui = {
                icons = {
                    package_installed = "✓",
                    package_pending = "➜",
                    package_uninstalled = "✗"
                }
            },
            ensure_installed = {
                "clangd",
                "clang-tidy",
            },
        },
    },
    {"williamboman/mason-lspconfig.nvim"},
    {
        "neovim/nvim-lspconfig",
        dependencies = {
            "williamboman/mason.nvim",
            "williamboman/mason-lspconfig.nvim"
        },
        config = function()
            require("mason").setup()
            require("mason-lspconfig").setup()
            -- I've opted for a manual configuration here to have more control
            -- of the lsps settings.
            require("lspconfig").clangd.setup({
                cmd = {
                    "clangd",
                    "--background-index",
                    "-j=8",
                    "--query-driver=/usr/bin/**/clang-*,/bin/clang,/bin/clang++,/usr/bin/gcc,/usr/bin/g++",
                    "--clang-tidy",
                    "--clang-tidy-checks=*",
                    "--all-scopes-completion",
                    "--cross-file-rename",
                    "--completion-style=detailed",
                    "--header-insertion-decorators",
                    "--header-insertion=iwyu",
                    "--pch-storage=memory",
                }
            })
        end,
    },
    {
        "mfussenegger/nvim-lint",
        event = {
            "BufReadPre",
            "BufNewFile",
        },
        config = function()
            nlint = require("lint")

            nlint.linters_by_ft = {
                c = { "cpplint" },
            }

            local nlint_augroup = vim.api.nvim_create_augroup("lint", { clear = true })

            vim.api.nvim_create_autocmd({ "BufEnter", "BufWritePost", "InsertLeave" }, {
                group = nlint_augroup,
                callback = function()
                    nlint.try_lint()
                end,
            })
        end,
    },
    {
        "stevearc/conform.nvim",
        event = {
            "BufReadPre",
            "BufNewFile",
        },
        config = function()
            local conformf = require("conform")

            conformf.setup({
                formatters_by_ft = {
                    c = { "clangd" },
                },
                format_on_save = {
                    timeout_ms = 500,
                    lsp_fallback = true,
                    async = false,
                },
            })

            vim.api.nvim_create_autocmd("BufWritePre", {
                callback = function(args)
                    require("conform").format({
                        bufnr = args.buf, 
                        timeout_ms = 500,
                        lsp_fallback = true,
                        async = false,
                    })
                end,
            })
        end,
    },
    {
        "hrsh7th/nvim-cmp",
        event = "InsertEnter",
        dependencies = {
            "hrsh7th/cmp-buffer",
            "hrsh7th/cmp-path",
            "L3MON4D3/LuaSnip",
            "saadparwaiz1/cmp_luasnip",
            "rafamadriz/friendly-snippets",
            "onsails/lspkind.nvim",
        },
        config = function()
            local cmp = require("cmp")
            local luasnipc = require("luasnip")
            local lspkindc = require("lspkind")

            require("luasnip.loaders.from_vscode").lazy_load()
            cmp.setup({
                completion = {
                    completeopt = "menu,menuone,preview,noselect",
                },
                snippet = {
                    expand = function(args) 
                        luasnipc.lsp_expand(args.body) 
                    end,
                },
                mappings = cmp.mapping.preset.insert({
                    ['<Down>'] = function(fallback)
                        if cmp.visible() then
                          cmp.select_next_item()
                        else
                          fallback()
                        end
                    end,
                    ['<Up>'] = function(fallback)
                        if cmp.visible() then
                          cmp.select_prev_item()
                        else
                          fallback()
                        end
                    end,
                    ["<CR>"] = cmp.mapping.confirm({
                        behavior = cmp.ConfirmBehavior.Insert,
                        select = true
                    }),
                    ["<C-Up>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
                    ["<C-Down>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
                    ["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
                    ["<Esc>"] = cmp.mapping {
                      i = cmp.mapping.abort(),
                      c = cmp.mapping.close(),
                    },
                    ["<C-l>"] = cmp.mapping(function()
                        if luasnip.expand_or_locally_jumpable then
                            luasnip.expand_or_jump()
                        end
                    end, { "i", "s" }),
                    ["<C-h>"] = cmp.mapping(function()
                        if luasnip.locally_jumpable(-1) then
                            luasnip.jump(-1)
                        end
                    end, { "i", "s" }),
                }),

                sources = cmp.config.sources({
                    { name = "nvim_lsp" },
                    { name = "luasnip" },
                    { name = "buffer" },
                    { name = "path" },
                }),

                formatting = {
                    format = lspkindc.cmp_format({
                        maxwidth = 50,
                        ellipsis_char = "...",
                    }),
                },
            })
        end,
    },
    {
        'stevearc/oil.nvim',
        dependencies = { "nvim-tree/nvim-web-devicons" },
        ---@module 'oil'
        ---@type oil.SetupOpts
        opts = {},
    },
    {
        'nvim-telescope/telescope.nvim',
        dependencies = { 'nvim-lua/plenary.nvim' },
        opts = {},
    },
  },
  -- Configure any other settings here. See the documentation for more details.
  -- colorscheme that will be used when installing plugins.
  install = { },
  -- automatically check for plugin updates
  checker = { enabled = true },
})

vim.keymap.set('n', '<C-f>', require('telescope.builtin').find_files, { desc = 'Telescope find files' })

-- Move focus to window
vim.keymap.set("n", "<A-Left>", "<C-w><C-h>", { desc = "Focus on the left window" })
vim.keymap.set("n", "<A-Right>", "<C-w><C-l>", { desc = "Focus on the right window" })
vim.keymap.set("n", "<A-Down>", "<C-w><C-j>", { desc = "Focus on the lower window" })
vim.keymap.set("n", "<A-Up>", "<C-w><C-k>", { desc = "Focus on the upper window" })

vim.keymap.set("n", "<Esc>", "<cmd>nohlsearch<cr>", { desc = "Clears search highlight with ESC" })

vim.keymap.set("n", "<C-e>", "<CMD>Oil<CR>", { desc = "Open parent directory" })

vim.cmd.colorscheme('habamax')
MiraiMindz commented 1 week ago

It was a typo, mappings should be mapping.

MiraiMindz commented 1 week ago

marking as solved