Endlessly repeating...

A quick intro to vim macros

9 January 2013

More of a note to self than anything but here's a quick introduction to macros in vim...

If you need to repeat a simple action in vim then you can easily do so by hitting the full stop key. The sequence A foo esc . . will result in the word foo being repeated 3 times (once typed in and twice repeated).

The simple repeating behaviour is helpful but it's no use if you need to repeat a series of actions involving motions - for that you need a macro. If you're anything like me you've already had an experience of macros when trying to quit vim and instead putting it into recording mode but bear with me, this can actually be useful. To start our simple example, enter a line of text then repeat that line a few times (yy to yank the line, 10p to paste it 10 times). I used the text "Every good boy deserves favour". Now go back to the start of the first line (gg) and decide on the change you want to make, I decided to change "boy" to "girl". Still in command mode enter qa to start recording into register a. Now carry out your change, move to the start of the next line, return to command mode and hit q to stop recording. In my example that meant doing w w c w girl esc j ^ q. Now it's a simple matter to repeat that by typing @a and of course you can repeat it multiple times by entering a number of repetitions followed by @a.