Skip to content

Give every Emacs key sequence prefix the power to be "sticky"

License

Notifications You must be signed in to change notification settings

meedstrom/deianira

Repository files navigation

Deianira

Bust of Hercules and Dejanira MET DP812684

A hydra-based which-key banisher. In some ways the opposite of hercules.el (a “which-key based hydra banisher”). In Greek myth, Hercules slew the beast called Hydra, but was then slain himself by the princess Deianira.

Paradigm

Imagine that after you press the Control key, Emacs behaves as if Control is still pressed for everything you do next, and then that if you press Meta, Emacs switches to behaving as if Meta is pressed. That’s basically what this package supports.

By itself, that isn’t revolutionary, but the details come together into a whole new input paradigm.

Implementation

  1. All existing key bindings get copied into hydras.
  2. Control, Meta, Super (and Alt and Hyper if you have them) all become “leader keys” which spawn a hydra specific to each.
    • You may know that Spacemacs and Doom Emacs have a thing with the Space key. That’s a leader key. You get up to five of them. Why we abuse the modifier keys this way will become apparent, read on.
  3. “Homogenized keymaps”: we forbid any difference between keys such as C-x C-e and C-x e; we bind both to the same command, so it won’t matter if you keep holding down Control or not.
    • Necessary since I want every keybinding to be typeable by pressing each key in isolation separately, e.g. the sequence <ctl> x e maps to C-x e, but a sequence like <ctl> x <ctl> e would have 4—count them, 4—isolated key presses and releases in sequence. That’s Just Bad, so we rule it out and are left with no obvious key sequence that would map to C-x C-e. Plus, we use the Control key to restart the input sequence, often useful.
  4. Forbid mixing modifiers: we don’t allow key sequences with more than a single modifier, like C-M-f, M-% or C-c M-o. I find these gratuitously painful, and anyway there’s no way to bring them over to our hydra system without sacrificing other aspects.

Consequences

  1. We can do what I’ll coin “transient exits”: When the Control hydra is active, we can still type e.g. M-f to move forward by word, without exiting the Control hydra. This applies to all our hydras, even cases like the hydra for the Control-X-prefix, so instead of a sequence like C-x t C-n C-x t C-n C-x t… you can “stay in the Control-X-prefix” and do t C-n t C-n t… This would not be possible if we allowed more than one modifier in a hotkey.
    • In this example, repeat wouldn’t have helped since you’re cycling between two different commands, making it useless.
  2. I find it intuitive, compared to god-mode or Spacemacs/Doom. There is no weird new leader key to learn. You press the same modifier keys you always have – Control and Meta – and that’s all there is to it.
  3. We get many benefits of modal editors and skip some of their drawbacks.
    • For example, instead of entering a mode, running a command, exiting it, and returning to whichever mode you were in, as with the hypothetical sequence <ctl> <meta> f <meta> <ctl>, it’s faster to just type M-f in whatever hydra you were—and remain in that hydra. These transient exits are one of the most valid uses of modifier chords I’ve seen, otherwise so maligned for ergonomics.
    • In the rest of this document, I avoid the term “mode” but speak of root hydras (the root level of the Control, Meta, Super, Alt or Hyper trees).

My motivations were:

  • I wanted a modifier-free life, and I decided I don’t mind typing more to get that. Longer key sequences beat modifiers. But as a happy side effect of implementing the vision, I found we need surprisingly little extra typing this way, and sometimes even less.
    • I first started to learn Vim, lured in by the promise of “modes instead of Control-chords”, but what did I find? An excessive use of capital letters, about as uncomfortable as Control chords. So Vim is not chord-free at all, what a strange oversight. What’s the point? It’s just a version of Emacs that uses Shift instead of Control, and ships some pretty good hydras (what it calls modes) – that was Vim’s real killer feature all along. Thus began a glimpse of Deianira: I disagree so much with the idea of having “modes” to help you escape chords, and then typing chords within those modes anyway.
  • I asked myself as a thought-experiment how one would use Emacs with an OLKB Planck or other tiny keyboard. This constraint sprouted many ideas. I wondered if you could just bind all commands to sequences of lowercase letters, and with Deianira you can if you want. Please observe that no part of the design was sacrificed to support tiny keyboards – I actually prefer enormous keyboards – and the good fit is a side effect.

No “vendor lock-in”

  • We rely on an external Linux utility, kmonad, to turn Control, Meta and Super into leader keys, even while they continue to work as modifiers. But even should the utility stop working somehow, we won’t be left dead in the water. Our mass-remapping is done by the massmapper Emacs-Lisp library, which will always work, so your bindings remain in the location you were expecting. During a kmonad service outage, you’ll just have to do one of two things:
    1. Chord at first to start a key sequence, like a normal Emacsian (boo hiss). Even forgetting about the hydra system, the remaps you’ve made along the way remain accessible, and the bindings are not worse than before you started.
    2. Resort to xmodmap or similar basic tool to wholesale remap the keys normally labelled “Ctrl” and “Alt” to send different key events entirely. You can no longer chord, but it’s a small loss. In fact, I suggest this trick anyway as a set of training wheels. In my experience, it’s preferable to have hydras than modifiers.
  • If you like the aesthetic of the rules described under Implementation, but decide you don’t like the pseudo-modal behavior, you can forgo the hydras entirely. You enable only massmapper-mode but not deianira-mode. You can leave it at that, or you can nerd out about defining a lot more repeat-maps or hand-made hydras, and perhaps that’s better in some ways. Please blog about it!

Mandatory setup

(If you have a question, welcome to file a GitHub issue, or find my email in the source code.)

Getting the package

Minimally tested on Emacs 29 and 30.

The package is not yet on (M)ELPA. With straight.el (and the often-enabled setting straight-enable-use-package-integration), you can install the package like so:

(use-package massmapper
  :straight (massmapper :type git :host github :repo "meedstrom/massmapper"))
(use-package deianira
  :straight (deianira :type git :host github :repo "meedstrom/deianira"))

Alternatively with Doom Emacs, this goes in packages.el:

(package! massmapper :recipe (:host github :repo "meedstrom/massmapper"))
(package! deianira :recipe (:host github :repo "meedstrom/deianira"))

KMonad

