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! @qapplies 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.
category: macros tags: #macros #registers #search #normal-mode #automation
Next
How do I open another file without changing the alternate-file mark (#)?
Related Tricks
How do I remove accidental Enter keystrokes from a recorded macro?
:let @q = substitute(@q, '\n', '', 'g')
How do I execute a macro from bottom to top over a selected range?
:'>,'<normal @q
How do I append keystrokes to a macro without re-recording it?
:let @q .= 'j'
How do I refactor a recorded macro by rewriting its keystrokes with substitute()?
:let @q = substitute(@q, 'foo', 'bar', 'g')
How do I append new keystrokes to an existing macro register without re-recording it?
:let @q .= 'A;<Esc>'
