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 serverfilter— a Lua function called for each action; returntrueto include ita.isPreferred— a boolean set by the LSP server indicating the recommended actionapply = 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 forvim.lsp.buf.code_action()(without auto-apply)- LSP servers like
rust-analyzer,pyright, andtypescript-language-serverfrequently setisPreferredon their most common fixes