Using vim's *
/ #
actions for finding the next/prev occurrence of an identifier in the current code file is just not accurate.
It will find unwanted matches such as an identically named local variable in a different function, or maybe somthing like this thing: myVar = "myVar"
.
A better approach is to go the next occurrence of the identifier under the cursor, with the code-wise definition of identifier (scope and all).
Fortunately, Neovim implements LSP (language server protocol) and supports document highlighting. The missing link is automatically calling document highlighting for the identifier under cursor, and then supporting jump to next/prev LSP highlight.
- First, configuring your LSP is required (as LSP is used for the highlighting groups). This can be done using nvim-lspconfig.
- Install using your favorite plugin manager. For example: install using lazy.nvim (Simple approach)
require("lazy").setup({
{ "neovim/nvim-lspconfig" config = ... },
{ "frenchef156/chef-lsp-occurrence" }
})
- The actual recommended configuration (using lazy.nvim):
require("lazy").setup({
{
"neovim/nvim-lspconfig",
dependencies = { "frenchef156/chef-lsp-occurrence" },
config = function()
-- Add LSP configuration here
-- Setup identifier highlighting and occurrence traversing
local chefOccurrence = require("chefLspOccurrence")
chefOccurrence.setup()
vim.keymap.set("n", "<leader><C-n>", chefOccurrence.next)
vim.keymap.set("n", "<leader><C-p>", chefOccurrence.prev)
vim.o.updatetime = 500 -- Add this line to show highlighting faster
end,
}
})