How do I run a substitute command without overwriting my last search pattern?
Answer
:keeppatterns %s/old/new/g
Explanation
The :keeppatterns modifier runs any Ex command without modifying Vim's last search pattern (stored in @/). This is especially valuable when you have an important search loaded — for example, you're using n/N to navigate matches — and you want to perform a substitution without losing that search.
How it works
:keeppatternsis a command modifier that wraps any following Ex command- Without it,
:s/old/new/greplaces@/withold, affecting subsequentn/Njumps and highlighted matches - With
:keeppatterns, the substitution runs normally but@/remains unchanged after it completes
Example
Suppose you searched for function and are navigating all occurrences with n. You want to fix a typo elsewhere without losing your search:
/function
" navigate with n/N...
:keeppatterns %s/recieve/receive/g
" @/ is still 'function', n/N still work
Without :keeppatterns:
:s/recieve/receive/g
" @/ is now 'recieve' — your 'function' search is gone
Tips
:keeppatternsworks with any Ex command that touches@/, including:globaland:vimgrep- Combine with
:silentfor completely unobtrusive batch fixes::silent keeppatterns %s/foo/bar/ge - In scripts and functions,
:keeppatternsis best practice to avoid surprising the user's search state - Check the current last search with
:echo @/