Clear search highlight
Vim’s search highlighting feature, set hlsearch
, is a popular toggle that will instantly highlight all the matches for your current pattern match. But once you’ve found what you were looking for, you may be annoyed that the highlight persists.
If you’re like me, you might just search for an unlikely pattern by randomly mashing the keys: /akljshdakdja
which will clear any present highlights because the pattern will not be found.
But, of course, Vim has a better way. The official way to clear the highlight for the last search is with the :nohlsearch
command which you can abbreviate to just :noh
. After completing your search, just type :noh
and your highlights will disappear until the next search.
You could also add a key mapping for that if you use it often enough. I recommend just using Tim Pope’s sensible.vim plugin, which provides a nearly universally accepted set of Vim default configurations. One of the included mappings is designed just for this use case:
" Use <C-L> to clear the highlighting of :set hlsearch.
if maparg('<C-L>', 'n') ==# ''
nnoremap <silent> <C-L> :nohlsearch<C-R>=has('diff')?'<Bar>diffupdate':''<CR><CR><C-L>
endif
With sensible.vim installed, you can simply press <ctrl-l>
to clear the search highlight until the next search.