Tutorial screencasts for Emacs

Keyboard Macros

| Comments

A little late but it’s finally up. We’re discussing keyboard macros in this episode.

Keyboard macros are Emacs’ way of recording and playing back a series of keys. It’s a useful feature that many people don’t sufficiently use. The excellent Emacs Rocks series of screencasts has some episodes on clever macro usage to reduce the number of keys needed to perform some kind of task.

The H.264 version of the video for iOS devices is at http://archive.org/download/EmacsMovies/10-episode-keyboard_macros.mkv.

Topics covered

  1. C-x ( and C-x ) to start and stop recording macros. With prefix arguments C-u and C-u C-u, you can append to existing macros.
  2. C-x e to replay macros. You can do this a number of times in one shot using prefix arguments. Also, the apply-macro-to-region-lines function to apply a macro to all lines in a region.
  3. The C-x C-k C-i chord to insert the macro counter while recording a macro. Modifying the macro counter using C-x C-k C-a and C-x C-k C-c.
  4. The C-x q command to stop while playing back a macro so that you can enter some text or make minor variations.
  5. The C-x C-k n to name the last macro and C-x C-k b to bind the last entered macro to a key. Finally, insert-kbd-macro to actually insert a macro as elisp into your current buffer so that you can save it for future use.

The F3 and F4 keys offer a convenient combination of the basic macro record and playback functions.

F3 stands for kmacro-start-macro-or-insert-counter. When it is hit the first time, the effect is the same as C-x ( (i.e. start recording a macro). While this is going on, if it is hit again, it will work like you hit C-x C-k C-i (i.e. insert the macro counter). F4 is bound to kmacro-end-or-call-macro. This will, if hit while a macro is being recorded, end the recording process. Here, it is similar to C-x ). If hit while a macro is not being recorded, it will work like C-x e and call the last recorded macro.

Macros are a little expansive so I took some liberties filtering out some of the features that I thought were not that useful. These are

  1. Editing macros.
  2. Interactively editing macros
  3. The macro ring which contains all the macros created so far.

I might do another screencast describing these but the manual page is explanatory and the things which I have covered will suffice for day to day usage.

Futher reading

  1. The emacs manual page on macros
  2. The wiki has a page on macros that contains a lot of useful snippets and other little goodies that can improve your experience.
  3. Xah Lee has a page on macros with some practical examples that he uses.
  4. The Emacs Rocks series of screencasts has some nice examples of macro magic.