How do I run a macro a specific number of times without using a recursive macro?
Answer
{N}@q
Explanation
Prefix a macro invocation with a count to execute it up to N times in a single command. Vim stops early if any single execution encounters an error (such as a failed motion or end of file), so you can safely use a large count even if you're unsure of the exact number of repetitions needed.
How it works
{N}is any positive integer prefix@qexecutes the macro stored in registerq- Vim runs the macro N times sequentially, stopping immediately at the first failure
- The early-stop behavior is the key difference from manually pressing
@qN times — a failed sub-command aborts the remaining repetitions cleanly
Example
Suppose register q holds a macro that moves to the next line and appends a semicolon (j$a;<Esc>). To apply it to the next 20 lines:
20@q
If the file only has 12 lines remaining, Vim runs 12 times and stops when j fails to move down — no error message, no manual counting.
You can also use a deliberately large number as a "run until end" strategy:
999@q
Tips
- Use
@@to re-run the last macro (with count:5@@) - Combine with
:normal @qto apply the macro only to lines in a range::'<,'>normal @q - Recording the macro with error-prone motions (like
j) naturally limits the count, making this pattern very safe