January 20, 2007 — jao

Gentle reader Marc Donner has sent me an email sharing one of his favorite emacs hacks:

(global-set-key [f10] 'start-kbd-macro) (global-set-key [f11] 'end-kbd-macro) (global-set-key [f12] 'call-last-kbd-macro) Yes, I could type C-x ( to start the macro and C-x ) to end the macro and C-x e to execute the macro, but that requires that my fingers be more nimble than they really are. Particularly because ( and ) are shifted keys. This way I can start a macro with a single button push, finish it with another, and then repetitively run it by pressing a third button over and over.

As it happens, Emacs 22 comes with the functionality Marc assigns to his F12 key built-in: press just e right after executing the macro the first time, as many times as you need. There’s also the possibility of using a numerical prefix to specify how many times the macro should be executed (as in M-10 C-x e to execute it ten times), and passing zero as the prefix will keep on (re)executing it until the end of the buffer is reached.

One can also achieve macro re-plays with the command repeat , bound by default to C-x z . repeat works quite a bit like Vim’s ‘.’: it, well, repeats the most recently executed command, and keeps repeating if you keep pressing z . So, instead of C-x e e e e e ... , one can C-x e C-z z z z... . Not as convenient, but this works in Emacs 21, and, besides, repeat is an interesting command on its own.

Saying that keyboard macro recording is a useful Emacs feature would be an understatement. You can record almost any Emacs operation and, therefore, keyboard macros can automate quite non-trivial tasks. For instance, i’ve just used them a couple hours ago to generate C function body stubs from their declarations in a header file. Just for the fun of it, here’s a screencast:

Note how you’re not limited to a single buffer, and how we use generic operations (like searching for next space to kill and yank the function’s return type). It’s also important to left the cursor in the right position for the next execution of the macro. At first you’ll make little mistakes, but fear not: you can actually edit the last recorded macro with kmacro-edit-lossage (Emacs 22 only). Just type C-xC-kl and you’ll be teletransported to a *Edit macro* buffer where you can edit your last keystrokes and record them as needed. Nifty, no?

As you get used to macros, you’ll surely discover many other tricks, but you can speed up your learning by means of the excellent pages KeyboardMacros and KeyboardMacrosTricks in the Emacs wiki. (One of my favourite tricks is using Elisp in macros to dynamically change what gets inserted). This Linux Journal article by Jesper Pedersen is also a good way to get you started as a power macro user.

Happy recording!