---
title: Recursive Macros in Vim
teaser: |
  Write a recursive Vim macro with `qqq` to clear the `q` register,
  `qq` to start recording the macro,
  doing your work,
  invoking the macro recursively with `@q`,
  stop recording the macro with `q`,
  and then invoking the macro with `@q`.
tags: vim
author: Rich Rines
published_on: 2014-01-17
---

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](https://thoughtbot.com/upcase/the-art-of-vim).
