vimtricks.wiki Concise Vim tricks, one at a time.

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

  • :keeppatterns is a command modifier that wraps any following Ex command
  • Without it, :s/old/new/g replaces @/ with old, affecting subsequent n/N jumps 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

  • :keeppatterns works with any Ex command that touches @/, including :global and :vimgrep
  • Combine with :silent for completely unobtrusive batch fixes: :silent keeppatterns %s/foo/bar/ge
  • In scripts and functions, :keeppatterns is best practice to avoid surprising the user's search state
  • Check the current last search with :echo @/

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?