Defining a Macro

To start defining a macro, type C-x (. The abbreviation Def appears on the mode line, showing that you are in macro definition mode. In this mode, Emacs records all the keystrokes that you type, whether they are commands or literal text, so that you can replay them later. To end the macro, type C-x ); you leave the macro definition mode, and Emacs stops recording your keystrokes. Emacs also stops recording your keystrokes automatically if an error occurs or if you press C-g.

While you’re defining a macro, Emacs acts on your keystrokes as well as recording them: that is, anything you type while in macro definition mode is treated as a regular command and executed. While you’re defining a macro, you’re doing completely normal editing. That way you can see that the macro does exactly what you want it to, and you can cancel it (with C-g) if you notice that the macro isn’t really quite what you want. Unfortunately, it’s very difficult to edit a macro in Emacs. If you make a mistake, your only real option is to cancel the macro and start again. [56]

To execute your macro, type C-x e (for call-last-kbd-macro). Emacs then replays your keystrokes exactly as you gave them. You can have only one active macro at a time. If you define another one, this new one becomes the active macro and overwrites any that you defined before.

Example

Example

Here’s a quick example that shows how to define and execute a macro. We like to read printouts that are double-spaced and there’s ...

Get Learning GNU Emacs, Second 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.