Monthly Archives: January 2014

A Vim macro is just a series of characters.

I just learned something that gave me a EUREKA moment. The text you type in vim is also potentially instructions to vim and the instructions are just text. You can record a macro, a series of keystrokes that you play back, in Vim by typing:

  1. q
  2. a letter to record your keystrokes into – let’s use r
  3. then doing your keystrokes
  4. then type q again to stop recording.

So qr6jf|c3w|width=autoESC9jf|c3w|width=80%ESCq

  • record a macro r
  • go down 6 lines
  • move forward to a pipe character “|”
  • Change the next 3 words to say |width=auto then escape edit mode
  • go down 9 lines
  • move forward to a pipe character “|”
  • change the next 3 words to |width=80% then escape edit mode
  • stop recording the macro

To apply that macro or play it back: type @r. Vim will play all those keystrokes back from where you are in a document. That’s really useful when you want to automate something repetitive.

I changed my mind in how I wanted something to look in a wiki at work. 80 pages needed to be changed in a dumb way and I thought it might take longer to explain to people that it needed to be done than to just do it myself. I started by copying each page to vim to edit, running a macro of keystrokes to make the change, then pasting the result back.

Then I hit a couple of pages that were slightly off. They broke the macro, which was long and complicated. I read up on how to edit a macro so I didn’t have to reenter it.

That’s when I found out that the “r” that we stored that macro in is just a register, just like you might yank into. In vim you copy/paste by yanking into a register with a y and pasting with a p:

  • fyt; – store in register f the yanking of everything on this line til a semicolon
  • fp – take what is in register f and put it where the cursor is.

I typed “rp and saw my macro contents there on a line. I edited the macro to account for these new differences and then did tD to delete the entire line and store it in register t. Then I went to the top of the document by typing gg and applied my macro t by typing @t and it just worked!

How cool is that? There is no new scripting language to learn – all the text you delete and paste is potentially also instructions. This must be what lispers feel like all the time.

Now I wonder about trying to apply documents as instructions to edit themselves….