jshawl
jshawl

Reputation: 3483

Toggle highlight while searching in Vim

I like highlighting while searching in vim. Here's what I want:

I search for a word with /

Then, all of the results are highlighted. If I press any key other than n or N, I want the highlighting to be toggled off.

If I press n or N again after any number of commands, I want to toggle on the highlighting.

Where do I start? I'm not even sure what to google.

Upvotes: 2

Views: 820

Answers (5)

Dhruva Sagar
Dhruva Sagar

Reputation: 7307

I prefer this, because to me it is nothing but natural.

Start searching with /<pattern> and once done, simply type <Leader>/ to stop the highlighting.

nnoremap <silent> <Leader>/ :set nohl<CR>

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

I remap control-l (lower case L) so that it clears the search result as well as repaints the screen. This line in .vimrc does it:

nnoremap <silent> <C-l> :nohl<CR><C-l>

Upvotes: 2

cforbish
cforbish

Reputation: 8819

One method is to setup a toggle mapping. These are some toggle mappings I have in my .vimrc:

let mapleader="\\"
noremap <silent> <Leader>th :set invhls hls ?<CR>
noremap <silent> <Leader>tn :set invnumber number ?<CR>
noremap <silent> <Leader>ts :set invspell spell ?<CR>
noremap <silent> <Leader>tw :set invwrap wrap ?<CR>

To toggle highlighting just type \th for toggle hls. The others are line number, spell checking, line wrapping. The final hls ? will display the new mode.

Upvotes: 0

Matt Woelk
Matt Woelk

Reputation: 2038

I have this in my .vimrc

nnoremap <CR> :noh<CR>

so that when I'm done seeing the highlighting, I just hit enter to remove it. It stays gone until I hit n or N again.

Note: If you want to keep the functionality of enter, add another <CR> on the end of the command.

Upvotes: 4

Nicky McCurdy
Nicky McCurdy

Reputation: 19554

You can manually disable the last highlight with nohl.

I will let you know if I can figure out how to automate this.

Upvotes: 1

Related Questions