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.
:h function-search-undo
– Christian Brabandt Nov 29 '18 at 6:49