3

I find :set hlsearch useful while I am entering the pattern; but I want the effect of :noh as soon as I press enter. Is that possible?

Toothrot
  • 3,129
  • 13
  • 27
  • 2
    Maybe nnoremap <CR> :nohl<CR><C-L>? – statox Sep 24 '15 at 20:31
  • @statox: thanks! what does do? – Toothrot Sep 24 '15 at 20:35
  • It redraws the screen (:h CTRL-L). Does the mapping works properly? I havent tested it so I'd like to have a confirmation before I make it an answer :-) – statox Sep 24 '15 at 20:37
  • @statox: yes. except I discovered that multiple highlights are only showed after <cr>; but the mapping works with the 2nd <cr>. – Toothrot Sep 24 '15 at 20:48
  • I not sure of what 2nd <CR> you're talking about, now I have access to a Vim I just tested nnoremap <CR> :nohl<CR> (without redraw) and it seems to work properly. – statox Sep 24 '15 at 21:57
  • I mean it only works after you pressed enter twice; but that makes sense, since you have to press it a first time for all the highlights to show. – Toothrot Sep 24 '15 at 21:59
  • I'm curious: did my solution not work for you? I think it should work (I've tested it), and it seems to me that it should be marked the correct answer. If not, could you explain what is wrong? – Karl Yngve Lervåg Jan 02 '16 at 22:36

3 Answers3

4

From a excellent book -- "Practical Vim":

Typing :noh<CR> to mute search highlighting is laborious. You can speed things up by creating a mapping such as this:

nnoremap <silent> <C-l> :<C-u>nohlsearch<CR><C-l> 

Normally, clears and redraws the screen (see :h CTRL-L). This mapping builds on top of the usual behavior by muting search highlighting.

You can add this line to you vimrc file. If you hit Ctrl+l, Vim will mute search highlighting and redraw the screen at the same time.

Feng Yu
  • 659
  • 5
  • 17
3

I think you can achieve what you want through the mapping

cnoremap <silent> <cr> <cr>:nohl<cr>

The above mapping should turn of highlighted searches after you have pressed enter to accept the search pattern.

Note, though, that the highlighting is turned back on with for instance n and N, i.e. when repeating the search. You can turn this off with maps, e.g.

nnoremap n n:nohl<cr>
nnoremap N N:nohl<cr>

Note: I found that the above cnoremap does not work as expected if you use the incsearch plugin, and I could not find why.

Karl Yngve Lervåg
  • 9,494
  • 25
  • 35
1

I have in my .vimrc

:nmap <leader>q :nohlsearch<CR>

which maps my leader (\ by default, but I remapped to ,) then q to remove the search highlighting. Not exactly what you're looking for, but it might be worthwhile.

That, and several other nice bits came from http://dougblack.io/words/a-good-vimrc.html#search, though he uses space to disable the highlight.

Rick R
  • 111
  • 2