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

How do I apply a macro to every non-blank line in the file while skipping empty lines?

Answer

:g/./norm @q

Explanation

Combining the :global command with :normal lets you run a macro on every non-blank line in one shot. The pattern /. matches any line that has at least one character, which naturally excludes empty lines. This is far more efficient than counting lines or manually stopping when the macro hits a blank line, and it scales to files of any size without needing to specify a count.

How it works

  • :g — the global command; iterates over every line in the buffer
  • /. — the match pattern; . matches any character, so this selects all non-empty lines
  • norm — short for :normal, executes normal-mode keystrokes for each matched line
  • @q — plays back the macro stored in register q; change q to whichever register you used

Example

Suppose register q holds the keystrokes A,<Esc> (append a comma at the end of the line). Given this buffer:

apple

banana

cherry

Running :g/./norm @q produces:

apple,

banana,

cherry,

The empty lines are untouched.

Tips

  • Replace q with any register name: :g/./norm @a uses macro a
  • Restrict to a subset of lines by changing the pattern: :g/^def /norm @q runs only on lines starting with def
  • To target blank lines instead, invert: :g/^$/norm @q
  • Use :g/./norm! @q (with !) to bypass custom key mappings during playback
  • Combine with a count to repeat the macro per line: :g/./norm 3@q

Next

How do I autocomplete macro-defined identifiers from header files while in insert mode?