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

How do I create a macro that repeats itself automatically until it can no longer proceed?

Answer

qq{actions}@qq

Explanation

A recursive macro ends by calling itself, so it loops automatically without you pressing @q repeatedly. Because Vim aborts macro execution on any error—a failed motion, a pattern that finds no match, reaching the end of the file—the recursion stops naturally when the macro runs out of work. No counter or conditional needed.

How it works

Record the macro so its last keystroke calls the same register it is stored in:

qq{your actions}@qq
  • qq — start recording into register q
  • {your actions} — the transformation to repeat
  • @q — call register q from inside the recording (the recursive step)
  • q — stop recording

When you run @q, Vim executes the body, then hits @q again, loops, and continues until something in the body raises an error (end of file, failed search, etc.).

Example

Convert every line in a buffer to uppercase:

qqVUj@qq
  • V — select current line
  • U — uppercase the selection
  • j — move down one line (fails on the last line, halting recursion)
  • @q — recurse

Run gg@q to start from line 1 and process the entire file in one shot.

Tips

  • Place the self-call at the very end of the body so an early error stops the loop cleanly
  • Start with gg@q to process the file from the top
  • A failed search (/pattern<CR>) also terminates the loop, making patterns like gg@q safe for conditional transforms—the macro halts when no more matches exist
  • Use a different register (e.g., qa...@aq) to avoid overwriting your q macro

Next

How do I switch between character, line, and block visual selection without starting over?