Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 740
Ein Avatar asked Jan 29 '12 16:01

Ein


People also ask

How to unset hlsearch in vim?

: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.


2 Answers

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" 
like image 183
Christian Brabandt Avatar answered Sep 21 '22 19:09

Christian Brabandt


" 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.

like image 37
trusktr Avatar answered Sep 18 '22 19:09

trusktr