How do I replay macro q from command-line mode without changing @/?
Answer
:keeppatterns normal! @q<CR>
Explanation
When you replay macros from Ex commands, Vim can overwrite @/ (the last search pattern) depending on what the macro does. Wrapping macro execution in :keeppatterns lets you run automation while preserving your current search context, highlight behavior, and n/N navigation target. This matters in real cleanup passes where you alternate between scripted edits and manual search jumps.
How it works
:keeppatternstells Vim to execute the following command without changing the search register.normal!runs Normal-mode keys literally, ignoring user mappings, which keeps macro playback deterministic.@qreplays the macro stored in registerq.- Combined,
:keeppatterns normal! @qexecutes the macro once while keeping@/intact.
Example
Assume you already searched for:
TODO
and recorded macro q to normalize spacing on the current line. Running:
:keeppatterns normal! @q
applies the macro but preserves the existing TODO search pattern, so n still jumps to the next TODO rather than a pattern introduced by the macro.
Tips
- Use a range to replay on multiple lines:
:10,30keeppatterns normal! @q. - Prefer
normal!overnormalfor scripts so mappings do not change behavior across machines. - If the macro itself depends on prior cursor position, test on a small range first, then scale up.