Definitions and Keybinds
lspconfig
provides a list of example keybindings you can use for other LSP features - including diagnostics (i.e. warnings/errors) and definitions.
Diagnostic Keybindings
The first of these keybindings are pulled straight from lspconfig
README on github.
vim.keymap.set('n', '<leader>do', vim.diagnostic.open_float)vim.keymap.set('n', '<leader>dp', vim.diagnostic.goto_prev)vim.keymap.set('n', '<leader>dn', vim.diagnostic.goto_next)vim.keymap.set('n', '<leader>dl', "<cmd>Telescope diagnostics<cr>")
If you are not using the Telescope plugin, you can omit the last keybind.
All of these keybinds make use of Neovim’s built-in diagnostic feature to open up warnings or errors raised by the LSP.
Most of these are self-explanatory (goto_prev
goes to the previous error, goto_next
goes to the next error, etc.)
open_float
opens the error is a small pop-up window in full, and you can repeat the keymap to bring your cursor “inside” the pop-up (use q
to quit).
LSP Keybindings
LSP keymaps are a little more complex, only because they require a little more Lua and Neovim magic. All of the code for this is in the lspconfig
docs.
vim.api.nvim_create_autocmd('LspAttach', { group = vim.api.nvim_create_augroup('UserLspConfig', {}), callback = function(ev) local opts = { buffer = ev.buf } vim.keymap.set('n', 'gD', vim.lsp.buf.declaration, opts) vim.keymap.set('n', 'gd', vim.lsp.buf.definition, opts) vim.keymap.set('n', 'K', vim.lsp.buf.hover, opts) vim.keymap.set('n', '<space>rn', vim.lsp.buf.rename, opts) vim.keymap.set('n', '<space>f', function() vim.lsp.buf.format { async = true } end, opts) end,})
Let’s break this down:
The autocmd created in the example code here is so the keybindings only activate when you are in a buffer which has an LSP client attached. The reason for this is so you can re-use keybindings which may do similar things outside of LSP buffers, for example exploring Neovim documentation with K.
The most common functions are:
- vim.lsp.buf.hover()
- vim.lsp.buf.format()
- vim.lsp.buf.references()
- vim.lsp.buf.implementation()
- vim.lsp.buf.code_action()