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:

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

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

record a macro r

go down 6 lines

lines move forward to a pipe character “|”

a Change the next 3 words to say |width=auto then escape edit mode

to say then escape edit mode go down 9 lines

lines move forward to a pipe character “|”

a change the next 3 words to |width=80% then escape edit mode

to 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:

“ f y t ; – store in register f the yanking of everything on this line til a semicolon

– store in the of everything on this line a “ f p – 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….

Share this: Share

Print

Email



Twitter

Reddit



Facebook



But wait, there's more