How do I edit the contents of a macro register without re-recording it?
Answer
:let @q = substitute(@q, 'old', 'new', 'g')
Explanation
When a recorded macro has a typo or needs a small tweak, re-recording the entire thing is error-prone. Instead, treat the macro register as a string and manipulate it directly with :let and substitute(). This gives you surgical control over macro contents without touching the rest of the sequence.
How it works
@q— reads the contents of registerqas a string:let @q = expr— writes a string back into registerqsubstitute(@q, 'old', 'new', 'g')— replaces all occurrences ofoldwithnewinside the macro
To inspect the macro first, use :reg q to see its raw contents, or :echo @q to print it.
You can also edit a macro interactively:
- Open a scratch line with
o<Esc> - Paste the macro:
"qp - Edit the text directly
- Yank it back:
0"qy$
Or set the macro directly from scratch:
:let @q = 'Iconsole.log("DEBUG: ");hh'
Example
You recorded a macro in q that types console.log(), but you want it to type console.error() instead:
:let @q = substitute(@q, 'log', 'error', 'g')
Then verify with :reg q — the register now contains console.error() in the macro sequence.
Tips
- Use
\nin the substitute pattern to match newlines inside multi-command macros - Combine with
execute()for complex transformations::let @q = execute('...') - Store macros in your
vimrcwith:let @q = '...'so they persist across sessions - Works for any register, not just
q