Vim Macro on Every Line of Visual Selection

Viewed 25326

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.

3 Answers

You can add the function below to your ~/.vimrc or simply copy it on your browser and running :@+

fun! RunMacroOverSelection(macroname)
    execute "'<,'>normal @". a:macroname
endfun
com -nargs=1 Rover :call RunMacroOverSelection(<f-args>)
nnoremap <leader>r :Rover<space>

The advantage is that you can apply any macro on the visual selection. You need to give the macro letter as argument, like:

:Rover a
Related