Discussion on: What's your favorite Vim trick?

vonheikemen profile image

My favorite so far is setting macros in command-line mode.

This post basically blew my mind. I don't actually use macros that often and when I do I always get stage fright whenever I start recording. But as the article says, macros are just registers that you can set and edit.

If I wanted to convert this.

const test = require('tape')

into this.

import test from 'tape'

I would start typing a command.

:let @i=''

Inside the quotes I'll write the keys that the macro would execute. The cool thing about this is that if you get something wrong you can undo, go back in the commands history, edit the macro and try again.

The final result would be this.

:let @i='^cwimport ^[f=cwfrom^[wdwds(j'

There is just no way I would get that right on the first try.

You'll have to be careful with special characters like "Escape". The way you get then in the command is by pressing ctrl+v first. For the escape character you would press ctrl+v first and then the escape key.

voyeg3r profile image
Sérgio Luiz Araújo Silva

Using double quotes you can use a better notation to indicate keystrokes, something like:

let @a="\<esc>0yyp\<c-a>ww150\<c-a>"

In order to test the above macro paste this on the firest line and run

on this line I have 1 and more 150
jkreeftmeijer profile image
Jeff Kreeftmeijer Author

Macros have been near the top of the list I’ve been planning to properly figure out for years now, I just never get around to it. I always have a hard time blindly recording macros with q<letter><commands>q.

I love the idea of writing macros in command mode, and having them available in the command history. That article looks great, too. Great suggestion!

phallstrom profile image
Philip Hallstrom

Brace yourself... you can still use your q...q command to record them as you go. Then, find a blank line somewhere and "qp and boom - your macro is right there. Tweak it, then highlight it and "qy and now @q will replay your new one.

Blew my mind when I figured out there was nothing special about qq.. it's just putting things into a buffer to replay.