vimtricks.wiki Concise Vim tricks, one at a time.

How do I create a mapping to quickly toggle search highlighting on and off?

Answer

:set hlsearch! (toggled via mapping)

Explanation

:set hlsearch! toggles search highlighting on and off in a single command — the ! (bang) flips the boolean option. Bound to a key, this gives you instant control over whether matches stay highlighted after a search.

How it works

  • :set hlsearch! — toggle highlighting on/off
  • :set hlsearch — force on
  • :set nohlsearch — force off
  • :nohlsearch (:noh) — clear the current highlight without disabling hlsearch (it returns after next search)

Recommended mappings

Toggle with <F3>:

nnoremap <F3> :set hlsearch!<CR>

Clear highlight on <Esc> in normal mode:

nnoremap <Esc> :nohlsearch<CR>

The difference: <F3> with hlsearch! is a persistent toggle; <Esc> with :noh temporarily clears until the next search.

Toggle with a status indicator in the mapping:

nnoremap <F3> :set hlsearch!<CR>:set hlsearch?<CR>

This also prints the new state in the command line.

Tips

  • :set hlsearch must be enabled first for any of this to matter — add set hlsearch to your vimrc
  • :noh is a one-shot clear; it does not disable hlsearch permanently
  • set incsearch (show matches as you type) is a companion option — usually enabled alongside hlsearch
  • <C-l> in some setups is mapped to :nohlsearch<CR><C-l> to clear + redraw in one keystroke

Next

How do I run a search and replace only within a visually selected region?