Better current word search in vim
I noticed something when I was refactoring my vim configs for the Nth time last week, which I wrote about in a bit more detail here[1]. It's a bit of vim configuration that I've been copying forward without thinking about it for years and years, never even remotely considering pruning it because it's so useful. I also came up with it myself but havne't ever really put any effort into sharing it, so here we are.
In just a few lines of lua, it's this:
vim.keymap.set('n', '*', function()
vim.api.nvim_exec('/\\v<' .. vim.fn.expand('') .. '>', false)
end)
vim.keymap.set('n', '#', function()
vim.api.nvim_exec('?\\v<' .. vim.fn.expand('') .. '>', false)
end)
By default, * and # do something very similar, they search for the word currently under the cursor. # simply searches backwards, while * is a forward search.
The mappings above copy that behavior (perform it as you would do it directly, explicitly) but introduce a very useful slight tweak. Executing /expand(<cword>) simply searches (/) for the word currently under the cursor (<cword>). But introducing < and > around it places word boundaries in the search string.
You see by the default naive cword search, any larger words which fully contain your search term would also show up as results. Try searching for a single letter variable that way and you'll have a bad time.
I think of this as a fantastic example of the utility of programmatic configuration (the sort that's made all the more powerful by using lua over VimL) - you're free to make the editor better in a hundred minor ways to smooth out your editing workflows, and in a way which is itself very much like maintaining code: build yourself a useful abstraction and don't have to think about it too much any more.