Repeating a Command

Zachary Kanfer has a nice post on how to repeat a command with a single keystroke. A familiar instance of this is the old-style keyboard macro execution. After defining the macro, you can execute it with 【Ctrl+x e】 and then execute it additional times by simply typing 【e】. Kanfer wants to be able to do this for his own commands.

The trick is to use a transient keymap. Once you use a key in a transient keymap, the keymap goes away so the key will revert to its old meaning. This is a handy trick that’s useful in other circumstances too. For example, here is my code for invoking the ping utility in a full-frame buffer and then restoring the previous window configuration.

 1: (defun net-utils-restore-windows ()
 2:   "Restore windows and clean up after ping."
 3:   (interactive)
 4:   (kill-buffer (current-buffer))
 5:   (jump-to-register :net-utils-fullscreen))
 6: 
 7: (defadvice net-utils-run-program (around net-utils-big-page activate)
 8:   (window-configuration-to-register :net-utils-fullscreen)
 9:   (let ((buf ad-do-it))
10:     (switch-to-buffer buf)
11:     (delete-other-windows)
12:     (set-transient-map
13:       (let ((map (make-sparse-keymap)))
14:         (define-key map (kbd "q") 'net-utils-restore-windows)
15:         map))
16:     (message "Type \"q\" to restore other windows.")))

After the ping operation finishes and we’ve inspected the results, we want to restore the previous window configuration by typing 【q】. As shown on lines 1215, we do that by defining a transient map. After typing 【q】 the transient map disappears and 【q】 reverts to simply being a letter.

This entry was posted in General and tagged . Bookmark the permalink.