Language Server Setup for Code Intelligence
Intermediate15 minTrending
Configure Neovim's built-in LSP client with mason.nvim for automatic server installation, autocompletion, and diagnostics.
Prerequisites
- -Neovim 0.9+ installed
- -lazy.nvim configured
- -Node.js installed (for many language servers)
Steps
1
Add LSP plugin specs
Create a plugin file that installs mason, mason-lspconfig, nvim-lspconfig, and nvim-cmp for completions.
$ cat > ~/.config/nvim/lua/plugins/lsp.lua << 'EOF'
return {
{ "williamboman/mason.nvim", config = true },
{ "williamboman/mason-lspconfig.nvim",
dependencies = { "williamboman/mason.nvim", "neovim/nvim-lspconfig" },
config = function()
require("mason-lspconfig").setup({
ensure_installed = { "lua_ls", "ts_ls", "rust_analyzer", "gopls", "pyright" },
automatic_installation = true,
})
end,
},
{ "neovim/nvim-lspconfig",
config = function()
local lspconfig = require("lspconfig")
local servers = { "lua_ls", "ts_ls", "rust_analyzer", "gopls", "pyright" }
for _, server in ipairs(servers) do
lspconfig[server].setup({})
end
end,
},
{ "hrsh7th/nvim-cmp",
dependencies = {
"hrsh7th/cmp-nvim-lsp",
"hrsh7th/cmp-buffer",
"L3MON4D3/LuaSnip",
},
config = function()
local cmp = require("cmp")
cmp.setup({
snippet = { expand = function(args) require("luasnip").lsp_expand(args.body) end },
mapping = cmp.mapping.preset.insert({
["<C-Space>"] = cmp.mapping.complete(),
["<CR>"] = cmp.mapping.confirm({ select = true }),
}),
sources = cmp.config.sources({
{ name = "nvim_lsp" },
{ name = "buffer" },
}),
})
end,
},
}
EOF
2
Install language servers
Open Neovim and let mason-lspconfig install the configured servers automatically.
$ nvim --headless '+Lazy sync' +qa && nvim --headless '+MasonInstall lua-language-server typescript-language-server' +qa
Run :Mason inside Neovim to see installed servers and install new ones interactively.
3
Add LSP keybindings
Set up keybindings for common LSP actions like go-to-definition and rename.
$ cat > ~/.config/nvim/lua/plugins/lsp-keys.lua << 'EOF'
return {
{ "neovim/nvim-lspconfig",
keys = {
{ "gd", vim.lsp.buf.definition, desc = "Go to definition" },
{ "gr", vim.lsp.buf.references, desc = "Find references" },
{ "K", vim.lsp.buf.hover, desc = "Hover documentation" },
{ "<leader>rn", vim.lsp.buf.rename, desc = "Rename symbol" },
{ "<leader>ca", vim.lsp.buf.code_action, desc = "Code action" },
{ "[d", vim.diagnostic.goto_prev, desc = "Previous diagnostic" },
{ "]d", vim.diagnostic.goto_next, desc = "Next diagnostic" },
},
},
}
EOF
4
Verify LSP is active
Open a source file and check that the language server is attached.
$ :LspInfo
If no server attaches, check :Mason to ensure the server is installed and :checkhealth lsp for diagnostics.
Full Script
FAQ
Discussion
Loading comments...