joplin-notes/joplin notion extension/Web Development/Neovim/Configuring c++ on neovim.md
2026-11-04 00:33:23 +05:30

125 lines
No EOL
2.7 KiB
Markdown

Configuring c++ on neovim
https://www.youtube.com/watch?v=lsFoZIg-oDs
- Installing clangd(LSP)
In ensure_installed section then type `:MasonInstallAll`.
In lspconfig.lua add this
```lua
lspconfig.clangd.setup{
on_attach=on_attach,
capabilities=capabilities,
init_options={
preferences={
disableSuggestions=true,
}
}
}
```
Add instead this in `lspconfig.lua` to remove warning
```lua
local cmp_nvim_lsp = require "cmp_nvim_lsp"
require("lspconfig").clangd.setup {
on_attach = on_attach,
capabilities = cmp_nvim_lsp.default_capabilities(),
cmd = {
"clangd",
"--offset-encoding=utf-16",
},
}
```
- Autoformatter
Install clang-format. Add following in `plugins.lua`
```lua
{
"jose-elias-alvarez/null-ls.nvim",
event="VeryLazy",
opts=function ()
return require "custom.configs.null-ls"
end,
},
```
Create `~/.config/nvim/lua/custom/configs/null-ls.lua`
and type this
```lua
local null_ls= require("null-ls")
local opts={
sources={
null_ls.builtins.formatting.clang_format,
}
}
return opts
```
Press space and type `fm` to format it
To have a custom file formatting we need to have `.clang-format` in out project folder. Generate using this
`~/.local/share/nvim/mason/bin/clang-format --style GNU --dump-config > .clang-format`
- Setup autoformat on save
In `null-ls.lua` file
modify it like this
```lua
local augroup=vim.api.nvim_create_augroup("LspFormatting",{})
local null_ls= require("null-ls")
local opts={
sources={
null_ls.builtins.formatting.clang_format,
},
on_attach=function (client,bufnr)
if client.supports_method("textDocument/formatting") then
vim.api.nvim_clear_autocmds({
group=augroup,
buffer=bufnr,
})
vim.api.nvim_create_autocmd("BufWritePre",{
group=augroup,
buffer=bufnr,
callback=function ()
vim.lsp.buf.format({bufnr=bufnr})
end,
})
end
end,
}
return opts
```
- Debugger
With mason, install `codelldb` plugin too.
To able to debug them use `--debug` flag after gcc command when compiling like this
`gcc --debug main.cpp -o main`
And when running debugger mention name of executable file ie `main` here
In `plugins.lua` add this
```lua
{
"mfussenegger/nvim-dap",
config=function (_, _)
require("core.utils").load_mappings("dap")
end
},
-- Also add this
{
"jay-babu/mason-nvim-dap.nvim",
event="VeryLazy",
dependencies={
"williamboman/mason.nvim",
"mfussenegger/nvim-dap",
},
opts={
handlers={}
},
},
-- Add nvim-dap-ui too from javascript debugger too
```
Also changes in `chadrc.lua` and add `mappings.lua` like with js debugger too