Tibor's Musings

Emacs Keyboard Macros

Need to run a certain operation on a bunch of lines? E.g. add some text after a certain column or to the end of every line in a buffer? With keyboard macros you can perform your line operations "live" for a line, while recording them, and then replay them for the other lines.

How to record a macro: position yourself to the beginning of line, press C-x ( to start recording keyboard macro, then do some stuff such as C-e to jump to end of line to write some text, then press C-a C-n to jump to start of the next line, then C-x ) to end macro recording.

How to replay a macro: C-x e to replay it once, then keep pressing e to replay it for other lines. Or, to replay it for the following 1234 lines, do C-u 1234 C-x e. Or, to replay macro to all lines in a region, do C-x C-k r.

One can combine macros with register counters in order to rapidly help Bart Simpson:

C-u 1 C-x r n a   ;; store number 1 in register `a'
C-x (             ;; start recording macro
C-x r i a         ;; insert contents of register `a'
C-f . I will not waste chalk. RET ;; enter our text
C-x r + a         ;; increment register `a'
C-x )             ;; end recording macro
C-u 7 C-x e       ;; apply macro 7 times

which will produce this output:

1. I will not waste chalk.
2. I will not waste chalk.
3. I will not waste chalk.
4. I will not waste chalk.
5. I will not waste chalk.
6. I will not waste chalk.
7. I will not waste chalk.
8. I will not waste chalk.

emacs