Search code examples
vimautocmd

Clear search highlight on autocmd BufWrite


I tried most of the suggestions in those three questions:

Get rid of Vim's highlight after searching text
How to get rid of search highlight in Vim
Vim clear last search highlighting

It's mainly the :noh, and it works when I type it manually. I just want it happen on BufWrite, so I tried multiple ways, none of which worked:

function! RemoveHighLight()
    :noh
endfunction

autocmd BufWrite * :call RemoveHighLight()
autocmd BufWrite * :noh
autocmd BufWrite * :execute "normal! :noh\<cr>"

Debuging echoms and adebug\<esc> in the function and in the third autocmd show that they execute successfully, just the :noh has no effect.

(Also tried :let @/ = "" which worked but it clears the search pattern, which is not I'm looking for. I just want to get rid of the highlight til pressing n or similar)

Using BufWritePost doesn't have effect, either.


Solution

  • It is a workaround but you can set nohlsearch by autocmd. Then you can add a mapping to set it back by n and N.

    au BufWrite * set nohlsearch
    nnoremap <silent> n n:set hlsearch<CR>
    nnoremap <silent> N N:set hlsearch<CR>
    

    Or maybe better, check if it is already set

    au BufWrite * set nohlsearch
    
    nnoremap <silent> n n:call ToggleHlBack()<CR>
    nnoremap <silent> N N:call ToggleHlBack()<CR>
    
    function! ToggleHlBack()
      if &hlsearch == 'nohlsearch'
        set hlsearch
      endif
    endfunction