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

How do I execute a macro from bottom to top over a selected range?

Answer

:'>,'<normal @q

Explanation

Running a macro over a range usually goes top to bottom, but that can break when the macro inserts or deletes lines. A bottom-up pass avoids index drift because each edit only affects lines above the current cursor position. This is a reliable pattern when refactors are structurally disruptive.

How it works

:'>,'<normal @q
  • '< and '> are the start/end marks of the last visual selection
  • Reversing them as '>,'< makes Ex process lines in reverse order
  • normal @q executes macro register q once per line in that range

The key idea is range direction: same macro, safer traversal order.

Example

Suppose macro q removes a line and appends data to the previous line. On a top-down pass, line numbers shift and later iterations can hit the wrong targets. Using the reversed range keeps each remaining target stable.

:'>,'<normal @q

Now the macro starts at the bottom selected line and works upward, so line deletions do not invalidate future iterations.

Tips

  • Use :normal! @q if mappings interfere with macro playback
  • Dry-run on a copied block first when the macro changes structure aggressively

Next

How do I lazy-load cfilter from vimrc without interrupting startup when it is unavailable?