As we know, we can set a highlight color while searching a keyword.

I'm wondering if I can set a timer task to clear the highlight color after a few seconds.

For now, I have to type :noh<CR> to clear the highlight color. If setting a timer task is possible, I'd like to set a timer task as below:

  1. searching a keyword
  2. 5 seconds later, :noh<CR> is executed automatically
  • Do you have +timers in :version? It was added in Vim 7.4.1578, so you may have it even on Vim 7. Dec 31 '19 at 3:57
  • As usual, you can also create a mapping to the :nohlsearch command to make this faster, but still manual
    – D. Ben Knoble
    Dec 31 '19 at 4:38
  • @MartinTournoij Yes I have
    – Yves
    Dec 31 '19 at 5:57

:noh is executed automatically

Well, that's kind of prohibited.

:h function-search-undo

The last used search pattern and the redo command "." will not be changed by the function. This also implies that the effect of |:nohlsearch| is undone when the function returns.

Note that internally all autocommands are functions, so :noh inside an autocommand won't have any effect either.

Therefore, you are more or less confined to feedkeys() like that

augroup autonoh | au!
    autocmd CursorHold * if v:hlsearch | call feedkeys(":noh\<CR>", 'n') | endif
augroup end

(Don't try to make use of timer_start() even if you have it in Vim7, as for this case you'll certainly also need SafeState, but it's available in Vim 8.1+ only).

Still, that does not feel good to me, so I believe that a mapping (nnoremap <C-L> :noh<CR><C-L>, or whatever) should be preferred.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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