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

How do I run a macro on every line in the entire file?

Answer

:%normal @q

Explanation

To apply a macro to every line in the file, use :%normal @q. This uses the :normal Ex command with the % range (the whole file) to execute the macro stored in register q as if you had pressed @q on each line.

How it works

  • :% — the range covering the entire file (equivalent to 1,$)
  • normal — execute the following keystrokes as Normal mode commands on each line
  • @q — play back the macro stored in register q

Unlike running 999@q (which relies on repetition count), :%normal @q processes every line exactly once, even if earlier lines fail or are skipped.

Example

Suppose register q contains I// <Esc> (insert a comment marker at the start of the line). Running:

:%normal @q

Converts:

foo()
bar()
baz()

To:

// foo()
// bar()
// baz()

Tips

  • Use a specific range instead of % to limit scope: :10,20normal @q
  • Use :g/pattern/normal @q to run only on matching lines
  • If the macro encounters an error on a line, :normal continues to the next line (unlike 999@q which stops)
  • Press <C-c> to abort mid-run if needed

Next

How do I visually select a double-quoted string including the quotes themselves?