Naming, Saving, and Executing Your Macros

In this section, we'll describe how to save macros so that you can use them in different editing sessions. To save a macro, bind it permanently to a key, and load it in subsequent Emacs sessions, follow these steps:

  1. Define the macro, if you haven't already.

  2. Type C-x C-k n (for name-last-kbd-macro). Now type a name for your macro and press Enter. A non-Emacs sounding name is best so that Emacs doesn't confuse it with one of its own commands. Once you've executed this command, Emacs remembers the macro for the rest of the editing session. To use it again, type the command M-x name (where name is the name you've chosen). Emacs treats your named macro like one of its own commands; it shows up in completion lists if you press Tab after typing a few letters of the name.

  3. If you want to save the macro definition permanently, you must insert the macro definition into a file. This could be your .emacs file or a macro file that you load through your .emacs file. Type C-x C-f filename Enter to find the file into which to insert the definition and move to the end of it by typing M->.

  4. Type M-x insert-kbd-macro Enter macroname Enter. Emacs inserts Lisp code that represents your macro.

  5. Add a line to .emacs make the key binding permanent. For example, if we called our macro transpose-names and bound it to C-x C-k T, we would add this line to our .emacs file (or other macro definition file):

    (global-set-key "\C-x\C-kT" 'transpose-names)
  6. If you save the macro ...

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.