You need kmonad, install it. Setup instructions follow.

Possible alternatives to kmonad:

The buggy and unmaintained xcape is NOT an alternative. Something so fundamental needs to be reliable; when I tried xcape, it could work for a while and then stop. This leads to giving up on Deianira.

What do I need kmonad for?

Emacs cannot detect the fact that you held down and released Control, Meta or Super, so we need some lower software needs to tell Emacs about it. Thus, we configure kmonad to send separate key events when you touch the keyboard this way.

It does not matter which key events will represent this, as the user almost never sees them printed in the echo area. The default choices are a bit unusual, discussed in the appendix.

Training config

Here is a basic KMonad config for a Surface Type Cover keyboard. As you’re probably not running that exact keyboard, edit the device-file field so it points to the correct keyboard under your /dev/input/by-id/....

(defcfg
 fallthrough true
 input (device-file "/dev/input/by-id/usb-Microsoft_Surface_Type_Cover-event-kbd")
 output (uinput-sink "My Deianira-enabling KMonad output"))

(defsrc
 lctl lmeta lalt ralt cmp)

(deflayer main
  KeyKatakana KeyHenkan KeyMuhenkan KeyMuhenkan KeyHenkan)

Here cmp is short for “Compose”, i.e. the Menu key, which is all the Surface Type Cover has in that location. If your keyboard has a real Right Win key, replace cmp here with rmeta.

(If you want to customize further, you’ll want to know that KMonad follows the Linux kernel names for Alt and Meta, what we Emacs folk know respectively as Meta and Super!)

BEWARE that this kills your ctl, alt and super keys for as long as the process runs, which may leave you unable to recover and need a reboot. You’ve been warned. To be safe, leave the process running as foreground in a terminal and close that terminal with the mouse when you need the effect to end.

Finally, once you come to agree with Super as Control (more on that later) you can just remove lctl and KeyKatakana here.

Full KMonad config

Once you’ve trained yourself out of the habit of chording your hotkeys, you can recover the normal chording behavior of Control/Meta/Super for those times it matters.

Change the config file above to look more like the below. The tap-hold-next magic is why we needed KMonad in the first place.

(defcfg
 fallthrough true
 input (device-file "/dev/input/by-id/usb-Microsoft_Surface_Type_Cover-event-kbd")
 output (uinput-sink "My Deianira-enabling KMonad output"))

(defsrc
 lctl lmeta lalt ralt cmp)

(defalias
  lc (tap-hold-next 200 KeyKatakana lctl)
  la (tap-hold-next 200 KeyMuhenkan lalt)
  ra (tap-hold-next 200 KeyMuhenkan ralt)
  lm (tap-hold-next 200 KeyHenkan lmet)
  rm (tap-hold-next 200 KeyHenkan rmet))

(deflayer main
  @lc @lm @la @ra @rm)

Basic initfile snippet

Put into your initfiles something like the following snippet.

It may look somewhat involved, but this isn’t a place for “sane defaults” or any defaults – I need to teach you how this stuff works.

(require 'massmapper)
(massmapper-mode)
(add-hook 'massmapper-keymap-found-hook #'massmapper-homogenize)
(setq massmapper-debug-level 1)
(setq massmapper-homogenizing-winners
  '(("C-c C-c")
    (find-file)
    ("C-x C-f" . global-map)
    ("C-x C-s" . global-map)
    ("C-x C-;" . global-map)
    ("C-h C-g" . global-map)
    ("C-c C-," . org-mode-map)))

