Some Emacs macro tricks

Keyboard macros are the Emacs feature that I wish every program had. Especially web browsers: having to carry out repetitive tasks in web apps always feels to me like a throwback to a less civilized era.

(More information about keyboard macros, for the uninitiated: see #2.)

Here are some useful macro-related commands that I recently learned to use:

Extending a macro. If you record a macro, then realize you forgot to add an important step at the end, you don't have to re-record it. C-u F3 replays the last macro and then lets you tack on more commands to the end of it.

For example, C-u F3 RET F4 replays the last macro and then appends RET to the end of it. (You can also use C-u C-u F3 ... F4 to extend a macro without replaying it again first.)

Editing a macro. For more intensive fixes or changes to macros, you can edit your most recent macro with C-x C-k C-e (kmacro-edit-macro-repeat). You get a buffer like the following, and you can remove keystrokes or add new ones:

;; Keyboard Macro Editor.
;; Press C-c C-c to finish; press C-x k RET to cancel.
;; Original keys: ESC c ESC f ESC f ESC f C-d RET<

Command: last-kbd-macro
Key: none


ESC c   ;; capitalize-word
ESC f   ;; forward-word
ESC f   ;; forward-word
ESC f   ;; forward-word
C-d   ;; delete-char
RET   ;; newline

Creating a macro from your keyboard history. If you just performed some task that you'd like to repeat, but didn't have the foresight to start recording a macro before you started, all is not lost. C-x C-k l (kmacro-edit-lossage) brings up a buffer (like the edit buffer above) containing your most recent 300 keystrokes, which you can pare down to create a new macro.

No comments:

Post a Comment