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 disablinghlsearch(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 hlsearchmust be enabled first for any of this to matter — addset hlsearchto yourvimrc:nohis a one-shot clear; it does not disablehlsearchpermanentlyset incsearch(show matches as you type) is a companion option — usually enabled alongsidehlsearch<C-l>in some setups is mapped to:nohlsearch<CR><C-l>to clear + redraw in one keystroke