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

How do I make a macro repeat itself until it reaches the end of the file?

Answer

qqq qq{commands}@qq @q

Explanation

A recursive macro calls itself at the end of its recording, causing it to repeat automatically until a motion fails (like j at the last line). This eliminates the need to count lines or guess a repeat count — the macro just runs until it naturally stops.

How it works

  1. qqq — clear register q first (this prevents the old macro from running during recording)
  2. qq — start recording into register q
  3. {commands} — perform your editing operations, ending with a motion that will fail at the boundary (like j to move down)
  4. @q — call the macro recursively (since we cleared it first, this does nothing during recording)
  5. q — stop recording
  6. @q — play the macro; it runs, moves down, calls itself, runs again... until j fails on the last line

The key insight is clearing the register first with qqq. Without this step, @q during recording would execute whatever was previously stored in q.

Example

Add a semicolon to the end of every line from the cursor to the end of file:

qqq
qqA;<Esc>j@qq
@q

This appends ;, moves down with j, and repeats. When j fails on the last line, the macro stops automatically.

Tips

  • Always clear the register first (qqq) to avoid unexpected behavior during recording
  • The macro stops when any motion in the sequence fails, so use j, n, w, or f as natural terminators
  • For more control, use } to jump by paragraph or ]] to jump by section

Next

How do I return to normal mode from absolutely any mode in Vim?