How do I create a macro that repeats itself until it hits an error or end of file?
Answer
qq{cmds}@qq
Explanation
A recursive macro is one that calls itself at the end of its own body. Because Vim stops macro execution the moment any command produces an error (a failed search, end of file, etc.), a self-calling macro runs until it naturally hits a dead-end — giving you a simple loop that processes every matching line in the buffer without needing a count or a range.
How it works
- Clear the register first —
qqqstarts and immediately stops recording intoq, leaving it empty. This is essential: ifqstill holds an old macro, the@qcall at the end would run that old content during recording. - Record with a self-call at the end —
qqbegins recording; perform your normal-mode actions; end with@qto recurse; thenqto stop recording. - Run once —
@qtriggers the first iteration; subsequent iterations are driven by the recursive@qinside.
qqq " Step 1: empty register q
qq " Step 2: start recording into q
/TODO<CR> " jump to next TODO
I[x] <Esc> " prepend a checkbox marker
@q " recurse
q " stop recording
@q " Step 3: run — processes every TODO until search fails
Example
Before:
TODO: write tests
TODO: update docs
TODO: fix bug
After @q (macro prepends [x] to every TODO line then stops at EOF):
[x] TODO: write tests
[x] TODO: update docs
[x] TODO: fix bug
Tips
- The stopping condition is implicit: any error (no more matches, cursor at last line, etc.) terminates execution
- Always step 1 (
qqq) before step 2 — skipping it risks a runaway macro ifqhas old content - For safety on large files, use
{count}@q(e.g.100@q) to cap the maximum iterations - Recursive macros shine when the exact iteration count is unknown at record time