LSP (clangd) for Vim and Neovim + Copilot chat - MarekBykowski/readme GitHub Wiki

Overview

  • LSP (Language Server Protocol) – standard protocol between an editor and a language server.
  • clangd – LSP server for C/C++ (definitions, references, call hierarchy, diagnostics).
  • bear – records compiler flags from make into compile_commands.json, which clangd reads.
  • Vim uses the vim-lsp plugin as the LSP client; Neovim has an LSP client built in.
  • clangd 20+ is required for outgoing call hierarchy (gH); clangd 18 only supports incoming calls.

1. Install clangd and bear

Ubuntu:

sudo apt install -y clangd-20 bear

CentOS / Rocky / RHEL:

sudo dnf install -y epel-release          # bear is in EPEL
sudo dnf install -y clang-tools-extra bear
clangd --version                          # gH needs 20+

2. Generate compile_commands.json (once per project)

cd ~/repos/<project>                      # directory with the Makefile
make clean                                # bear only records files that actually get compiled
bear -- make                              # writes compile_commands.json
clangd --check=foo.c                      # optional: verify flags/headers are found

Re-run make clean && bear -- make when source files are added/removed or compiler flags change.

3. Vim (pathogen + vim-lsp)

git clone https://github.com/prabirshrestha/vim-lsp       ~/.vim/bundle/vim-lsp
git clone https://github.com/mattn/vim-lsp-settings       ~/.vim/bundle/vim-lsp-settings

Add to ~/.vimrc (full version with all mappings: .vimrc in this repo):

" Use clangd-20 if installed (Ubuntu), otherwise plain clangd (CentOS/RHEL)
let s:clangd = executable('clangd-20') ? 'clangd-20' : 'clangd'
let g:lsp_settings = {'clangd': {'cmd': [s:clangd, '--background-index']}}

nmap gd <plug>(lsp-definition)
nmap gr <plug>(lsp-references)
nmap gh <plug>(lsp-call-hierarchy-incoming)
nmap gH <plug>(lsp-call-hierarchy-outgoing)
nmap K  <plug>(lsp-hover)

Check: open a .c file and run :LspStatus → clangd: running.

For Copilot in Vim (inline suggestions only, no chat) see copilot.

4. Neovim (global install)

The apt package (0.9.x) is too old for Copilot Chat – use the official tarball:

curl -LO https://github.com/neovim/neovim/releases/latest/download/nvim-linux-x86_64.tar.gz
sudo rm -rf /opt/nvim-linux-x86_64
sudo tar xzf nvim-linux-x86_64.tar.gz -C /opt
sudo ln -sf /opt/nvim-linux-x86_64/bin/nvim /usr/local/bin/nvim
rm nvim-linux-x86_64.tar.gz
nvim --version | head -1

Put the config below in ~/.config/nvim/init.lua and start nvim – lazy.nvim installs all plugins on first start.

Do not install copilot.vim for Neovim – copilot.lua below replaces it.

mkdir -p ~/.config/nvim
cat >> ~/.config/nvim/init.lua << 'EOF'
-- ~/.config/nvim/init.lua
-- Neovim + clangd (built-in LSP) + GitHub Copilot Chat

-- --- Basic options ---
vim.g.mapleader = "\\"            -- same leader as in Vim
vim.opt.number = true
vim.opt.mouse = ""                -- don't capture the mouse (terminal copy works)
vim.opt.completeopt = { "menu", "menuone", "noselect", "popup" }

-- --- Plugin manager: lazy.nvim (bootstraps itself on first start) ---
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not vim.uv.fs_stat(lazypath) then
  vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable",
                  "https://github.com/folke/lazy.nvim.git", lazypath })
end
vim.opt.rtp:prepend(lazypath)

require("lazy").setup({
  -- Copilot: login (:Copilot auth) + inline suggestions while typing
  {
    "zbirenbaum/copilot.lua",
    cmd = "Copilot",
    event = "InsertEnter",
    opts = {
      suggestion = {
        auto_trigger = true,
        -- Accept suggestion with Alt-l (Tab stays free)
        keymap = { accept = "<M-l>", next = "<M-]>", prev = "<M-[>", dismiss = "<C-]>" },
      },
      panel = { enabled = false },
    },
  },

  -- Copilot Chat
  {
    "CopilotC-Nvim/CopilotChat.nvim",
    dependencies = {
      "zbirenbaum/copilot.lua",
      { "nvim-lua/plenary.nvim", branch = "master" },
    },
    cmd = { "CopilotChat", "CopilotChatToggle", "CopilotChatExplain",
            "CopilotChatReview", "CopilotChatFix", "CopilotChatModels" },
    opts = {},
    keys = {
      -- Toggle chat window
      { "<leader>cc", "<cmd>CopilotChatToggle<CR>", desc = "Copilot Chat" },
      -- Explain / review / fix the visual selection
      { "<leader>ce", ":CopilotChatExplain<CR>", mode = "v", desc = "Explain selection" },
      { "<leader>cr", ":CopilotChatReview<CR>",  mode = "v", desc = "Review selection" },
      { "<leader>cf", ":CopilotChatFix<CR>",     mode = "v", desc = "Fix selection" },
    },
  },
})

