TIL: highlight search matches in Vim

Like any good text editor, Vim supports highlighting of search matches. Think of it like searching in your browser: it highlights all occurrences of the search string. In Vim it’s similar, except that it also works with regular expressions.

Highlighting of matches is turned off by default. Enable it with the following snippet in your ~/.vimrc file:

" Highlight search matches
set hlsearch 

The following makes the whole thing a little smarter when it comes to matching upper case and lower case:

" Ignore case when searching
set ignorecase
" except when search string contains uppercase
set smartcase

Notice that there is still a difference between searching in Vim and in your browser: the latter jumps to the first match while you enter the search string. If that’s your cup of tea, enable it with:

" Jump to first match while entering search string
set incsearch

Here’s a handy shortcut to turn highlighting off once you’re done with searching. It’s the proper way to do that, instead of searching for something non-existent like asdf as I used to do when I started out with Vim many years ago. Note that highlighting will turn itself back on next time you search.

" Turn highlighting off till next search
map <silent> <leader>/ :nohlsearch<cr>

That’s the <leader> key following by a slash. As the mnemonic counterpart to the single slash used to initiate a search.

By default the leader key is set to backslash, but I have mine set to the easier-to-reach comma instead:

" Set leader key
let mapleader = ","

Existing mappings are not updated after setting this value. Some plugins set mappings as well. So make sure to set the leader early enough in your config.


← back to main page