I have found a very good solution called xcape. From the README:
xcape runs as a daemon and intercepts the Control key. If the Control
key is pressed and released on its own, it will generate an Escape key
event.
This makes more sense if you have remapped your Caps Lock key to
Control. Future versions of this program might do that mapping for
you, but for now this is something that you have to do yourself.
In X11 (on console I don't know) you can do it by redefining the behaviour of the Escape key.
I looked at the "shift(break_caps)" definition to see how it works, and adapted it.
Look at this answer on xkb for more details on how/where to put the locally modified files and load them.
And for doing what you want, you need in the local symbols file (eg: ~/.xkb/symbols/mysymbols
) a section like this:
partial modifier_keys
xkb_symbols "esc_breaks_caps" {
key <ESC> {
type = "ALPHABETIC",
actions [Group1] = [
SetMods(modifiers=none),
SetMods(modifiers=Lock,clearLocks)
]
};
};
and in the local keymap file (eg: ~/.xkb/keymap/mykbd
; you can create it with setxkbmap -print > ~/.xkb/keymap/mykbd
) change the xkb_symbols
line to add +mysymbols(esc_breaks_caps)
.
You can now load it with: xkbcomp -I$HOME/.xkb ~/.xkb/keymap/mykbd $DISPLAY
and pressing Esc will remove the CapsLock state (actually, the effect happens on the release of Esc; I think that only modifiers keys have immediate effect; others the effect is after their release.)
Oh, if you want to also swap Escape and CapsLock keys; then use this instead (and you put "+mysymbols(esc_swap_and_breaks_caps)" in your mykbd file):
partial modifier_keys
xkb_symbols "esc_swap_and_breaks_caps" {
replace key <CAPS> {
type = "ALPHABETIC",
symbols = [ Escape, Escape ],
actions [Group1] = [
SetMods(modifiers=none),
SetMods(modifiers=Lock,clearLocks)
]
};
replace key <ESC> { [ CapsLock, CapsLock ] };
};
note the physical keys are <CAPS>
and <ESC>
; <CAPS>
(key engraved CapsLock in your keyboard) send Escape and <ESC>
(key engraved Esc) sends CapsLock, whith <CAPS>
(sending Escape) also unsetting capslock state
Best Answer
This keymod program reads keyboard events from a
/dev/input/eventX
device and injects most directly back into the kernel using the/dev/uinput
device. The caps lock behavior is special: if the key is pressed and released without touching another key, an Esc key is sent into the kernel. If another key is pressed while holding the caps lock, holding the (left) control key is emulated instead.Since the program takes control over the specified event device, being able to access the computer using e.g. SSH can be very handy when testing this. For example, pausing this program (using ctrl-z for example) will make sure you can't use your keyboard anymore (it has taken control over it exclusively and is now no longer active).