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

How do I record and replay a macro in Vim?

Answer

qa ... q ... @a

Explanation

Macros let you record a sequence of commands and replay them. Press qa to start recording into register a, perform your edits, press q to stop, then @a to replay.

How it works

  • qa starts recording all keystrokes into register a
  • Perform any sequence of Vim commands
  • q stops recording
  • @a replays the recorded macro
  • @@ repeats the last played macro

Example

To wrap each line in quotes:

  1. qa — start recording
  2. I" — insert " at the beginning of the line
  3. A" — append " at the end
  4. j — move to the next line
  5. q — stop recording
  6. 5@a — replay 5 times for the next 5 lines

Tips

  • Use any register a through z — you can have 26 macros stored at once
  • Prefix with a count: 100@a replays the macro 100 times
  • Edit a macro by pasting the register ("ap), modifying the text, and yanking it back ("ayy)
  • Recursive macros: qA appends to an existing macro in register a

Next

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