How do I edit the contents of a macro using Vimscript string functions without re-recording it?
Answer
:let @q = substitute(@q, 'from', 'to', 'g')
Explanation
Macros are stored as plain text in named registers, so you can manipulate them with any Vimscript string function. The :let @q = ... form assigns a new value to a register, and substitute(@q, 'from', 'to', 'g') replaces text within it — effectively editing the macro without re-recording.
This is far faster than re-recording a long macro when you only need to fix a small part, and is essential when the macro is too complex to reproduce easily.
How it works
@q— the current contents of registerq(the macro)substitute(@q, 'from', 'to', 'g')— Vimscript'ssubstitute()function applies a string replacement on the register contents:let @q = ...— writes the modified string back into registerq
Example
Suppose you recorded a macro in q that renames a variable oldVar. You later realize the variable is actually named oldVarName. Instead of re-recording:
:let @q = substitute(@q, 'oldVar', 'oldVarName', 'g')
Or to add a missing ! to a :write inside a macro:
:let @q = substitute(@q, ':w', ':w!', 'g')
Tips
- Use
:echo @qfirst to inspect the raw macro text before modifying it - To view a macro in a readable form, yank it into the buffer with
"qpon a blank line, edit it, then yank it back with"qyy - The same technique works for any named register:
@a,@b, etc. - Use
escape()if the macro contains special characters you need to match literally:substitute(@q, escape('a.b', '.'), 'axb', 'g')