How do I run a substitution without overwriting my current search pattern?
Answer
:keeppatterns {command}
Explanation
The :keeppatterns modifier runs an Ex command — typically :s, :g, or :v — without modifying @/ (the last search pattern) or the command history. This means your current hlsearch highlight, n/N navigation target, and search history all remain untouched after the command completes.
How it works
:keeppatternsis a command modifier, placed before any Ex command that uses a search pattern- Without it,
:s/foo/bar/would replace@/withfoo, breaking your previous search highlights - With it,
@/is restored to its original value after the command runs
This is especially useful in scripts, mappings, and autocmds that perform housekeeping substitutions.
Example
Suppose you're actively searching for TODO items (they're highlighted across your buffer). You want to strip trailing whitespace without losing that context:
" Without keeppatterns — destroys your TODO search:
:%s/\s\+$//e
" With keeppatterns — TODO stays highlighted and n/N still work:
:keeppatterns %s/\s\+$//e
A practical autocmd to strip trailing whitespace on save without disrupting any active search:
autocmd BufWritePre * keeppatterns %s/\s\+$//e
Tips
- Combine with
:silentto suppress both the substitution count message and the pattern side-effect::silent keeppatterns %s/\s\+$//e - Works with
:globaltoo::keeppatterns g/debug/ddeletes debug lines without altering@/ - Check your current last search pattern anytime with
:echo @/