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

How do I run a macro on every line in a visual selection?

Answer

:'<,'>normal @a

Explanation

The :'<,'>normal @a command executes the macro stored in register a on every line within the current visual selection. This is one of the most powerful macro techniques in Vim, letting you apply a recorded transformation to a specific set of lines.

How it works

  1. First, record a macro into register a with qa...q
  2. Select lines in visual line mode with V and movement keys
  3. Type :normal @a — Vim automatically prepends '<,'> to scope the command to your selection
  4. The macro runs once on each line in the selection, with the cursor starting at the beginning of each line

Example

Suppose you want to wrap each line in quotes. Record a macro:

qaI"<Esc>A"<Esc>q

Given the text:

apple
banana
cherry
date

Select all four lines with ggVG, then type :normal @a<CR>. The result:

"apple"
"banana"
"cherry"
"date"

The macro runs on each selected line independently.

Tips

  • If the macro fails on a line (e.g., a search within the macro finds no match), Vim stops on that line but continues to the next
  • Use :'<,'>normal @a for visual selections, or :%normal @a to run the macro on every line in the file
  • Use :10,20normal @a to run the macro on lines 10 through 20
  • Use :g/pattern/normal @a to run the macro only on lines matching a pattern
  • Always test your macro on a single line first before applying it to a range
  • The :normal command executes keystrokes as if typed in normal mode, so your macro runs in the same context as if you pressed @a manually on each line

Next

How do I edit multiple lines at once using multiple cursors in Vim?