vimtricks.wiki Concise Vim tricks, one at a time.

How do I use LSP for go-to-definition, references, and refactoring in Neovim?

Answer

gd / gr / <leader>rn with nvim-lspconfig

Explanation

The Language Server Protocol (LSP) brings IDE-level intelligence to Neovim — go-to-definition, find references, rename symbol, and more. With Neovim's built-in LSP client and nvim-lspconfig, setup is straightforward.

Setup

-- Install mason + lspconfig
require('mason').setup()
require('mason-lspconfig').setup({
  ensure_installed = { 'gopls', 'pyright', 'ts_ls' },
})

-- Configure each server
local lspconfig = require('lspconfig')
lspconfig.gopls.setup({})
lspconfig.pyright.setup({})
lspconfig.ts_ls.setup({})

Essential LSP keybindings

vim.keymap.set('n', 'gd', vim.lsp.buf.definition)      -- Go to definition
vim.keymap.set('n', 'gr', vim.lsp.buf.references)       -- Find references
vim.keymap.set('n', 'K', vim.lsp.buf.hover)             -- Show documentation
vim.keymap.set('n', '<leader>rn', vim.lsp.buf.rename)   -- Rename symbol
vim.keymap.set('n', '<leader>ca', vim.lsp.buf.code_action) -- Code actions
vim.keymap.set('n', 'gi', vim.lsp.buf.implementation)   -- Go to implementation
vim.keymap.set('n', '<leader>f', function()
  vim.lsp.buf.format({ async = true })
end)                                                     -- Format file

Diagnostics navigation

vim.keymap.set('n', '[d', vim.diagnostic.goto_prev)  -- Previous diagnostic
vim.keymap.set('n', ']d', vim.diagnostic.goto_next)  -- Next diagnostic
vim.keymap.set('n', '<leader>e', vim.diagnostic.open_float) -- Show error

What LSP provides

Feature Keybinding
Go to definition gd
Find references gr
Hover documentation K
Rename symbol <leader>rn
Code actions <leader>ca
Format code <leader>f
Signature help <C-k>

Tips

  • Mason installs language servers automatically — no manual setup
  • nvim-cmp with cmp-nvim-lsp adds LSP-powered autocompletion
  • trouble.nvim provides a better diagnostic list view
  • <C-o> jumps back after gd (uses the jumplist)
  • Since Neovim 0.11, many LSP features work out of the box with less config
  • Vim 8+ users can use vim-lsp or coc.nvim for similar features

Next

How do I run the same command across all windows, buffers, or tabs?