The Macro Ring

Although our latest macro is interesting, it's not really a general purpose macro. It is a temporary solution to a one-time problem. It saves you some work, but it isn't general enough to save and use again. On the other hand, our macro to transpose names is generally useful. We'd like to use it again. We'd like to bind it to a key. But it is no longer the "latest" keyboard macro.

As we mentioned earlier, Emacs has a macro ring much like the infamous kill ring. It's useful in the case we've just described, but it's also useful because of the fragility of the macro definition process. You create a macro and make a wrong move that rings the bell, and your macro is canceled. It's fairly easy to create a macro that does nothing. Perhaps the macro that you just created was wonderful, and this new nonfunctional nothing macro has supplanted it. Again, the macro ring is the solution. To delete a macro from the ring, type C-x C-k C-d (for kmacro-delete-ring-head). This deletes the most recently defined keyboard macro.

What if you want to swap the positions of two macros? Instead, type C-x C-k C-t (for kmacro-swap-ring). This transposes macros 1 and 2.

In a more general sense, you can cycle to the previously defined macro by typing C-c C-k C-p (for kmacro-cycle-ring-previous). To move the ring the other way, type C-x C-k C-n (for kmacro-cycle-ring-next). The familiar C-p for previous and C-n for next bindings are appended to the general macro keyboard prefix C-x C-k.

Before we ...

Get Learning GNU Emacs, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.