Vim Macro on Every Line of Visual Selection

Stefan Mai picture Stefan Mai · Jul 26, 2010 · Viewed 20.9k times · Source

I'd like to run a macro on every line in a selection, rather than totalling up the number of lines in my head. For instance, I might write a macro to transform:

Last, First

Into

First Last

and I'd like it to run on all these lines:

Stewart, John 
Pumpkin, Freddy
Mai, Stefan
...

Any ideas Vim gurus?

EDIT: This is just an example, obviously this is trivialy regexable, but there are other instances that come up that aren't quite so easy that I'd prefer to use macros.

Answer

rampion picture rampion · Jul 26, 2010

Suppose you had a macro q that ran (and remained) on a single line. Then you could run it on every line in your selection with:

:'<,'>normal @q

(if you already have a group of lines selected, hitting : produces :'<,'> on the command line)

For example, the following macro capitalizes every word but the first on a line:

:let @q="^dwgU$P"

So running it on the following (where the + lines are selected)

 0000: a long long time ago
 0001: in a galaxy far away
+0002: naboo was under an attack
+0003: and i thought me and qui-gon jinn
+0004: could talk the federation in
 0005: to maybe cutting them a little slack.

With the above normal @q command, produces:

 0000: a long long time ago
 0001: in a galaxy far away
 0002: naboo WAS UNDER AN ATTACK
 0003: and I THOUGHT ME AND QUI-GON JINN
 0004: could TALK THE FEDERATION IN
 0005: to maybe cutting them a little slack.