-- --- clangd (built-in LSP, no plugin needed) ---
-- Use clangd-20 if installed (Ubuntu), otherwise plain clangd (CentOS/RHEL)
local clangd = vim.fn.executable("clangd-20") == 1 and "clangd-20" or "clangd"
vim.lsp.config("clangd", {
  cmd = { clangd, "--background-index" },
  filetypes = { "c", "cpp" },
  root_markers = { "compile_commands.json", ".git" },
})
vim.lsp.enable("clangd")

-- Remove Neovim's default gr* LSP maps so our 'gr' reacts immediately
for _, k in ipairs({ "grr", "grn", "gra", "gri", "grt", "grx" }) do
  pcall(vim.keymap.del, "n", k)
  pcall(vim.keymap.del, "x", k)
end

-- Same keys as in ~/.vimrc (vim-lsp)
vim.api.nvim_create_autocmd("LspAttach", {
  callback = function(ev)
    local map = function(lhs, fn, desc)
      vim.keymap.set("n", lhs, fn, { buffer = ev.buf, desc = desc })
    end
    -- Navigation
    map("gd", vim.lsp.buf.definition,      "Jump to definition (back: Ctrl-T/Ctrl-O)")
    map("gD", vim.lsp.buf.declaration,     "Jump to declaration")
    map("gy", vim.lsp.buf.type_definition, "Jump to type definition")
    -- Who uses what
    map("gr", vim.lsp.buf.references,      "List references")
    map("gh", vim.lsp.buf.incoming_calls,  "Who calls this function")
    map("gH", vim.lsp.buf.outgoing_calls,  "What this function calls")
    -- Info (K = hover is a Neovim default)
    map("<leader>s", vim.lsp.buf.document_symbol,  "Symbols in this file")
    map("<leader>S", vim.lsp.buf.workspace_symbol, "Symbols in the project")
    -- Diagnostics (]d / [d are Neovim defaults)
    map("]g", function() vim.diagnostic.jump({ count = 1,  float = true }) end, "Next diagnostic")
    map("[g", function() vim.diagnostic.jump({ count = -1, float = true }) end, "Prev diagnostic")
    map("<leader>e", vim.diagnostic.setloclist, "List diagnostics")
    -- Editing
    map("<leader>rn", vim.lsp.buf.rename,      "Rename symbol")
    map("<leader>a",  vim.lsp.buf.code_action, "Code actions")
  end,
})

-- Result lists (]q [q ]l [l are Neovim defaults)
vim.keymap.set("n", "<leader>q", "<cmd>cclose<bar>lclose<CR>", { desc = "Close quickfix/location list" })
EOF

Check: open a .c file and run :checkhealth vim.lsp

nvim doe-emu.c

5. Copilot Chat (Neovim)

Requirements: GitHub account with Copilot (Copilot Free is enough) and Copilot Chat in the IDE enabled in GitHub Copilot settings.

nvim

And log in (once):

:Copilot auth          " opens a device code – enter it at github.com/login/device
:Copilot auth info     " verify
:checkhealth CopilotChat

6. Cheat sheet

Navigation (Vim and Neovim)

Key Action
gd go to definition (back: Ctrl-T / Ctrl-O)
gD go to declaration
gy go to type definition
gr list references
gh who calls this function
gH what this function calls
K hover: type / signature
\s / \S symbols in file / in project
]g / [g next / previous diagnostic
\e list diagnostics
\rn rename symbol
\a code actions (e.g. expand macro)
]q / [q next / previous quickfix entry
\q close quickfix / location list

Copilot (Neovim)

Key Action
\cc toggle chat window
visual + \ce / \cr / \cf explain / review / fix selection
Alt-l accept inline suggestion
Ctrl-S (insert) / Enter (normal) send prompt (in chat)
Ctrl-Y apply suggested change (undo with u)
q close chat
#buffer:active, #file:foo.c, #gitdiff:staged add context to prompt (Tab completes after #)
:CopilotChatModels choose model
⚠️ **GitHub.com Fallback** ⚠️