How do I run a substitute command without overwriting my current search pattern?
Answer
:keeppattern %s/old/new/g
Explanation
When you run a :s or :%s substitute command, Vim updates the search register (@/) with the substitution pattern. This means your previous search highlight and n/N navigation are lost. The :keeppattern modifier prevents this, letting you perform substitutions while preserving your current search context.
How it works
:keeppattern— a command modifier that tells Vim not to update the last search pattern (@/) with whatever pattern the following command uses%s/old/new/g— the standard global substitution, replacing all occurrences ofoldwithnewthroughout the file
Without :keeppattern, after running :%s/old/new/g, pressing n would search for old. With :keeppattern, pressing n continues searching for whatever you had searched for before the substitution.
Example
Suppose you searched for /TODO and are navigating through TODO comments. You realize you also need to rename a variable:
" Your current search is /TODO — highlights are active
:keeppattern %s/myVar/myVariable/g
" Press n — still jumps to next TODO, not to myVariable
Tips
- This is especially useful in scripts, mappings, and autocommands where you don't want side effects on the user's search state
- Works with any Ex command that normally updates the search register, not just
:s - You can also use
let @/ = savedto manually save and restore, but:keeppatternis cleaner