How do I run a macro a specific number of times at once?
Answer
{count}@{register}
Explanation
Prefix any macro execution with a count to repeat it that many times in a single command. Instead of pressing @q over and over, type 5@q to run the macro in register q five times, or 100@q to run it a hundred times.
How it works
{count}— A numeric prefix that tells Vim how many times to execute the following command@— Execute the contents of the specified register as a macro{register}— The register holding the recorded macro (e.g.q,a,1)
After the first run completes, Vim immediately replays the macro for each remaining count without any intermediate prompts. If the macro fails or hits an error mid-run, Vim stops and does not execute the remaining iterations.
Example
Suppose you have recorded a macro in q that appends a semicolon to the end of a line and moves down:
foo
bar
baz
qux
quux
With the cursor on foo, running 5@q applies the macro five times:
foo;
bar;
baz;
qux;
quux;
Without the count you would need to press @q five times, or type @q once and then press @@ (repeat last macro) four more times.
Tips
- Use a count larger than needed — Vim stops cleanly when the macro reaches the bottom of the file (if the macro tries to move past EOF the error ends execution)
- Combine with
qq...qto record a tight one-action macro, then fire it with a large count across the whole file - To repeat the last-used macro register without typing the register name again, use
@@