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

How do I automatically apply the preferred LSP code action without a selection prompt in Neovim?

Answer

vim.lsp.buf.code_action({ apply = true, filter = function(a) return a.isPreferred end })

Explanation

When an LSP server marks a code action as isPreferred (e.g., the recommended auto-fix for an error, or organize imports), you can apply it directly with a single keymap — no popup menu needed. This is ideal for common actions like fixing a specific diagnostic or auto-importing a symbol.

How it works

  • vim.lsp.buf.code_action(opts) — requests code actions from the language server
  • filter — a Lua function called for each action; return true to include it
  • a.isPreferred — a boolean set by the LSP server indicating the recommended action
  • apply = true — if exactly one action passes the filter, apply it immediately without a menu

Example

Add this keymap in your Neovim config:

vim.keymap.set('n', '<leader>ca', function()
  vim.lsp.buf.code_action({
    apply = true,
    filter = function(a) return a.isPreferred end,
  })
end, { desc = 'Apply preferred code action' })

Now <leader>ca silently applies the preferred fix. If no preferred action exists, or if multiple actions are preferred, the standard selection menu appears as a fallback.

Tips

  • To apply the first available action regardless of isPreferred: { apply = true } (applies immediately only when there's exactly one action)
  • To filter by kind: filter = function(a) return a.kind == 'quickfix' end
  • gra — Neovim 0.10+ default mapping for vim.lsp.buf.code_action() (without auto-apply)
  • LSP servers like rust-analyzer, pyright, and typescript-language-server frequently set isPreferred on their most common fixes

Next

How do I enable matchit so % jumps between if/else/end style pairs?