2

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.

Community
  • 1
  • 1
Al.G.
  • 4,327
  • 6
  • 31
  • 56

1 Answers1

2

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
ryuichiro
  • 3,765
  • 1
  • 16
  • 21
  • That's a nice trick, thanks. There is a little bug, however. Is there a way to `set hlsearch` on next search? Because now it resets after n/N-ing but not on search+enter -ing. I'm more pedantic here than I have to be of course, I'm just curious ;d (older comment removed) – Al.G. Nov 01 '15 at 19:33
  • Sorry, that is true. I did not think about it. It could be done probably in a better way but you could add a mapping `nnoremap / :call ToggleHlBack()/`. – ryuichiro Nov 01 '15 at 19:52