How do I edit a recorded macro in Vim?
Answer
"ap, edit, "ayy
Explanation
Vim stores macros in registers, which means you can paste a macro's contents into a buffer, edit it as regular text, and yank it back into the register. This three-step technique lets you fix mistakes in recorded macros without re-recording them from scratch.
How it works
- Paste the macro:
"appastes the contents of registerainto the buffer as a line of text - Edit the text: Use normal Vim editing commands to fix, add, or remove keystrokes in the macro
- Yank it back:
"ayy(or0"ay$to avoid capturing the newline) yanks the edited line back into registera
The macro in register a is now updated with your changes.
Example
You recorded a macro with qa that inserts Hello at the beginning of each line:
IHello ^[
(where ^[ represents <Esc>)
But you realize you wanted Hello: instead of just Hello. Paste with "ap, edit the text to change Hello to Hello: , then yank it back with 0"ay$. Now @a runs the corrected macro.
Alternative: direct editing with :let
You can also edit a macro using the :let command:
:let @a = 'IHello: \<Esc>'
Use \<Esc> for Escape, \<CR> for Enter, and \<C-w> for Ctrl-w within the string.
Tips
- Use
:reg ato inspect the current contents of registerabefore editing - Use
0"ay$instead of"ayyto avoid including the trailing newline in the macro - Open a new scratch buffer with
:enewbefore pasting the macro so you do not clutter your working file - Special characters like
<Esc>appear as^[when pasted — you can type a literal<Esc>in insert mode with<C-v><Esc> - This technique works for any named register (
a–z) since macros and registers share the same storage