Remove VIM search highlight

All we need is an easy explanation of the problem, so here it is.

After a search I’ve done, all the matches for the respective query remain highlighted and it’s annoying. This happens even after I close the respective file (normal behavior?). How to I remove this?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You want the command :nohlsearch, but you don’t want to type that every time. Put this in your ~/.vimrc:

nnoremap <silent> <leader>n :nohlsearch<CR>

After that, you just enter your leader (which by default is \) and then n to clear the matches. You don’t need to use n; if you prefer, pick something else.

You can also remap your leader to something more comfortable, if you like. I use a comma:

let mapleader = ","

(That goes before the mapping to clear searches.)

Method 2

i just /qiw772723euz to “search” for something thats not in the file. hacky workaround, i know, i am interested in a real solution as well 🙂

Method 3

Similar to @Telemachus answer above, a comment on this answer over at SO by @David Winslow suggested mapping a toggle of hlsearch. You would map the following:

nmap <silent> <leader>n :set hlsearch!<CR>

Hitting n would then toggle highlight search off and on every time you hit it.

Method 4

In my config, I clear highlighted search terms by just hitting enter in command mode. This is how that’s configured.

set hlsearch    " highlight all matched terms
" Pressing return clears highlighted search
:nnoremap <CR> :nohlsearch<CR>/<BS>

As a side note, I like to make sure that my search matches are highlighted super clearly, no matter the color scheme, so I give them black text on a yellow background.

" When highlighting search terms, make sure text is contrasting color
:highlight Search ctermbg=yellow ctermfg=black
" Do the same for gvim
:highlight Search guibg=yellow guifg=black

Method 5

I have a slightly different solution. To me it feels as the natural thing to do would be to press <esc> to make it go away. However, that doesn’t work. Mapping <esc> to :noh has nasty side-effects, so that’s not an option either. <Leader>n and similar mappings feels unintuitive for me for such a trivial task. However, pressing <esc> twice is something I can live with:

nnoremap <silent> <esc><esc> :nohlsearch<CR>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply