4

I've set hlsearch on my .vimrc.

The problem is: when I find what I need in my document, I want it to automatically disable hlsearch when I enter insert mode for that searched string.

So, if I try to search for another string, it starts over again. This behavior is well known among other editors.

How do I do it?

2 Answers 2

7

disable highlighting when entering insertmode via i:

noremap i :set nohlsearch<CR>i

to reenable it by leaving insert mode (via ESC):

inoremap <ESC> <ESC>:set hlsearch<CR>

you could apply these idea to all kind of keys like a, o etc.

OR

autocmd InsertEnter * :set nohlsearch
autocmd InsertLeave * :set hlsearch

(kudos for the 'InsertEnter' event idea)

4
4

I found a completely different approach, but that's is EXACTLY what I was looking for.

:set hlsearch
autocmd InsertEnter * :let @/=""
autocmd InsertLeave * :let @/=""

This sets the "latest search" register to the empty string, so that nothing will be highlighted. Earlier searches can still be remembered by using the key after hitting / or ? and optionally the "start" of the string to be searched.

Source

Thanks for your answer akira, but this solution is really elegant in my opinion. And it works, I tested it!

2
  • if it works, its fine with me.
    – akira
    Jun 28, 2010 at 6:35
  • 2
    This approach breaks the "search again" functionality (/ <cr>).
    – Xilexio
    Sep 21, 2015 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.