Emacs: Collect keyboard macros

Keyboard macros in Emacs are ephemeral, but if you use them often, it makes sense to collect them. Here’s how.

The procedure of keyboard macros in Emacs is as follows:

  1. Press F3 to start
  2. Do the keyboard sequence
  3. Press F4 to close
  4. Press F4 again to launch the recorded keyboard sequence

The recorded keyboard sequence (macro) remains available until you record another one or restart Emacs. If there are several macros that are intensely useful, then it is a good idea to name them and save them. For this there are some kbd-macro commands.

To name the latest macro: M-x name-last-kbd-macro. (The name becomes a new M-x command, but it still only survives until restart of Emacs.)

To insert a named macro in a buffer: M-x insert-kbd-macro.

I have started collecting my macros (repetitive moves when editing HTML or other things) in a .el file among other manually installed Emacs extensions.

  1. Create a new .el file in the folder where you keep the other manually installed Emacs extensions, for example kbd-macros.el
  2. Insert named macros there. (They look like primitive Lisp code)
  3. At the bottom of the file, write (provide 'kbd-macros) where the name kbd-macros is the same as the name of the file you created
  4. In Emacs init file, add (require 'kbd-macros)

This way the saved keyboard sequences become permanent M-x commands in Emacs. An even better solution would be to learn to code Lisp properly, but saving macros is a start in that direction.

Leave a Reply

Your email address will not be published. Required fields are marked *