How do I refactor a recorded macro by rewriting its keystrokes with substitute()?
Answer
:let @q = substitute(@q, 'foo', 'bar', 'g')
Explanation
Recorded macros are plain text stored in registers, which means you can refactor them instead of re-recording from scratch. This is useful when a macro is almost correct but needs one repeated token changed everywhere, such as a delimiter, a field name, or a motion. Using substitute() on the register gives you a fast, reproducible way to patch macro logic.
How it works
:let @q = ...reassigns registerq, where your macro is storedsubstitute(@q, 'foo', 'bar', 'g')rewrites everyfoooccurrence in the macro text@qon the left side overwrites the original macro with the edited version'g'applies replacement globally within the register string
This pattern works because macros are just keystroke strings. You are not editing buffer text here; you are editing the macro program itself.
Example
Assume macro q currently inserts TODO markers like this:
TODO(api): fix endpoint
You decide the macro should emit NOTE instead of TODO. Run:
:let @q = substitute(@q, 'TODO', 'NOTE', 'g')
Now replaying @q inserts:
NOTE(api): fix endpoint
without rerecording any motions or insert-mode steps.
Tips
- Inspect a macro with
:echo @qbefore and after rewriting - Use
escape()when replacing characters that have regex meaning - Keep a backup first, for example
:let @z = @q