Highlighting a search term without moving the cursor
skyblue’s answer shows the core of the idea of how to use the normal search highlighting to accomplish what you want.
I extended that technique by making a keybinding that works similarly to the *
command, but without actually moving to the next match.
My thanks goes to garyjohn for pointing out the expand()
equivalent to *
’s word selection (to avoid using *
itself and restoring the view). This simplifies the code enough so that it can go directly in the mapping (obviates using a function). I have also added a mapping that matches partial words (like g*
).
:" The leader defaults to backslash, so (by default) this
:" maps \* and \g* (see :help Leader).
:" These work like * and g*, but do not move the cursor and always set hls.
:map <Leader>* :let @/ = '\<'.expand('<cword>').'\>'\|set hlsearch<C-M>
:map <Leader>g* :let @/ = expand('<cword>')\|set hlsearch<C-M>
You could also set the search register to the variable you want to match.
First, make sure search highlighting is turned on:
:set hlsearch
Then, you can set the search register with:
:let @/="variable"
This will highlight all occurrences of variable without jumping to the next match.
For more information, see :help @/
One way is to use the :match
command, e.g.,
:match Question '^R^W'
That will highlight the word under the cursor using the Question highlight group. I often use the Question group because on my terminal it's a nice green. To see the available highlight groups, execute
:hi
The ^R
and ^W
are Ctrl-R and Ctrl-W, respectively, and are replaced by the word under the cursor. See
:help c_CTRL-R_CTRL-W
for more on that. See
:help :match
for more on the :match
command. To clear that highlighting, simply execute
:match
with no arguments.