Can one associate a regex query with a particular file, so that whenever that file is opened, the query (e.g., /text) is run, causing all instances of text to be highlighted? I considered using modelines for this purpose but they only accept option settings. Is there another mechanism whereby an arbitrary search can be run upon loading a specific file (perhaps through use of autocmds in an adjunct .vimrc file placed in the same directory as the file in question)?


You were on the right path with your autocmd hunch. However, this problem is complicated by :h autocmd-searchpat (emphasis mine):

Autocommands do not change the current search patterns. Vim saves the current search patterns before executing autocommands then restores them after the autocommands finish. This means that autocommands do not affect the strings highlighted with the 'hlsearch' option.

However, a workaround is then described:

If you want an autocommand to set the search pattern, such that it is used after the autocommand finishes, use the ":let @/ =" command.

So, you could directly manipulate the last used search pattern with :let @/ = {pattern}

autocmd BufRead {filename} let @/ = '{pattern}'

With {filename} replaced with your filename, and {pattern} replaced with the pattern you wish to search for.

  • Thanks, though that does not seem to work for me on vim v8.1. The search does run but the instances of {pattern} are left unhighlighted despite hlsearch being set. Pressing n / N uses the last manual query, rather than the one in the autocmd. I am able to verify that the search runs when the file is loaded because if I search for text that is not present, vim displays an error upon opening the file: Error detected while processing BufRead Autocommands for "<path>": E486: Pattern not found: badpattern. The effect of the search appears to be discarded.
    – user001
    Oct 4 '20 at 0:24
  • Hmm... does using BufWinEnter instead work? Maybe you have to search after processing mode lines. Oct 4 '20 at 0:30
  • That also does not work. I also tried removing the modeline.
    – user001
    Oct 4 '20 at 1:12
  • I have edited my answer. Oct 4 '20 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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