I want :nohl to be run automatically whenever I run :w.

How can I set this up?

I tried

autocmd BufWrite * :nohl

in my vimrc but that's not working

Apparently (from comments, thanks D. Ben Knoble)

Theres a note in the help somewhere about how you cant use nohl in autocmds

So how can I do it without autocmds?

  • 1
    Theres a note in the help somewhere about how you cant use nohl in autocmds – D. Ben Knoble Nov 29 '18 at 3:24
  • 3
    it is at :h function-search-undo – Christian Brabandt Nov 29 '18 at 6:49

Indeed there is this note at :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.

Which also applies to auto commands, so as you noted, :au BufWritePre * :nohls won't work.

However, you can trick Vim with using the feedkeys() function. I think the following should work (and does from my limited testing):

au BufWritePre * :call feedkeys(":nohls\n")

This will inject the command directly into Vims typeahead buffer and won't be marked as coming from a function that needs to be undone once the auto command returns.


For the convenient, I usually save the file whenever I press the ESC so that I mapped ESC like this: map <esc> :w\|:noh<cr> The ESC functionality still working normally.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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