How do I run a substitute command without changing my current search pattern?
Answer
:keeppattern s/old/new/g
Explanation
When you run a :s or :g command, Vim updates the search register (@/) with the pattern you used. This means your previous search — the one you can jump back to with n or N — is lost. The :keeppattern modifier prevents this, letting you perform substitutions or global commands without disturbing your current search context.
How it works
:keeppattern— a command modifier that tells Vim not to update the search register with the pattern used by the following commands/old/new/g— the substitution runs normally, replacingoldwithnew, but@/retains whatever pattern you had searched for previously
This is especially valuable in scripts, mappings, and autocommands where you want to manipulate text without side effects on the user's search state.
Example
Suppose you searched for /function and are navigating matches with n. You need to quickly fix some formatting:
:keeppattern %s/\t/ /g
All tabs are replaced with spaces, but pressing n still jumps to the next function match — your search pattern is untouched.
Tips
- Works with
:g,:v, and:s— any command that would normally set@/ - Essential in
autocmdand custom functions to avoid polluting the user's search state - Combine with
:silentfor completely invisible operations::silent keeppattern %s/\s\+$//e