Sams Teach Yourself Emacs in 24 Hours

ContentsIndex

Hour 13: Macros

Previous HourNext Hour

Sections in this Hour:

 

Saving a Macro for Later Sessions


Only the most-recently-defined macro is available by pressing C-x e (call-last-kbd-macro). If you want to have several macros defined at a time, you need to give them names and, instead of pressing C-x e to execute them, you must press M-x and the name that you gave to the macro.

Naming a Macro

To get several macros available at a time or to save a macro to a file, you need to give it a name. Follow these steps to name a macro:

1. Record the macro as described previously in the To Do section "Recording and Executing Macros." Press M-x (name-last-kbd-macro), press Return, and type a name for the macro.

Tip - It's wise to prefix the name of the macro with your initials to avoid overriding an existing function that is defined in Emacs. If you want to name a macro that does some special opening of files, you could name it jkp-open-file (given that your initials are jkp).


2. When you have named the macro, you can access it by pressing M-x and its name. Until you define a new macro, it's still available by pressing C-x e (call-last-kbd-macro).

If you do not save your macro to your startup file, the macro will be forgotten the next time you start Emacs. This is fine for many macros, but if you have developed a macro that you think is your best piece of work ever, and you believe that this macro will save you lots of time in the future, it might be a good idea to save it for later sessions.

Saving a Macro to Your Startup File

This To Do task teaches you how to save a named macro to your startup file (that is, your .emacs file or a file specific for macros). Follow these steps:

1. Define and name your macro as described in the previous To Do task.

2. Switch to the file in which you want to save your macro.

3. Press M-x (insert-kbd-macro). Press Return and type the name of your macro.

If you save a macro in your .emacs file or another file read by your .emacs file, your macro will be available in all your Emacs sessions in the future. If you use the macro often, it might be wise to bind it to a key.

Tip - If you have developed a set of macros that you want to use on only a given file (or a limited set of files), you can save these macros to a separate file and insert the following lines at the end of the files that use these macros:

% Local Variables:
% eval: (load-file "macros.el")
% End:

The percent sign might be replaced with any text (for example the comment symbol in C files) and macros.el should be replaced by the name of the file in which you saved your macros. This is described in detail in Hour 24, "Installing Emacs Add-Ons."


Sams Teach Yourself Emacs in 24 Hours

ContentsIndex

Hour 13: Macros

Previous HourNext Hour

Sections in this Hour: