Friday, November 16, 2007

Macro Registers

Most Vim users know about macros and find them useful; however, until recently, I didn't realize they are actually stored in the same registers we all know and love. For example, you create a new macro by pressing `qa'. You type in a series of commands that you would like to repeat, end the macro, done. But wait, you made a mistake. Well, you can easily edit the macro stored in `qa'. I typically issue a :new to open a new window, move my cursor to that window and then "ap. The contents of the macro are printed to the window. From there, you can edit the macro as needed and then yank the macro back in to the desired register by executing something like 0"ay$. Once yanked, the new macro will execute as you would expect it would.

6 comments:

Unknown said...

i do the paste-and-edit thing with my macros ALL the time. i also almost always use the 'q' register to record, since i rarely need more than one macro at a time, and this way i can start recording quickly with qq. finally, today, it occurred to me to do

:noremap qp Go^]"qp

so that typing qp will automatically put the q register contents on a new line at the end of the file for editing. then i can do

:noremap qd G0"qd$

to replace the macro with the edited version. since it's rare/easily-avoidable for me to use the d or p registers for macros, this mapping won't cause me to miss out on much. i think this might be worthy of inclusion in my vimrc...which is a sacred file ;)

Unknown said...

btw, ^] == <ESC>
you can enter the <ESC> digraph using <C-k>EC, or since this is an Ex command, you could just type <ESC>. but the digraph is just way cooler

Nick Knowlson said...

Christopher: Thanks, that's a really useful tip for editing macros! One more thing I added to make it more convenient was to make a mark assigned to q when I start editing a macro, and jump back to q when I'm done.

:noremap qp mqGo^]"qp
:noremap qd G0"qd$`q

I just want to point that I used the ` backtick right before that last q, not a single quote, in case it looks like that.

Cheers!

Anonymous said...

Great tips. I've been using macros forever but never knew I could edit them like this.

one slight improvement to Nick's version ...

:noremap qd G0"qdd`q

Now the last line containing the macro is deleted as it is yanked

Oh and by the way, ' and ` do the same thing!

Dinesh Sehra said...

Travis Whitton: Thank you for your wonderful editing macro post. I know I am going to use it extensively. Love vim.

Lucas Oman said...

Quick response to some of the comments:

Christopher: a map isn't really necessary for qp/qd. Simply assign the registers:

:set @p='Go^]"qp'

This makes it like any other macro, opening it to editing, reassigning, etc.

Anonymous: ' and ` are different! The former goes to the line and column of the mark, whereas the latter goes to the beginning of the line of the mark.

Cheers!