Emacs Lisp: Repeat Command by Key, set-transient-map

By Xah Lee. Date: . Last updated: .

Some command lets you press a key to call it again, without relying on your current global keymap nor any keymap.

For example, text-scale-adjust. You can call it by Alt+x text-scale-adjust. Once you call it, press + to increase font size, = to decrease, 0to resize to default.

Another command that have such key feature is repeat. Once called, press whatever key that invoked it will repeat the command.

Add a Repeat Key to Any Command

You can add a repeat key for any emacs command. Just write a wrapper function and add set-transient-map at end.

Suppose you want add a repeat key r to call forward-word (moving cursor to right by word) and l for backward-word

Solution:

(defun my-forward-word ()
  "move cursor right 1 position.
Press r will do it again, press l will move to left. Press other key to exit.
Version 2021-08-08"
  (interactive)
  (progn
    (forward-char )
    (set-transient-map
     (let (($kmap (make-sparse-keymap)))
       (define-key $kmap (kbd "r") 'my-forward-word )
       (define-key $kmap (kbd "l") 'my-backward-word )
       $kmap))))

(defun my-backward-word ()
  "move cursor left 1 position.
Press r will do it again, press l will move to left. Press other key to exit.
Version 2021-08-08"
  (interactive)
  (progn
    (backward-char )
    (set-transient-map
     (let (($kmap (make-sparse-keymap)))
       (define-key $kmap (kbd "r") 'my-forward-word )
       (define-key $kmap (kbd "l") 'my-backward-word )
       $kmap))))

Emacs Keys

Overview

How-To

Key Tips

Emacs Pinky

Misc