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:
:nohlsearch
temporarily disables highlight visibility without turning the hlsearch
setting off, but it does not toggle visibility back again.:set hlsearch!
does toggle on/off, but I don't want to toggle the hlsearch
setting off, just the visibility setting. If hlsearch
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://stackoverflow.com/a/16750393/1176650
:set invhlsearch will disable the highlighting if its already highlighted and enable it if it isn't. You can map it to say Shift-H.
Note, recent Vims (7.4.79) have the v:hlsearch
variable available. This means you can improve your mapping to:
:nnoremap <silent><expr> <Leader>h (&hls && v:hlsearch ? ':nohls' : ':set hls')."\n"
" ctrl+c to toggle highlight. let hlstate=0 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. Only quirk is you gotta press it twice after a search to toggle off highlight because searching doesn't increment the counter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With