There is a much more convenient way. Rather than using
:set nohlsearch
which actually turns the hlsearch setting off, use
:nohls
This will only turn hlsearch off until you search again. From :help nohls
*'hlsearch'* *'hls'* *'nohlsearch'* *'nohls'*
'hlsearch' 'hls' boolean (default off)
global
{not in Vi}
{not available when compiled without the
|+extra_search| feature}
...
When you get bored looking at the highlighted matches, you can turn it
off with |:nohlsearch|. This does **not change the option value**, as
soon as you use a search command, the highlighting comes back.
However, this solution isn't perfect, since you still have to type out :nohls
which is pain to do after every search. You can get around this with a mapping, e.g.
nnoremap <esc><esc> :silent! nohls<cr>
But there is an even better solution! haya14busa/incsearch.vim. This is, at least in my opinion, an essential vim plugin. The main feature is that all search matches are highlighted in real time, as you are typing out your regex. For example:
However, a secondary feature that is also provided is the option to immediately toggle hlsearch on and off when you start/stop searching. To enable this feature, you will have to add
set hlsearch
let g:incsearch#auto_nohlsearch = 1
map n <Plug>(incsearch-nohl-n)
map N <Plug>(incsearch-nohl-N)
map * <Plug>(incsearch-nohl-*)
map # <Plug>(incsearch-nohl-#)
map g* <Plug>(incsearch-nohl-g*)
map g# <Plug>(incsearch-nohl-g#)
to your .vimrc
.
If you have any other n
mappings, you will have to turn these off. For example, I used to have
nnoremap n nzz
nnoremap N Nzz
These two mappings are not compatible with eachother!
/
or?
, or if I pressn
orN
, it will turn on without me needing to press any more buttons.:nno <BS> :set hls!\|set hls?<CR>
-- one line, one keypress, state feedback, and doesn't try to second-guess when you may or may not want highlighting. Sometimes I want highlighting left on the screen when editing. Sometimes I don't, e.g. using/
as a motion with an operator.nnoremap <M-\> :set hlsearch!<CR><Bar>:echo 'hlsearch: ' . ['Off', 'On'][&hlsearch]<CR>