ARCHIVED: In Emacs, how do I define and use macros?

This content has been archived, and is no longer maintained by Indiana University. Information here may no longer be accurate, and links may no longer be available or reliable.

Emacs allows you to record one series of commands (called keyboard macros or kbd macros) and execute those commands as often as you need. If you want to record more than one macro, you must save the first one with a name before creating the next one. Macros are active only during the current Emacs session unless you save them to your .emacs file (saving them with names will not make them stick).

Note:
For information on how to issue the commands below in Emacs, see How keystrokes are denoted in Emacs

Recording a macro

First, press:

  C-x (

The message "Defining kbd macro..." will appear in the minibuffer (the line at the bottom of the Emacs window). Now enter the Emacs commands you would like to record as your macro.

When you're finished, press:

  C-x )

This will complete the macro, and "Keyboard macro defined" will appear in the minibuffer.

Using a macro

To execute the macro, press C-x e . This command executes the last macro you have defined.

Naming a macro

You can assign a name to a macro by entering:

  M-x name-last-kbd-macro

"Name for last kbd macro:" will appear in the minibuffer. Give the macro a short name. If Emacs reports an error, that means you entered a name that was already defined. Enter a different name. You will then be able to execute your macro by entering:

  M-x name

Replace name with the name you gave the macro.

Saving a macro

To save your named macro to your .emacs file so you can use it in the future, enter:

  M-x insert-kbd-macro

Then enter the name of your macro. The Lisp command for your macro will appear on the screen. It should look something like this:

  (fset 'name
     "macro")

In the above example, name is the name you assigned to the macro and macro is the text of the macro itself. Copy the Lisp command exactly and insert it into your .emacs file. You will then be able to use the macro in future sessions of Emacs.

At Indiana University, for personal or departmental Linux or Unix systems support, see Get help for Linux or Unix at IU.

This is document aaxw in the Knowledge Base.
Last modified on 2018-01-18 10:47:06.