My solution: put this in your vimrc file
set nohlsearch
noremap * :set hlsearch<CR>:nohlsearch<CR>*
noremap / :set hlsearch<CR>:nohlsearch<CR>/
noremap ? :set hlsearch<CR>:nohlsearch<CR>?
nnoremap <F4> :set invhlsearch<CR>
inoremap <F4> <ESC>:set invhlsearch<CR>gi
nnoremap <CR> :set nohlsearch<CR>
What it does:
- Searches always enable highlights.
- Use Enter to turn off highlights until the next search, but not the next substitute. Pressing Enter again will not turn them back on though.
- Use F4 to turn off highlights until the next search, but not next substitute. Pressing F4 again will toggle the highlights for the last search pattern --- search OR substitute --- if there was one.
Some notes on highlights that are never really explained well:
When the 'hlsearch'
option is on, all future searches/substitutes will turn on "highlight visibility"
. The current "highlight visibility"
is not really an option you can directly query or set independently, but you can independently turn OFF highlight visibility with the command :nohlsearch
(this is not the same as :set nohlsearch
, because the next search will enable visibility again).
In addition, whenever you run the command :set hlsearch
there are two effects: It sets the option AND it makes vim forget if you've ever typed :nohlsearch
. In other words, changing 'hlsearch'
(either on or off) will force the current "highlight visibility"
to logically match.