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

How do I run a macro on only the lines I've visually selected?

Answer

:'<,'>norm @q

Explanation

When you visually select lines and then type a : command, Vim automatically inserts '<,'> (the visual range marks) into the command line. Combining this with :norm @q lets you apply a recorded macro (q) to only the selected lines, rather than repeating it a fixed number of times with N@q. This is perfect when you need to transform a specific, non-contiguous or irregular set of lines.

How it works

  1. Record a macro into register q: qq ... q
  2. Visually select the lines you want to transform: V then j/k
  3. Press : — the command line shows :'<,'>
  4. Type norm @q and press <CR>
  5. Vim runs @q (execute macro from register q) on each line in the selection

Example

Macro in q: ^Isprintf("<Esc>A");<Esc> (wraps a word with sprintf("..."))

Before (lines 3–7 selected):

error_message
warning_text
info_log

After :'<,'>norm @q:

sprintf("error_message");
sprintf("warning_text");
sprintf("info_log");

Tips

  • You can use any register: :'<,'>norm @a for macro in a
  • To run the last used macro, use @@: :'<,'>norm @@
  • This technique also works with a line range: :5,12norm @q
  • Compare with N@q (count-based repeat) — range-based is more precise when you can't easily count the lines

Next

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