(require 'deianira)
(deianira-mode)

If you have (setq hydra-is-helpful nil) somewhere in your initfiles, you’ll want to revert it to t for at least a while to see what’s going on.

Homogenizing

Let me introduce you to the most important variable, massmapper-homogenizing-winners. Take ownership of it; Deianira refuses to start if it’s nil. You’ll want to customize it gradually over time. Do you use C-x f or C-x C-f more? It’s hard to know when thinking about it, only experience will tell you. But this is absolutely key to becoming comfortable.

For more info, check the variable’s documentation – type C-h v massmapper-homogenizing-winners RET.

To see what it has done to your Emacs, type M-x massmapper-list-remaps RET. There is no way to revert these bindings except by restarting Emacs, but that buffer works as a lookup table for what you used to have on a key, if you merely want a reminder.

Superfluous entries in which-key

If you keep which-key, the following snippet will hide the superfluous entries.

;; Hide any key sequence involving more than one chord.  We have no reason to
;; see them after using `massmapper-homogenize'.
(with-eval-after-load 'which-key
  (cl-pushnew '((" .-." . nil) . t) which-key-replacement-alist
              :test #'equal))

Desktop-specific configuration

See the appendix sections:

Optional setup

Non-US keyboard

If you use Emacs with a non-US keyboard layout, you may want to customize these variables.

  • dei-hydra-keys
  • dei-all-shifted-symbols

Where is repeat?

Do you use the repeat command? Ensure it’s always there for you by binding hydra-repeat in hydra-base-map to the same key where you bound repeat in global-map.

Let’s say you already bound it to <f5> globally and want to keep it there. Then just add an eval-after-load so the end result looks like:

(define-key global-map (kbd "<f5>") #'repeat)
(with-eval-after-load 'hydra
  (define-key hydra-base-map (kbd "<f5>") #'hydra-repeat))

C-g alternative

Since C-g is normally bound to keyboard-quit, pressing g in the Control hydra will do what you’d expect (the same thing as C-g), but I advise against getting in the habit of using it. It’s so prone to muscle-memorization and when you’re in the Meta hydra or any other hydra, g will do something else. Some naive recourses could be:

  • 1. Bind g to keyboard-quit in every hydra, i.e. bind M-g, s-g, M-s g, C-x g and so on, or:
  • 2. Don’t get in the habit of pressing g in the Control hydra; press C-g always
  • 3. Always press Control and g sequentially.

All three have issues. #1 still will need C-g when no hydra is active. With #2, it’s a chord, and we wanted to be free of chords (and I’d realistically never keep up that discipline). Perhaps more natural is #3, but I find using it this way invites the question why it was ever on a two-key chord in the first place. If I may recommend a bold alternative:

  • 4. Bind some other key to do what C-g did.

Everyone’s got a different origin story with Emacs, but when you first learned C-g in the tutorial, I expect you must have been bemused. Maybe you got used to it and haven’t thought about it since, but it’s a bizarre binding. Such a fundamental action should only take one keystroke – on a convenient key such as Return or Escape.

I picked Escape. I put the following in my init file. After a short period of feeling like I was committing sacrilege, it felt natural like I’d been waiting to do it this way all my life. Try it!

(define-key input-decode-map (kbd "<escape>") (kbd "C-g"))

(Wondering how to do ESC ESC ESC now? Type C-[ C-[ C-[.)

Note that when Emacs freezes up, you cannot break the freeze with <escape>, and all of a sudden C-g is what you must type to break it, even if you had bound C-g to something else. No other key will do. I suspect it’s because Emacs stops looking up the keymaps at all working while it’s frozen and the only thing Emacs will react to is a true ^G character, much like a traditional terminal program can be interrupted with a ^C character. Try for yourself: eval (sleep-for 5) and try to break out of it. Escape won’t work, and C-g will.

One day, I hope we can set the hardcoded interrupt key as a build option if not a Lisp variable.

(ASIDE: Another thing disregards Escape: the M-x save-some-buffers prompt. This is a bug (https://debbugs.gnu.org/cgi/bugreport.cgi?bug=58808): it calls map-y-or-n-p which uses read-event rather than the more appropriate read-key. But very few things use map-y-or-n-p, and most of the time you’d type y or n, not C-g, so you don’t think about it. You may be glad to know it hardcodes q as an alternative cancel key.)

So C-g remains your “unfreeze Emacs” key. You can argue it actually should be on a separate key anyway. However, if that bothers you, the final solution is to use an external program like kmonad to remap the Escape key to send C-g long before Emacs or even Xkb is involved. This deprives non-Emacs apps of a functioning Escape, but the trick is to then install EXWM and use exwm-input-simulation-keys to translate C-g back into Escape!

(Feeling vendor-locked-in yet?)

Mass remapping

Super as Control

In case I ever sell you on deprecating the Control key, this hook setting copies all Control bindings to Super.

(add-hook 'massmapper-keymap-found-hook #'massmapper-define-super-like-ctl)

If there’s any inconsistency,

  • check your initfiles to see if you had directly bound any Super keys
  • otherwise, please open a GitHub issue

Benefits

  1. Luxury for an EXWM user: you can set all your exwm-input-prefix-keys, exwm-input-global-keys and exwm-input-simulation-keys to work only on Super bindings, ceding to other apps full control of Control.
  2. You can liberate the “nightmare keys” (see docstring of dei--nightmare-p): C-i, C-[, C-m, C-g. Because s-i, s-[, s-m, s-g are not magic aliases to TAB and ilk, you can rebind them at will and buy yourself more real estate.

Super as Control-Meta

An alternative if you didn’t buy my kool-aid above. This hook copies all Control-Meta bindings (i.e. keys starting with C-M-…) to Super, giving you a nice starting place for filling out Super.

(add-hook 'massmapper-keymap-found-hook #'massmapper-define-super-like-ctlmeta)

Of course it’s only relevant if you hate typing Control-Meta keys, like me. It is possible to make it so that pressing Control and Meta together pops up a special hydra for Control-Meta bindings, but in my opinion that’s a nasty complication: with three modifiers to start from already, you shouldn’t be lacking for available key sequences anyway. And if you do, upgrading the hardware (get a keyboard with thumb keys) is the way to go, not contrive software to do things like this. Chords are the enemy, why would you start a key sequence with one?

Prefix arguments: C-u M-d, Brutus?

The bindings for universal-argument, digit-argument and negative-argument present a conundrum.

  1. C-123456890 and M-123456890 are a huge waste of good keys.
    • Why are the ten keys M-1234567890 bound to digit-argument, but we’re too stingy to bind one more key, M-u, to universal-argument?
  2. Having universal-argument only on C-u breaks the ideal we were going for, of never mixing modifiers:
    • a. Ever had to type C-u 0 M-x? I wanted to jump out the window too.
    • b. It’s similar to our issue with C-g; the universal argument should be available under every modifier, and for us also every hydra. In other words if we stick to u as the final leaf, we want C-u, C-x u, M-u, M-s u, s-u etc. But we needn’t stick to u, more on this later.

Note: This is not a particular consequence of Deianira. The issue just sticks out like a sore thumb under our paradigm. Binding only C-u but not M-u, so you end up having to switch modifier midway through typing a command, as in C-u 0 M-x byte-recompile-directory… It’s made tolerable by the fact that all of C-1234567890 and M-1234567890 are digit-argument by default, so that particular example can be called thru M-0 M-x byte-recompile-directory (on GUI Emacs).

If we unbind the digit arguments, we can deal with the loss by making it extra convenient to use the universal argument. By default, to do M-d 9 times you have to type C-u 9 M-d. The solution, if sticking with C-u for universal-argument, we’ll make it also possible to type M-u 9 M-d and, in particular, M-u M-9 M-d (this last form provides most comfort). And in a hydra you can simply type u9d. Then it should be less scary to get rid of M-123456890.

You notice that in the above example, we needed to bind M-u, implying we bound every possible sequence ending in u: M-u, s-u, C-x u &c. I do not recommend it. If you pick a dedicated key such as <f12> instead, it’s an equal waste of keys in theory since you could’ve used that to start a key sequence, but:

  1. it’s a shame to spend an alphabetic character on this, they’re best reserved for semantics. The use of u can aid remembering commands like up-list and upcase-word.
  2. The universal argument isn’t important enough for such a good key as u, in my experience
  3. it’s nice to exploit Deianira by bringing in all key sequences under the umbrella of the root hydras that double as modifiers, so we wouldn’t make a sequence start on <f12> anyway

(“Really? F12 as universal argument?” But imagine this key is actually physically labelled Universal Argument, with real ink, as if it was a normal feature of keyboards, equally non-negotiable to the Tab key. You’d just hit it where it is and not even consider moving it to C-u…)

Another clean-feeling alternative could be the leaf =, i.e. the keys C-=, M-=, C-x = so on, since (on a US QWERTY keyboard) it’s right next to -.

I find the negative argument the most useful of them all, so I keep the leaf - bound in every hydra (just like having C--, M--, and company) but if you want to really conserve keys, I suggest picking a location for the universal argument such that it is easy to type together with -. On my laptop, <print> is suitable since it’s just above and to the right. Or you could relocate negative-argument itself to, let’s say, <f11>, with universal-argument on <f12>.

Here is an example fix including moving universal-argument to C-=, M-= and company, instead of C-u, M-u and company. It skips touching C-x = or any other long sequence ending in =, but I judge they won’t be needed (file an issue if you need it) since this fix ensures = will work inside any hydra as universal-argument anyway.

;;; Fix prefix arguments

(define-key global-map (kbd "C-u") nil)
(define-key universal-argument-map (kbd "C-u") nil)
(define-key universal-argument-map (kbd "=") #'universal-argument-more)
(define-key universal-argument-map (kbd "-") #'negative-argument)

(with-eval-after-load 'hydra
  (define-key hydra-base-map (kbd "C-u") nil)
  ;; in case you use non-Deianira-made hydras
  (define-key hydra-base-map (kbd "=") #'hydra--universal-argument))

;; Don't waste good keys (C-123456890) on digit arguments.
;; But make it more convenient to access them in other ways.
(let ((modifiers '("C-" "M-" "s-" "H-" "A-"))
      (digits (split-string "1234567890" "" t)))
  (dolist (mod modifiers)
    (define-key global-map (kbd (concat mod "-")) #'negative-argument)
    (define-key global-map (kbd (concat mod "=")) #'universal-argument)
    (define-key universal-argument-map (kbd (concat mod "=")) #'universal-argument-more)
    (dolist (d digits)
      (define-key global-map (kbd (concat mod d)) nil) ;; unbind
      (define-key universal-argument-map (kbd (concat mod d)) #'digit-argument))))

If you want to use a dedicated key like <print> instead, replace all occurrences of = with <print> in the code snippets so far, and add another line:

(define-key global-map (kbd "<print>") #'universal-argument)

Finally note that the Org setting org-replace-disputed-keys overrides M--, so you may want to leave it at nil.

Community packages override my M-1234567890!

Some packages override M-1234567890. If you want to prevent that, you can use snippets such as the one posted below. Although a cleaner strategy would be to:

  • wrt. global bindings, take back only C-1234567890 and s-1234567890 for personal use (it’s rare anything binds them), but don’t put any global bindings on M-1234567890
  • wrt. mode-specific bindings, take back M-1234567890 for personal use unless a package already binds them

You will not mind the fact that Magit binds M-2 in magit-section-mode-map if you don’t have anything at all on M-2 in global-map anyway. You can still make your own binding for M-2 in org-mode-map, another binding for M-2 in emacs-lisp-mode-map, another in eww-mode-map and so on.

;; Don't take my M-1234567890
(with-eval-after-load 'ranger
  (let ((digits (split-string "1234567890" "" t)))
    (dolist (d digits)
      (define-key ranger-normal-mode-map (kbd (concat "M-" d)) nil)
      (define-key ranger-emacs-mode-map (kbd (concat "M-" d)) nil))))

;; Don't take my M-1234567890
(with-eval-after-load 'magit
  (define-key magit-section-mode-map (kbd "M-1") nil)
  (define-key magit-section-mode-map (kbd "M-2") nil)
  (define-key magit-section-mode-map (kbd "M-3") nil)
  (define-key magit-section-mode-map (kbd "M-4") nil))

Quitters and quasiquitters

The following variables let you specify additional keys and commands that should exit the hydra and how it should happen. As with massmapper-homogenizing-winners, experience will tell you over time how to customize these. Read their docstrings so you’re aware of their existence.

  • dei-quitter-keys
  • dei-quitter-commands
  • dei-quasiquitter-keys
  • dei-quasiquitter-commands
  • dei-stemless-quitters
  • dei-inserting-quitters

Q&A

Can I keep which-key?

Yes.

Can I keep ergoemacs?

In theory. I haven’t tested it.

Can I keep xah-fly-keys?

Probably not.

Can I keep god-mode?

No.

What if instead of all this crap, you just use sticky keys and thoughtfully-made repeat-maps?

Not the same thing – for it to be comparable, you’d need something like god-mode, and you’d still need to setup kmonad or similar software so as to make the Control and Meta keys into entry-points for god-mode’s simulations of Control and Meta.

Do that and I’ll link your blog post here! Many things will be different, but I’ll leave the particulars for then.

Can you use this without the drastic “homogenizing” remaps?

No. Or there will be a lot of keys you can’t reach from hydra, and the paradigm is broken. Worse, if we have bastard sequences (see terminology) or different bindings for chord-once and perma-chord sequences (see terminology), it introduces a layer of doubt that interferes with you memorizing the sequence – as your muscle memory can’t “cross-train” between what happens inside the hydra and what happens outside it.

Note that we remap only in a structural way, according to a few fixed rules. Sometimes these rules poke us in the eye, but aside from them, we’re carefully non-opinionated. In another package, ergoemacs-mode, they move M-x to M-a, a wonderful improvement but the kind of decision Deianira doesn’t involve itself in.

Why do you hate Shift? Shift is great!

Shift has some surprising utilities. But to understand what makes it unique, here’s a thought experiment.

Imagine you make another key replace all the use cases of Shift. Let’s say you choose the s key, short for “Shift” because you’re sentimental.

Now instead of binding anything to say, <f1> K, you bind <f1> s k. You’ll note it’s the same number of key presses (3), and probably more comfortable.

It’s more comfortable than Shift because Shift has flaws:

  • Shift needs to be held down. (You can solve this with the “sticky keys” feature on many OSes.)
  • Shift is typically hit with the pinky finger. (You can solve this with a non-standard keyboard that gives it to a thumb.)

Even after solving both of these issues, the Shift-involved key sequence will only approach the comfort of the Shift-free key sequence, not meaningfully exceed it.

So why ever involve Shift in a hotkey? Especially considering you may not always have sticky keys, nor a specialty keyboard? Reasons I’ve found:

  1. Mnemonics
  2. Because it chords

I find Reason 1 insufficient (just my subjective sense of aesthetics—I’d rather have more nested sequences if that means they can all be all-lowercase), so let’s look at Reason 2. It’s subtle.

(The below is probably easier to understand after you’ve used Deianira)

With Deianira, the <f1> s ... keys get collected into a new hydra. This much you know.

Now if we want that hydra to faithfully reflect the Shift experience, we have to make a tradeoff. Should it reflect Shift-with-Sticky-Keys, or chord-Shift? The latter case is easy, it’s just Deianira’s default behavior (well, it doesn’t in fact look up any Shifted keys, but in principle).

For the former, we’d need a new type of “temporary” hydra where once you execute any key in it, you exit, but you go up only one level, i.e. you come back to the <f1> ... hydra rather than exiting fully.

If instead of the s key, you use the actual Shift key like a normal person, you get to choose depending on the context. Sticky Shift does not preclude chord-Shift on occasion. So you can hold down Shift and spam something while sitting in the <f1> ... hydra.

That is the unique utility of Shift. It’s not much, but it’s there. We could generalize this benefit with a massive round of key-chord.el mappings inside each and every hydra. I.e. make it so that when you’re in <f1> ... you can hit the chord sk as if typing s k but without actually entering the <f1> s... subhydra. It could be a wishlist feature.

However there seems a good alternative use of key-chord in the concept of Extend from the Colemak community, to vastly increase the number of things you can do without exiting a given hydra.

Vision

Which engine?

Despite the name, Deianira is not necessarily a Hercules killer, but could be remade to run on top of it. In fact, there’s a range of potential “engines” for us:

  1. Hydra
  2. Hercules (or just bare which-key)
  3. define-repeat-map
  4. Transient

(I’d like an engine-agnostic term for the concept shared by all these. Please hit me up. For now, the term “hydra” is short and useful: it can become verbs and adjectives like “hydraize”, “hydrable”, even other nouns like “hydratics”. A “head” is meaningfully different from a “key” and it’s nice to have that word. In addition, you can speak of “flocks” of hydras, and of “spawning” and “slaying” them.)

While it looks perfectly possible to rewire the package to use the other engines, I doubt we get any important benefit from options 2 or 3. What about option 4, tarsius’ Transient package? It may have a ton of potential, which I dare not imagine because I’ve spent enough years thinking about hotkeys and if I’m right, that would blaze a new path full of new questions.

Let me explain.

The famous collection of Transients known as Magit is, sayeth Internet Truth, a discoverable way to subtly modify any git command, beating the command line even for command line masters.

If we represent all of Emacs’ key bindings in Transients, the same way Magit swallowed all of Git’s commands, the benefit is unclear compared to doing the same with Hydra, because most of the time, you do not want to modify a command anyway. But that very fact may boil down to us now having separate commands for all of the following, because we did not have Transient back in the Screaming Eighties:

  • transpose-chars (C-t)
  • transpose-words (M-t)
  • transpose-sexps (C-M-t)
  • transpose-lines (C-x t)
  • transpose-sentences
  • transpose-paragraphs
  • transpose-regions
  • avy-transpose-lines-in-region
  • crux-transpose-windows

(Vimmers, bear with me)

These commands speak of one verb “transpose”, together with a variety of targets or objects “char”, “word”, “sexp”, “line” and so on. We see a similar pattern for the verb “kill”:

  • kill-word (M-d)
  • kill-line (C-k)
  • kill-sexp (C-M-k)
  • kill-buffer (C-x k)
  • kill-comment
  • kill-whole-line
  • kill-process
  • kill-emacs
  • ....

And so on it goes; the pattern is everywhere in Emacs. With such a cornucopia of predefined commands, it’s natural that they rarely need modifying.

Deianira cooperates with this; it just uncreatively brings in existing key bindings under a hydra, so you get precisely the subset of Emacs commands that had key bindings (a few hundred). By contrast, to properly use Transient’s potential, you’d find ways to call every one of Emacs’ 3,000+ commands, and maybe by accident create whole crops of new commands that don’t yet exist.

It’s easy to imagine a Transient that has just one key for the verb “transpose”, one key for the verb “kill”, one key for the object “char”, one key for the object “word” and so on, and then you add adverbs and adjectives. Once you get to this point, you’ve reinvented Vim.

But with the masterpiece that is Transient, maybe we could do better than Vim, beating the “Vim paradigm” even for Vim masters, like Magit beats the command line paradigm?

As heady as that vision sounds, I’m skeptical whether it’d do much better. That’s where I suggest Deianira can come in, one of a set of twins that together beats Vim at Vimgolf. Maybe that’s just a fever dream.

How easy would it be to change engine?

I don’t know, but Deianira would not become any simpler. If you imagine that using the Emacs 28 repeat-maps would uncomplicate the code – no, the lines of code would multiply. Hydra provides a satisfactory API.

Notes

Extra modifiers fix everything forever! Or?

If your keyboard is blessed with extra thumb keys, you may be able to acquire Hyper and Alt for a total of five leader keys. If so, you could move most of what you use from under the prefixes C-h, C-x, M-g, M-s etc to just H- and A-, but I believe the advantage is small if you already curate the C- and M- prefixes since:

  1. We have many discomfort mitigations in place.
  2. It isn’t actually good to spread your leaves under many different prefixes. It’s something you do to shorten key sequences, but because we have hydras, many keys are now already as short as they can be, and switching prefix becomes an extra action! The more well-filled one prefix, the less likely you’ll have to switch prefix while exploiting a hydra. Thus, you’ll benefit more from curating the 2-3 modifiers you already have, than from acquiring extra modifiers like Hyper and Alt.
  3. We have Backspace. On a standard keyboard, Control/Alt/Super aren’t in comfortable places, so supposing you find Backspace more comfortable, you may want to minimize the switching between root hydras, and instead travel among a single root hydra’s children, going in and out of nested key sequences with the help of Backspace.
    • very often, Backspace brings a subtle practical benefit, because for a variety of reasons, there will exist at least a few deeply nested key sequences in your keymap – much of MELPA binds them by default! When you’re in a deep sequence, it can be quicker to Backspace to reach a command than it would be to start over from a root hydra. Only if you truly ensured there were no deep sequences anywhere would the comparison become fair.

Hyper and Alt are not the panacea you think, because you remain highly vulnerable to the choice of where you bind each command: it could be good or it could be terrible, needing you to switch prefix very often. Commands you’re likely to call after each other should live in the same prefix. No amount of extra keys can brute-force this mandate for careful design. See also Vision.

Although extra arms would help a ton—if you had many arms, you’d not need any modifiers!

Terminology

Permachord and chord-once

The rule of homogenized keymaps imply the following:

  1. C-x k e is legal
  2. C-x C-k e is illegal
  3. C-x k C-e is illegal
  4. C-x C-k C-e is legal, but must be bound the same as #1.

I call the variant at #1 a chord-once sequence and the variant at #4 a permachord sequence. The act of “homogenizing” a binding is just making sure #1 and #4 are bound to the same command. By default, the command bound at #1 will be copied to #4, overriding what was on #4. There used to be a variable to control which way it would go by default, but experience showed some problems with the opposite default.

As for the middle variants, #2 and #3, I call them ‘bastard sequences’, because they result from a copulation no one wanted.

Bastard sequence

  • C-c p 4 C-d (projectile)
  • C-c C-e l o (org)

I call the above bastard sequences. Basically those that have you hit a modifier, release it halfway and maybe hit it again at different points. I suspect they arise accidentally or from historical reasons – at least I hope so.

Key sequence

Standard Emacs term. A sequence of keys of any number of steps, any of which may include chords. Technically, a single key such as <f3>, or a chord such as C-M-f, is a key sequence of one step.

Multi-chord

A chord involving more than one modifier, such as C-M-f.

Single-pair chord

A chord that only involves one modifier, such as C-f.

Mixed-modifier sequence

A key sequence that involves more than one modifier, such as C-c M-o or C-M-w (which is also a multi-chord).

Key

In Emacs vocabulary, a “key” can mean a chord such as C-M-f, which in my opinion is best thought of as three keys. Until we come up with a new term for what it is that’s happening thrice in C-M-f (“key presses”?), it can reduce confusion to pay attention to what is actually meant when someone uses this word.

Quitter

Quasi-quitter

Surprising powers

Power 1. You can use digit arguments on commands bound to the same digit, by backspacing out of the prefix-argument-adapted hydra that temporarily appears. Here we assume that <f12> is your universal argument key, what most people call C-u:

<ctl> x <f12> 3 <backspace> 3  ;; calls C-x 3 with argument 3

Power 2. You can insert prefix arguments anywhere inside a key sequence, rather than only at the start. These are all equivalent:

<ctl> x <f12> 3 <backspace> 3
<ctl> <f12> 3 <backspace> x 3
<f12> 3 <ctl> x 3

Power 3. When a desktop environment like GNOME clobbers your s-a chord, you can still access it by typing <super> a. Similarly, on many systems Alt+F4 tries to kill your Emacs, but you can type <meta> <f4> to reach its real binding, if you gave it one.

Known issues

Hint is misleading until after the first command

Noticed 2023-11-13. Will work on it.

The misleading hint also includes “hydra–digit-argument” on the number keys. They’re a lie and not meant to be shown.

The reason this issue could crop up is that I haven’t got back to dogfooding this package. (That’s also why the package is not published anywhere, yet somehow it got 15 stars…)

On start, no hydras for a little while

Yeah, it takes time to build the first flock (5-20 seconds, longer if you are interacting with Emacs in the meantime). Look at buffer *deianira*.

It used to take minutes and lock up Emacs, so I’m happy with that improvement :-) Further improvement is possible (see source comments on dei--try-birth-hydra) but it’s not my itch to scratch.

Hydra does not update instantly

If you run buffer-switching commands such as next-buffer while a hydra is active, getting a different major mode and keymaps, the hydra hint will not reflect this, but continue to reflect the last buffer you were in.

Aside from confusion, it’s usually not a problem because:

  • In a supermajority of cases, the difference is only visual: it’s the hydra hint that reflects the wrong buffer’s bindings. The keys still do what they should, since most of them are not bound to specific commands but to (call-interactively (key-binding KEY)), which results in the correct action.
  • By default, next-buffer (C-x <right>) and similar commands are under the Control-X-prefix, which is static and unchanging, i.e. it has no mode-specific anything, so there is no change to show in the hydra

If you do this under a prefix that changes a lot between major modes, like C-c, the next key can behave unexpectedly because:

  • It can happen that you expect a key to lead to a sub-hydra but it doesn’t.
  • The heads’ individual :exit flags also do not change, so they can be inappropriate for the current buffer, not reflecting dei-quitter-keys or related variables.

In principle, I can fix this so that Deianira serves up a fresh hydra on buffer change, but I haven’t found the matter a big deal.

Hydra hint width is wrong

Can happen when you resize the frame.

Pre-release TODOs

Training wheels

It’s REALLY hard to stop chording while the modifiers still work as they always did, because

  • Muscle memory
  • I’m in the habit of absently pressing the modifiers for no reason, which then unexpectedly pops up hydras, and I might accidentally call commands and get a bit overwhelmed with all the unintentional things happening

A few training wheels in mind, but the most important: disable the modifiers for a while.

  1. Disable the modifiers
    • Alt 1. Just plainly remap the lctrl key to KeyKatakana etc.
    • Alt 2. Turn the modifiers into Hyper or Alt when held, to block any combinations.
      • Because even when Ctl no longer does Ctl, pressing it together with f will still output f on screen – frustrating. If it were Hyper, you instead get the message “H-f is unbound”.
        • As a bonus, if your window manager supports it, you could have H-f send C-f in non-Emacs applications so they still work.

Appendix

I’m a layman. Why did this program take you years to write? It seems simple, what it does?

  1. KEYMAPS. Like a lot of software, Emacs binds keyboard keys to commands, but unlike most software, Emacs doesn’t just have one static list of key-bindings, but keeps hundreds of separate lists which it calls “keymaps”. Each may bind the same keys to different commands! To determine what a given key should in fact do, Emacs consults a composite of all the relevant keymaps for the current context, considering rules of precedence. One problem is that this composite changes rapidly, and we use a technology (hydra) that defines keys in a static way. A technical challenge then becomes to continuously update these hydras to reflect the current composite.
  2. KEY SEQUENCES. Also unusual among software, Emacs has key sequences. Aside from reflecting the keymap composite, we want to make hydras to reflect in which step of any sequence we are sitting. This is half the package’s raison d’etre. We must now connect the hydras to each other in an intuitive predictable way.
  3. AVOIDING MODIFIERS. Having solved 1 and 2, we’ve done a lot already to avoid modifiers. However, there may be bound two different sequences like Ctrl+X F and Ctrl+X Ctrl+F to different commands. And not only do we want to avoid holding down Ctrl, we want to tap it no more than once. So we bash together the lists of keys, into chord-free lists, so that we won’t need to press Ctrl+F in that example, nor even for that matter ensure that we press Ctrl and X simultaneously. Kind of simple, but there’s a horrific amount of edge cases, such as when one keymap binds a single command at a given location, and another keymap binds a whole sub-keymap instead, and it takes some thinking to understand what’s appropriate here, and we must plug in the user’s preferences along the way.
  4. PERFORMANCE. The package must continuously keep its state in sync with the truth of the context – not just the hydras (points 1 and 2) but the bashing together of key bindings (point 3). Since it could do so as often as every keystroke, and we don’t want any input latency, performance becomes a challenge, and we must devise ways to let the computer skip work without breaking the truthful sync.

After all of that is done, the program starts to be usable.

Out of GNOME hell

For users on GNOME or Ubuntu.

Okay, GNOME’s behavior when you press the Super key, addictive right? But Super-S does the same thing! There’s no need to clobber Super itself! Win back your Super key with this shell command:

gsettings set org.gnome.mutter overlay-key ''

You probably know that you can install Gnome Tweaks to access many hidden settings. However it’s not so helpful in discovering which setting is responsible for a misbehavior, like the above-mentioned. So it’s worth keeping a personal cheatsheet.


The KDE equivalent of the above:

kwriteconfig5 --file kwinrc --group ModifierOnlyShortcuts --key Meta ""

GNOME overrides anything you do with setxkbmap and many other commands, but there will be a gsettings command to do the same thing.

Instead of setxkbmap -option caps:menu, run this:

gsettings set org.gnome.desktop.input-sources xkb-options 'caps:menu'

Instead of xset r rate 200 30:

gsettings set org.gnome.desktop.peripherals.keyboard repeat-interval 30
gsettings set org.gnome.desktop.peripherals.keyboard delay 200

For EXWM users

If you want access to the hydras from EXWM buffers, configure either exwm-input-prefix-keys or exwm-input-global-keys so that they passthrough the keys defined in dei-ersatz-control, dei-ersatz-meta etc.

If you wish to change the keys

We default to the key events Henkan, Katakana, Hiragana and friends because almost all alternatives I’ve found needs the user to put in some elbow grease to make them work, especially on Wayland. If you type Japanese, you’ll need to bind something else. Here’s how.

The keys we’ve chosen to represent presses of Control/Meta/Super must be listed doubly – once in the kmonad config, and once in the following Customizable variables.

  • dei-ersatz-alt (default “<hiragana-katakana>”)
  • dei-ersatz-control (default “<katakana>”)
  • dei-ersatz-hyper (default “<hiragana>”)
  • dei-ersatz-meta (default “<muhenkan>”)
  • dei-ersatz-super (default “<henkan>”)

If you wish to change a keysym, change it in both places!

Which keysyms?

In my testing, these keys are predefined on Xkb’s us layout on the standard pc105 geometry. In other words, the config you get with setxkbmap -layout us . I find it likely these keys are defined under many other configs too, maybe even all configs?

Additionally… they actually work in my testing under Sway WM (a Wayland compositor), unlike many other predefined keys. If someone could explain why so many don’t work, I’d appreciate it.

Kernel keysymEmacs keydescXkb keysymKernel codeXkb code
KEY_SEARCH<XF86Search>XF86Search217225
KEY_MAIL<XF86Mail>XF86Mail155163
KEY_HOMEPAGE<XF86HomePage>XF86HomePage172180
KEY_NEXTSONG<XF86AudioNext>XF86AudioNext163171
KEY_KATAKANA<katakana>Katakana9098
KEY_HIRAGANA<hiragana>Hiragana9199
KEY_HENKAN<henkan>Henkan92100
KEY_KATAKANAHIRAGANA<hiragana-katakana>93
KEY_MUHENKAN<muhenkan>Muhenkan94102
KEY_HANGEUL<Hangul>122
KEY_HANJA<Hangul_Hanja>123
KEY_PAUSE<pause>

A keysym is not being recognized!

Unfortunately, this is unsolved. While many syms look like they should work, the majority did not for me. Hence the known-good table above.

I understand if it’s just that we cannot rely on xmodmap because xmodmap is obsolete, relying on pre-Xkb ideas of how things work. However, the issue crops up even with keysyms that exist by default in both the kernel and default Xkb table. And that’s a mystery to me.

It seems that interception-tools or dual-function-keys interfere with xmodmap settings and even reset Xkb options, so they look like possible culprits also for why some keysyms aren’t recognized. I remember xcape cooperating better in this regard.

Write a custom .xkb file

My next step is to write a custom .xkb file and see if that’s respected.

Custom .xkb files are also the most current and portable way to configure the keyboard (it works not only on Xorg but on wlroots-based Wayland compositors like Sway).

Start by generating a custom.xkb file with xkbcomp and modify it:

xkbcomp $DISPLAY custom.xkb

After editing to your satisfaction, load it back. This does not persist across reboots, so if you mess something up badly you can always reboot.

In Xorg like this

xkbcomp custom.xkb $DISPLAY

In Sway like this

sway input xkbfile custom.xkb

Alt and Hyper

I once thought it was just Wayland (and Microsoft and Apple) that lacked the concepts of Alt and Hyper, but even Xkb layouts don’t normally come with them!

The Linux kernel doesn’t define any syms for what Emacs calls Alt or Hyper, and I doubt that you can find any kernel keycodes that would be automagically recognized as such by Xkb and thereafter Emacs. We need an edit to the Xkb settings. With xmodmap that would have been a couple of simple commands, but it’s long deprecated, so here is the .xkb file method: https://wiki.archlinux.org/title/X_keyboard_extension#Meta,_Super_and_Hyper

(Addendum: looks like Xkb keycodes 92 and 203 are mapped to Mod3 and Mod5 by default?)

AUR

Note to self—and whoever hasn’t tried AUR.

In case I want to try AUR packages like interception-k2k, interception-xswitch or hawck-git, how to do it (the Arch wiki page is much too wordy):

sudo pacman -S --needed base-devel # run once
git clone https://aur.archlinux.org/interception-k2k-git
cd interception-k2k-git
makepkg
# replace this with the filename you produced
sudo pacman -U interception-k2k-git-0.0.0.r30.259a549-1-x86_64.pkg.tar.zst

Install KMonad on NixOS

Here’s how I did it on NixOS:

  1. set up Guix
  2. install kmonad into your user profile with guix install kmonad
  3. write this NixOS system service (assuming that your user is named me and your kmonad config file is named /home/kept/sysconf/kmonad/usb-Microsoft_Surface_Type_Cover-event.kbd)
systemd.services.kmonad = {
  enable = true;
  description = "KMonad";
  after = [ "syslog.target" ];
  script = "/var/guix/profiles/per-user/me/guix-profile/bin/kmonad /home/kept/sysconf/kmonad/usb-Microsoft_Surface_Type_Cover-event.kbd";
  serviceConfig = {
    Restart = "on-failure";
    RestartSec = 15;
  };
  startLimitBurst = 5;
  startLimitIntervalSec = 60;
  wantedBy = [ "multi-user.target" ];
};

dual-function-keys

On Arch, install like so:

sudo pacman -S interception-dual-function-keys

Let there be two config files, named ~/udevmon.yaml and ~/dual-fn.yaml (the filenames and locations don’t matter). Fill them with copypasta from the following sections.

(Users of Guix System have some alternate instructions)

udevmon.yaml

# note -- change the file path in here if necessary!
- JOB: "intercept -g $DEVNODE | dual-function-keys -c /home/me/dual-fn.yaml | uinput -d $DEVNODE"
  DEVICE:
    EVENTS:
      EV_KEY: [ KEY_LEFTCTRL, KEY_LEFTALT, KEY_LEFTMETA, KEY_RIGHTCTRL, KEY_RIGHTALT, KEY_RIGHTMETA ]

dual-fn.yaml

TIMING:
  DOUBLE_TAP_MILLISEC: 0  # default 150
  # TAP_MILLISEC: 200  # default 200

MAPPINGS:
  # Control  
  - KEY: KEY_LEFTCTRL
    TAP: KEY_KATAKANA
    HOLD: KEY_LEFTCTRL
    
  - KEY: KEY_RIGHTCTRL
    TAP: KEY_KATAKANA
    HOLD: KEY_RIGHTCTRL

  # Emacs calls this "Meta"

  - KEY: KEY_LEFTALT
    TAP: KEY_MUHENKAN
    HOLD: KEY_LEFTALT

  - KEY: KEY_RIGHTALT
    TAP: KEY_MUHENKAN
    HOLD: KEY_RIGHTALT

  # Emacs calls this "Super"

  - KEY: KEY_LEFTMETA
    TAP: KEY_HENKAN
    HOLD: KEY_LEFTMETA

  - KEY: KEY_RIGHTMETA
    TAP: KEY_HENKAN
    HOLD: KEY_RIGHTMETA

Test

Step 1. Test it. Execute the following shell command in some terminal. You can end the effect by interrupting the terminal with Ctrl-C.

sudo nice -n -20 udevmon -c ~/udevmon.yaml

Step 2. With the above program active, you should expect that tapping Ctrl, Alt or Super in Emacs will yield a message like “<muhenkan> is undefined”. Make sure you see that sort of message for all three modifier keys, both the left and right variants, so you know they all work.

Step 3. After verifying the above, type M-x deianira-mode RET and see what now happens when you press Ctrl, Alt or Super. You get hydras? Great!

All done, proceed to next chapter.

Please mind that this is just a test – later on, I’ll recommend some more lisp in your initfiles.

(ASIDE: If you want Alt and Hyper, see the appendix.)

(ASIDE: To use other keysyms than Katakana and friends, see the appendix.)

(ASIDE: Running this program temporarily resets my Xkb settings – I have no idea why, but don’t be surprised if this happens to you. There are no Gitlab issues about it so maybe I missed something. But running it on computer boot before Xorg, you don’t face the problem.)

For users of Guix System

I don’t yet know how to write an on-boot service, but here is how to create udevmon.yaml inside the system declaration with hardcoded store paths.

(packages
 (cons* ...
        interception-tools
        interception-dual-function-keys
        ...))
(services
 (cons* ...
        (extra-special-file
         "/etc/interception/udevmon.yaml"
         (mixed-text-file "udevmon.yaml"
                          "- JOB: \""
                          interception-tools "/bin/intercept"
                          " -g $DEVNODE | "
                          interception-dual-function-keys "/bin/dual-function-keys"
                          ;; NOTE: change this filesystem path to wherever you keep the file
                          " -c /home/me/dual-fn.yaml | "
                          interception-tools "/bin/uinput"
                          " -d $DEVNODE\"
  DEVICE:
    EVENTS:
      EV_KEY: [ KEY_LEFTCTRL, KEY_LEFTALT, KEY_LEFTMETA, KEY_RIGHTCTRL, KEY_RIGHTALT, KEY_RIGHTMETA ]
"))
        ...))

Execute the following Bash in some TTY and you’re ready to go. Re-execute on every boot.

sudo nice -n -20 udevmon -c /etc/interception/udevmon.yaml

(For those just running GNU Guix as a package manager, follow the Arch instructions instead, I think it’ll work.)

Thanks

I owe thanks to abo-abo and the other contributors to Hydra. If I’d had to wrangle god-mode or which-key to my purposes, I would have needed to know a lot more about the Emacs hotkey internals than I did starting out. With Hydra, I could just hack and experiment, and incrementally arrive to where I am. There’s something right about it, it’s a friendly API that allows you to iteratively learn as you bend it towards your needs, so it’s a fine member of the Emacs ecosystem and representative of its spirit.

About

Give every Emacs key sequence prefix the power to be "sticky"

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published