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

How do I replay a macro multiple times in Vim?

Answer

10@a

Explanation

The 10@a command replays the macro recorded in register a exactly 10 times. By prefixing the macro replay command @a with a count, you can repeat any recorded macro as many times as you need, saving enormous amounts of repetitive work.

How it works

  • @a replays the macro stored in register a
  • Prefixing with a number like 10 tells Vim to execute the macro that many times
  • Replace 10 with any count and a with any register (az) where your macro is stored

Example

Suppose you record a macro in register a that deletes the first word of a line and moves down:

qa0dwjq

This records: go to beginning of line (0), delete word (dw), move down (j), then stops recording (q).

Given the text:

foo first line
bar second line
baz third line
qux fourth line

Running 3@a replays the macro 3 times, resulting in:

foo first line
second line
third line
fourth line

(Assuming the cursor started on bar second line.)

Tips

  • Use @@ to replay the last executed macro without specifying the register name
  • Use 100@a to run a macro "until it fails" — Vim stops automatically when the macro encounters an error (like reaching the end of the file), so using a large count is a common idiom
  • In visual mode, use :'<,'>normal @a to run the macro once on each selected line
  • Use :5,20normal @a to run the macro on lines 5 through 20
  • If the macro does not behave as expected, inspect its contents with :reg a and edit it by pasting with "ap, modifying the text, and yanking it back with "ayy
  • Make sure your macro ends with the cursor in the right position for the next iteration — this is key to making counted replays work correctly

Next

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