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

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

  1. Clear the register firstqqq starts and immediately stops recording into q, leaving it empty. This is essential: if q still holds an old macro, the @q call at the end would run that old content during recording.
  2. Record with a self-call at the endqq begins recording; perform your normal-mode actions; end with @q to recurse; then q to stop recording.
  3. Run once@q triggers the first iteration; subsequent iterations are driven by the recursive @q inside.
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 if q has 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

Next

How do I create my own custom ex commands in Vim?