How to accept nvim lsp suggestions?

4.3k Views Asked by At

To give a simple example. Having a variable or function misspelled, the LS gives a suggestion "Cannot find name 'voteings'. Did you mean 'votings'?

Is there a way to quickly accept those suggestion?

1

There are 1 best solutions below

0
On

As suggested by nalzok, :lua vim.lsp.buf.code_action() will open the code actions that can be performed on the LSP's suggestion.

If you want to automatically accept the action without having the code actions open up, you can use the options parameter. The options parameter has two fields that come in handy here, filter and apply. The first field will allow you to filter the list of code actions and the second field will auto apply the code action if it's the only one available.

Using these two together yields the following command:

lua vim.lsp.buf.code_action({
  filter = function(code_action)
    return string.find(action.title, "spelling")
  end,
  apply = true,
})

This will filter the code actions to only show the ones that suggest spelling fixes and will auto apply it if there is only one code action left.

Alternatively, you can leave out the filter field if you only want it to apply if the only code action is the spelling fix.

For more info, check out :h vim.lsp.buf.code_action.