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:
- Press F3 to start
- Do the keyboard sequence
- Press F4 to close
- 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.
- Create a new .el file in the folder where you keep the other manually installed Emacs extensions, for example
kbd-macros.el
- Insert named macros there. (They look like primitive Lisp code)
- At the bottom of the file, write
(provide 'kbd-macros)
where the namekbd-macros
is the same as the name of the file you created - 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.