How do I run a substitute command without overwriting my current search pattern?
Answer
:keeppatterns
Explanation
Normally, any command that uses a pattern — including :substitute, :global, and :vimgrep — replaces the current search register @/ with the new pattern. This means your carefully crafted search highlight disappears the moment you run a :s command. :keeppatterns is a command modifier that tells Vim to restore the previous search pattern afterward, leaving your @/ register (and hlsearch highlighting) untouched.
How it works
- Prefix any Ex command with
:keeppatternsto prevent it from overwriting the search register :keeppatterns s/trailing_space \+$//— strip trailing whitespace without changing@/:keeppatterns g/^$/d— delete blank lines while preserving your active search- Works with any Ex command that internally uses patterns, including
:globaland:vimgrep - Especially useful in
.vimrcand scripts where silent cleanup should not affect user workflow
Example
You search for a function name (highlighted across the file), then realise you need to strip trailing whitespace:
/myFunction
Without :keeppatterns:
:%s/ \+$//e
This strips trailing spaces but your myFunction highlight is gone — n now jumps to trailing-space matches.
With :keeppatterns:
:keeppatterns %s/ \+$//e
Trailing spaces removed, myFunction still highlighted, n still navigates to the next match.
Tips
- Put it in your
BufWritePreautocommand for on-save cleanup without disrupting your search - Combine with
:silent!for completely invisible cleanup::keeppatterns silent! %s/ \+$// - The
/eflag on:ssuppresses the "no match" error; together they make a robust, non-intrusive formatter