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 echom s 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.


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
链接地址: http://www.djcxy.com/p/49388.html

上一篇: 在vim中,鼠标点击和滚动被看作是击键和搞乱我的文本

下一篇: 清除搜索突出显示autocmd BufWrite