Using emacs-lisp in emacs keyboard macros

2 minute read Published:

Powerful text editors, like vim, emacs, atom or even microsoft’s vs code, offer ways to automate boring stuff at hand. Repetitive work isn’t really something a human enjoys but it is exactly the kind of work that computers excel in.

So in emacs there are many ways to edit in interesting ways like Magnar Sveen’s beautiful package multiple-cursors. The more traditional,and my personally preferred, way is to use keyboard-macros (kmacro -* commands) to define ad-hoc ways to transform, edit and insert text.

The basic usage of kmacros is quite simple. Type C-x ( or F3 starts recording a set of actions and and C-x ) or F4 stops the recording. Then we can repeat the recorded actions by pressing either C-x e or F4 as many times needed or by giving a numerical prefix argument, ie C-u 5 C-x e will run the current kmacro five times.

An interesting application of this is to use some emacs-lisp to spice up our kmacros. So recently I was making a list of chapters I needed to study on some math textbook. Writing Chapter 1, Chapter 2 etc was quite tiresome so I used this simple trick:

I initiated kmacro record after running M-: (setq x 1). With this I had a variable that I could use as a counter. After inserting the markup for creating a list in org-mode and writing “Chapter” I inserted the x variable in the buffer with C-u M-: x. Then I incremented the variables value by running M-: (setq x (+ x 1)) and adjusted the position of the mark to an appropriate place for running the kmacro in a sequence. Then by running C-u 14 C-x e my list was created.

This is just one way of how kmacros can be spiced up, as there are many creative uses there! If a kmacro we compose seems general and useful enough we can even save them for later usage by invoking C-x C-k n for naming the last kmacro we used or M-x insert-kbd-macro to get the last kmacro’s definition inserted in a buffer, mainly init.el for future usage.