How do I create a macro that runs continuously until it hits an error?
Answer
@q
Explanation
A recursive macro is a macro that calls itself as its last step, causing it to loop automatically until an operation fails (such as reaching the end of the file or finding no more matches). This eliminates the need to guess a repeat count with 100@q — the macro simply runs until it can't continue.
How it works
The trick relies on the fact that Vim stops executing a macro the moment any command fails. The setup is:
- Clear the register first:
qqq— records an empty macro intoq, ensuring@qinside the new recording does nothing on the first pass - Record the recursive macro:
qq→ perform your action → end with@q→q - Run it once:
@q
On each iteration, the macro performs its action then calls @q again. When any step in the action fails (for example j fails on the last line), Vim aborts silently and execution stops.
Example
Add a semicolon to the end of every line in a file:
qqq " Step 1: clear register q
qqA;<Esc>j@qq " Step 2: record recursive macro
@q " Step 3: run it
Breaking down the macro A;<Esc>j@q:
A;— append;at end of line<Esc>— return to normal modej— move down one line (fails on last line, stopping recursion)@q— call this macro recursively
Tips
- Always clear the target register before recording (
qqqfor registerq) so the embedded@qis a no-op during the first recording pass - Any failing motion or command acts as the termination condition:
n(no more matches),/pattern(no match), etc. - For very large files, a recursive macro can be slower than
:%norm @q; use the latter when performance matters - Use a letter register (
q–z) rather than numbered registers, which are overwritten by yank/delete operations