Recursive Macros in Vim

Rich Rines

Macros in vim can be a huge time saver, especially if they apply to a large number of lines. A trick I’ve been using recently is to use recursive macros to format large chunks of a file.

Let’s say we have the following list of thousands of dates:

10/30/2013
11/30/2013
12/30/2013
...

And we want to change each to the following:

10/30/2013 : 10-30-2013
11/30/2013 : 11-30-2013
12/30/2013 : 12-30-2013
...

Macro Recording Time

Let’s create the macro:

qqq             #clear out anything that may already be in the q register
qq              #start recording a macro and store it in the q register
y$              #copy to the end of the current line
A               #append the end of the current line
<Space>:<Space> #add a colon surrounded by spaces
<Escape>        #return to visual mode
p               #paste the date from the buffer
F/              #find the last instance of /
r-              #replace the / with a -
;.              #repeat the last find and replace
^               #go to the front of the line
j               #move down one line
@q              #make the macro recursive by having it invoke itself
q               #stop recording the macro

Now when you run @q vim will run the macro on every line until it finishes while you sit back and relax. I like using recursive macros because the loop will be exited if it fails to execute on a line. This improves the speed of making changes without risking applying it incorrectly throughout the file, provided you write your macros carefully.

What’s next

If you liked this post you should check out our vim screencast series The Art of Vim.