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

How do I repeat a macro as many times as possible until it fails?

Answer

999@q

Explanation

Prefixing a macro invocation with a large count like 999@q tells Vim to run register q up to 999 times. Vim stops automatically as soon as any step in the macro fails — for example, when a search has no more matches or when a motion hits the end of the file. In practice, the large number is never reached; the macro runs exactly as many times as it can succeed.

How it works

  • 999 — a count large enough to exhaust any realistic file
  • @q — replay macro stored in register q
  • Vim aborts the loop silently at the first failure, leaving the cursor at the last successful position

This is simpler than a recursive macro and does not require re-recording. The trade-off is that unlike a recursive macro, it will not stop mid-macro if an early step succeeds but a later step fails — the count decrements only on full macro completion.

Example

Macro in register q that adds a semicolon to the end of each line then moves down:

A;<Esc>j

Running 999@q applies this to every remaining line in the file, stopping when j can no longer move down (end of file).

Tips

  • Any large number works — 1000@q, 9999@q — as long as it exceeds the file's line count
  • @@ replays the last macro and also accepts a count: 999@@
  • For a macro that must stop mid-execution on failure, use a recursive macro (qaqqa...@aq) instead
  • Use :set nowrapscan to prevent searches from wrapping around and accidentally continuing

Next

How do I get just the filename without its path or extension to use in a command?