An Emacs script to define repeat maps.

17 May 2022, 21:46

Update [2025-11-09 Sun 14:26]: This script is obsolete since the introduction of defvar-keymap in Emacs 29.

With lengthy key-chords and prefixes, a common desire among Emacs users is being able to access a set of related keybindings in quick succession, or just the same one repeatedly.

A long-standing solution for repeating has been the repeat function, accessible via C-x z. However, more robust solutions for accessing collections of related bindings exist, including Hydra. The built-in transient package can also be used for repeated/grouped key-bindings, according to this Reddit thread.

However, in Emacs 28, we got access to repeat-mode, which provides built-in standardised support for repeating a lot of common key-bindings, including window resizing and error list navigation.

I investigated this and came up with a tiny ELisp script to add repeating keys based on repeat-mode: repeat-map-define.el.

This was also, excitingly my first ‘proper’ stand-alone ELisp script. Once you’ve loaded it, you can add keybindings like this:

(repeat-map-define
 defun-repeat-map
 '(
   ("a" beginning-of-defun)
   ("e" end-of-defun)
   ))

Corresponding to the global-map feature of Hydra, we can bind a key to the map itself to get access to the bindings with a prefix:

(global-set-key (kbd "C-x c") defun-repeat-map)

Note the lack of a quote before the reference to defun-repeat-map, since the map only exists as a variable and not a function. If a function is desired, the following somewhat ugly workaround can be used. I got this from the definition of vc-prefix-map.

(fset 'defun-repeat-map defun-repeat-map)

I’m pleased with the results of this, and feel like it aligns well with my notion of ‘vanilla Emacs’, which I discuss in my page about Emacs.