XKB – Make Ordinary Key Act as Modifier with xcape

xkb

To make Spacebar act as Ctrl under appropriate circumstances, GitHub page of xcape currently instructs as follows:

# Map an unused modifier's keysym to the spacebar's keycode and make it a
# control modifier. It needs to be an existing key so that emacs won't
# spazz out when you press it. Hyper_L is a good candidate.
spare_modifier="Hyper_L"
xmodmap -e "keycode 65 = $spare_modifier"
xmodmap -e "remove mod4 = $spare_modifier" # hyper_l is mod4 by default
xmodmap -e "add Control = $spare_modifier"

# Map space to an unused keycode (to keep it around for xcape to
# use).
xmodmap -e "keycode any = space"

# Finally use xcape to cause the space bar to generate a space when tapped.
xcape -e "$spare_modifier=space"

How to achieve this with xkb rather than xmodmap?

Best Answer

With Hyper_R in place of Hyper_L, it goes like this:

contents of ~/.config/xkb/keycodes/my-keycodes:

xkb_keycodes "xcape-special" {
    <HYPR> =  65;
    <SPCE> = 207;
};

Note: 207 is the default keycode for (virtual) Hyper_R key in the keycode table loaded on my machine.

contents of ~/.config/xkb/symbols/my-symbols:

xkb_symbols "xcape-special" {
    key <HYPR>  { [ Hyper_R ] };
    modifier_map Control { <HYPR> };
};

excerpt from ~/.xinitrc:

XKB_DIR="$HOME/.config/xkb"
XKB_SYMBOL_FILE="my-symbols"
XKB_KEYCODE_FILE="my-keycodes"

setxkbmap -layout "us+$XKB_SYMBOL_FILE(xcape-special)" \
    -keycodes "evdev+$XKB_KEYCODE_FILE(xcape-special)" \
    -option "" -print \
    | xkbcomp -I"$XKB_DIR" - "${DISPLAY%%.*}" >/dev/null 2>&1

xcape -e "Hyper_R=space"

This is not the only way to configure xkb. Configuration could probably be loaded from a single file with a single xkbcomp call. Subdirs of ~/.config/xkb/ merely follow the structure of /usr/share/X11/xkb/. The ... -print | xkbcomp ... part is somewhat convoluted but flexible. At the moment I'm unable to try a simpler setup.

Related Question