How to toggle Vim's search highlight visibility without disabling it

Ein picture Ein · Jan 29, 2012 · Viewed 12.4k times · Source

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:

  1. Mapping F4 to :nohlsearch temporarily disables highlight visibility without turning the hlsearch setting off, but it does not toggle visibility back again.
  2. Mapping F4 to :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

Answer

Christian Brabandt picture Christian Brabandt · Oct 22, 2014

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"