What I'd like is to map one key, e.g. F4, so that pressing F4 will toggle the visibility of search highlights, and so that starting a new search enables visibility no matter the current visibility.
What I've tried:
- Mapping F4 to
:nohlsearch
temporarily disables highlight visibility without turning thehlsearch
setting off, but it does not toggle visibility back again. - Mapping F4 to
:set hlsearch!
does toggle on/off, but I don't want to toggle thehlsearch
setting off, just the visibility setting. Ifhlsearch
is off then it doesn't come back automatically with a new search.
There doesn't seem to be an opposite form of :nohlsearch
and the command itself has problems being called from a function.
I've found similiar questions, but they don't provide an answer.
Update:
The first comment provides exactly what I was asking for, reproduced below:
let hlstate=0
nnoremap <F4> :if (hlstate == 0) \| nohlsearch \| else \| set hlsearch \| endif \| let hlstate=1-hlstate<cr>
(N.B. for anyone using this --- cramming the map onto one line instead of using a function is necessary since you can't effect a change on highlighting from inside a function.)
Related question for slightly different functionality: https://mcmap.net/q/584342/-highlight-searches-in-vim-but-not-substitutions
" ctrl+c to toggle highlight.
, Line 2:let hlstate=0
. Line 3:nnoremap <c-c> :if (hlstate%2 == 0) \| nohlsearch \| else \| set hlsearch \| endif \| let hlstate=hlstate+1<cr>
. Now just press ctrl+c to toggle highlight. – Jeuz