vimtricks.wiki Concise Vim tricks, one at a time.

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

  1. Paste the macro: "ap pastes the contents of register a into the buffer as a line of text
  2. Edit the text: Use normal Vim editing commands to fix, add, or remove keystrokes in the macro
  3. Yank it back: "ayy (or 0"ay$ to avoid capturing the newline) yanks the edited line back into register a

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 a to inspect the current contents of register a before editing
  • Use 0"ay$ instead of "ayy to avoid including the trailing newline in the macro
  • Open a new scratch buffer with :enew before 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 (az) since macros and registers share the same storage

Next

How do I edit multiple lines at once using multiple cursors in Vim?