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

How do I run a substitute command without changing my current search pattern?

Answer

:keeppattern %s/pattern/replacement/g

Explanation

When you run a :substitute command, Vim updates the search register (@/) with the substitute pattern, which changes your hlsearch highlighting and affects n/N navigation. The :keeppattern modifier prevents this — the substitution still runs, but your previous search pattern stays intact.

How it works

  • :keeppattern — modifier that tells Vim not to update the search register
  • %s/pattern/replacement/g — a normal substitute command that follows it

The substitute executes identically, but @/ retains whatever pattern you had before. This is especially useful in scripts, functions, and autocommands where you do not want side effects on the user's search state.

Example

Suppose you searched for /TODO and have matches highlighted. Now you want to clean up trailing whitespace without losing your TODO highlights:

:keeppattern %s/\s\+$//e

After running this, n still jumps to the next TODO match, and your highlighting is unchanged.

Tips

  • Particularly valuable inside autocmd and function definitions where you want to avoid side effects
  • Combine with e flag to suppress "pattern not found" errors: :keeppattern %s/old/new/ge
  • Works with any Ex command that modifies the search pattern, not just :substitute
  • In Vimscript functions, consider always using :keeppattern for substitutions to avoid surprising the user

Next

How do I ignore whitespace changes when using Vim's diff mode?