If you check :h :nohl
, you will see that the command :nohl
does not work within an autocmd, the reason being that vim saves & restores the search & search highlighting state after executing an autocmd. Hence technically it is not feasable to do so. The best way is to create a mapping like nnoremap <C-l> :nohlsearch<CR>
and use it when you want to temporarily disable the search highlighting.
However there is a slight hack that i'd like to demonstrate that does work in a way like you expect by using set nohlsearch
instead of nohlsearch
, the downside of course is that it turns off search highlighting completely and you need to re-enable it using set hlsearch
, so it isn't really a solution but it makes for a good example to demonstrate how one could perform time based operations within vim.
NOTE: This is more for educational purposes to demonstrate how you could do time based non-blocking tasks in vim. The performance of these could vary depending on what you do within the event triggered function.
augroup NoHLSearch
au!
autocmd CursorHold,CursorMoved * call <SID>NoHLAfter(3)
augroup END
function! s:NoHLAfter(n)
if !exists('g:nohl_starttime')
let g:nohl_starttime = localtime()
else
if v:hlsearch && (localtime() - g:nohl_starttime) >= a:n
set nohlsearch
unlet g:nohl_starttime
endif
endif
endfunction