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.
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:(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:
So running it on the following (where the
+
lines are selected)With the above
normal @q
command, produces:You can add the function below to your
~/.vimrc
or simply copy it on your browser and running:@+
The advantage is that you can apply any macro on the visual selection. You need to give the macro letter as argument, like:
Select the lines then press
:
to enter command mode. Vim will automatically fill in'<,'>
, which restricts the range to the selected lines. For your example you can use the:s
command to do the swap:This will swap two words separated by a comma on every line in the visual selection.
You can also use
'<
and'>
like any other bookmark or line position, e.g. as part of a movement command, so in normal moded'<
will delete from the current cursor position to the start of the first line in the visual selection. The marks remain in effect even if the block is not longer visually highlighted.If you want to replay a recorded macro on every line the you need to execute the macro with the
:normal
command. Unfortunately the:normal
command does not operate on a range of lines, but you can fix that with the:global
command. This runs an:ex
command on every line that matches a regex, so you can do this:Explanation: