Extending the X keyboard map with xkb

martin f. krafft

xmodmap has long been the only way to mod­ify the key­board map of the X server, short of the com­plex con­fig­u­ra­tion dae­mon ap­proaches used by the large desk­top man­agers, like KDE and GNOME. But it has al­ways been a hack: it mod­i­fies the X key­board map and thus re­quires a base­line to work from, kind of like a patch needs the cor­rect con­text to be ap­plicable.

Worse yet, xmodmap weird­ness re­quired me to in­voke it twice to get the ef­fect I wanted.

When the re­cent up­grade to X.org 7.4 broke larger parts of my elab­o­rate xmodmap con­fig­u­ra­tion, I took the time to fi­nally ditch xmodmap and im­ple­ment my mod­i­fi­ca­tions as proper xkb con­fig­uration.

Background information#

I had tried be­fore to use per-user xkb con­fig­u­ra­tion, but could not find the an­swers I want. It was some­what by chance that I found Doug Palmer’s “Un­re­li­able Guide to XKB con­fig­u­ra­tion” at the same time that Julien Cristau and Matthew W. S. Bell pro­vided me the nec­es­sary hints on the #xorg/​irc.​freenode.​org IRC chan­nel to get me started.

The other re­source worth men­tion­ing is Ivan Pas­cal’s col­lec­tion of XKB doc­u­ments, which were in­stru­men­tal in my gain­ing an un­der­stand­ing of xkb.

And just as I am writ­ing this doc­u­ment, De­bian’s X Strike Force has pub­lished their In­put Hot­plug Guide, which is a nice com­ple­ment to this very doc­u­ment you are read­ing right now, since it fo­cuses on auto-con­fig­u­ra­tion of xkb with HAL. The de­fault xkb con­fig­u­ra­tion comes with a lot of flex­i­bil­ity, and of­ten you don’t need any­thing else.

But when you do, then this is how to do it:

Installing a new keyboard map#

The most ba­sic way to in­stall a new key­board map is us­ing xkbcomp, which can also be used to dump the cur­rently in­stalled map into a file. So, to get a bit of an idea of what we’ll be deal­ing with, please run the fol­low­ing commands:

xkbcomp $DISPLAY xkb.dump
editor xkb.dump
xkbcomp xkb.dump $DISPLAY

The file is com­plex and large, and it com­pletely went against my aes­thet­ics to edit it to have xkb work ac­cord­ing to my needs. I sought a way in which I could use as much as pos­si­ble of the de­fault con­fig­u­ra­tion, and only place self-con­tained ad­di­tional snip­pets in place to do the things I wanted done dif­ferently.

setxkbmap and rule files#

Thus be­gan my voy­age into the do­main of rule files. But be­fore we dive into those, let’s take a look at setxkbmap. De­spite the triv­ial in­vo­ca­tion of e.g. setxkbmap us to in­stall a stan­dard US-Amer­i­can key­board map, the com­mand also takes ar­gu­ments. More specif­i­cally, it al­lows you to spec­ify the fol­low­ing high-level pa­ram­e­ters, which de­ter­mine the se­quence of events be­tween key press and an ap­pli­ca­tion re­ceiv­ing a KeyPress event:

  • Model: the key­board model, which de­fines which keys are where
  • Lay­out: the key­board lay­out, which de­fines what the keys ac­tually are
  • Vari­ant: slight vari­a­tions in the layout
  • Op­tions: con­fig­urable as­pects of key­board fea­tures and pos­si­bilities

Thus, with the fol­low­ing com­mand line, I would se­lect a US lay­out with in­ter­na­tional (dead) keys for my Think­Pad key­board, and switch to an al­ter­nate sym­bol group with the win­dows keys (more on that later):

setxkbmap -model thinkpad -layout us -variant intl -option grp:win_switch

In many cases, be­tween all com­bi­na­tions of the afore­men­tioned pa­ram­e­ters, this is all you ever need.

But I wanted more.

If you ap­pend -print to the above com­mand, it will print the keymap it would in­stall, rather than in­stalling it:

$ setxkbmap -model thinkpad -layout us -variant intl -option grp:win_switch -print
xkb_keymap {
  xkb_keycodes  { include "evdev+aliases(qwerty)"       };
  xkb_types     { include "complete"    };
  xkb_compat    { include "complete"    };
  xkb_symbols   { include "pc+us(intl)+inet(evdev)+group(win_switch)"   };
  xkb_geometry  { include "thinkpad(us)"        };
};

There are two things to note:

  1. The -option grp:​win_​switch ar­gu­ment has been turned into an ad­di­tional in­clude group(win_​switch) on the xkb_​symbols line, just like the model, lay­out, and vari­ant are re­spon­si­ble for other as­pects in the output.

  2. The out­put seems re­lated to what xkbcomp dumped into the xkb.​dump file we cre­ated ear­lier. Upon closer in­spec­tion, the dump file is a pre-pro­cessed ver­sion of the key­board map, with include in­struc­tions exploded.

At this point, it be­came clear to me that this was the cor­rect way for­ward, and I started to in­ves­ti­gate those points in order.

The trans­la­tion from pa­ram­e­ters to an xkb_​keymap stanza by setxkbmap is ac­tu­ally gov­erned by a rule file. A rule is noth­ing more than a set of cri­te­ria, and what setxkbmap should do in case they all match. On a De­bian sys­tem, you can find this file in /usr/​share/​X11/​xkb/​rules/​evdev, and /usr/​share/​X11/​xkb/​rules/​evdev.​lst is a list­ing of all avail­able pa­ram­e­ter values.

The xkb_​symbols in­clude line in the above xkb_​keymap out­put is the re­sult of the fol­low­ing rules in the first file, which setxkbmap had matched (from top to bot­tom) and processed:

! model         layout              =       symbols
  […]
  *             *                   =       pc+%l(%v)

! model                             =       symbols
  *                                 =       +inet(evdev)

! option                            =       symbols
  […]
  grp:win_switch                    =       +group(win_switch)

It should now not be hard to de­duce the xkb_​symbols in­clude line quoted above, start­ing from the setxkbmap com­mand line. I’ll re­pro­duce both for you for con­venience:

setxkbmap -model thinkpad -layout us -variant intl -option grp:win_switch
xkb_symbols   { include "pc+us(intl)+inet(evdev)+group(win_switch)"   };

A short note about the syn­tax here: group(win_​switch) in the sym­bols col­umn ref­er­ences the xkb_​symbols stanza named win_​switch in the sym­bols file group (/usr/​share/​X11/​xkb/​symbols/group).

Thus, the rules file maps pa­ram­e­ters to sets of snip­pets to in­clude, and the out­put of setxkbmap ap­plies those rules to cre­ate the xkb_​keymap out­put, to be pro­cessed by xkbcomp—which setxkbmap in­vokes im­plic­itly, un­less the -print ar­gu­ment was given on in­vocation.

It seems that for a cri­te­ria (op­tion, model, lay­out, …) to be hon­oured, it has to ap­pear in the cor­re­spond­ing list­ing file, evdev.​lst in this case. There is also evdev.​xml, but I couldn’t fig­ure out its role.

Attaching symbols to keys#

I ended up cre­at­ing a sym­bols file of rea­son­able size, which I won’t dis­cuss here. In­stead, let’s solve the fol­low­ing two tasks for the pur­pose of this document:

  1. Make the Win-Hy­phen key com­bi­na­tion gen­er­ate an “en” dash (–), and Win-Shift-Hy­phen an “em” dash (—).

  2. Let the Caps Lock key gen­er­ate Mod4, which can be used e.g. to con­trol the win­dow manager.

To ap­proach these two tasks, let’s cre­ate a sym­bols file in ~/.​xkb/​symbols/​xkbtest and add two stan­zas to it:

partial alphanumeric_keys
xkb_symbols "dashes" {
  key <AE11> {
    symbols[Group2] = [ endash, emdash ]
  };
};

partial modifier_keys
xkb_symbols "caps_mod4" {
  replace key <CAPS> {
    [ VoidSymbol, VoidSymbol ]
  };
  modifier_map Mod4 { <CAPS> };
};

Now let me ex­plain these in turn:

  1. We used the op­tion grp:​win_​switch ear­lier, which told xkb that we would like to use the win­dows keys to switch to group 2. In the cus­tom sym­bols file, we now de­fine the sym­bols to be gen­er­ated for each key, when the sec­ond group has been selected.

    Key <AE11> is the hy­phen key. To find out the names of all the other keys on your key­board, you can use the fol­low­ing command:

    xkbprint -label name $DISPLAY - | gv -orientation=seascape -
    

    I had to de­clare the stanza partial be­cause it is not a com­plete key­board map, but can only be used to augment/modify other maps. I also de­clared it alphanumeric_​keys to tell xkb that I would be mod­i­fy­ing al­phanu­meric keys in­side it. If I also wanted to change mod­i­fier keys, I would also spec­ify modifier_keys.

    The rest should be straight­for­ward. You can get the names of avail­able sym­bols from keysymdef.h,1 strip­ping the XK_ prefix.

  2. The sec­ond stanza re­places the Caps Lock key def­i­ni­tion and pre­vents it from gen­er­at­ing sym­bols (VoidSymbol).

    The im­por­tant as­pect of the sec­ond stanza is the modifier_​map in­struc­tion, which causes the key to gen­er­ate the Mod4 mod­i­fier event, which I can later use to bind key com­bi­na­tions for my win­dow man­ager (awesome).

    A note about VoidSymbol (as op­posed to e.g. Hyper L as the sym­bol to be gen­er­ated by the caps lock key: As far as I un­der­stood, Con­trol, Shift, and Caps are nec­es­sary sym­bols, but all the oth­ers (in­clud­ing Alt and Meta) are ac­tu­ally just sym­bols and in­de­pen­dent from any other func­tion of the keys. In par­tic­u­lar, modifier_​map seems com­pletely in­de­pen­dent of the sym­bols. As many ap­pli­ca­tions use Meta/Alt, you won’t get around gen­er­at­ing those, but I don’t know of ap­pli­ca­tions that use Su­per or Hy­per, so I pre­fer not to gen­er­ate them.

The eas­i­est way to ver­ify those changes is to put the setxkbmap -print out­put of the key­board map you would like to use as a base­line into ~/.​xkb/​keymap/​xkbtest, and ap­pend snip­pets to be in­cluded to the xkb_​symbols line, e.g.:

"pc+us(intl)+inet(evdev)+group(win_switch)+xkbtest(dashes)+xkbtest(caps_mod4)"

When you try to load this key­board map with xkbcomp, it will fail be­cause it can­not find the xkbtest sym­bol def­i­ni­tion file. You have to let the tool know where to look, by ap­pend­ing a path to its search list (note the use of $HOME in­stead of ~, which the shell would not expand):

xkbcomp -I$HOME/.xkb ~/.xkb/keymap/xkbtest $DISPLAY

You can use xev to ver­ify the re­sults, or just type Win-Hy­phen into a ter­mi­nal; does it pro­duce “–”?

By the way, I found xev much more use­ful for such pur­poses when in­voked as fol­lows (thanks to Penny for the idea):

xev | sed -ne '/^KeyPress/,/^$/p'

xev can also tell you which mod­i­fiers are in ef­fect. For that, you have to hold the mod­i­fy­ing key down, press an­other key, and take note of the state field, which is the hexa­dec­i­mal sum of all mod­i­fiers in ef­fect. The ones I found are:

0x0001 Shift
0x0002 Caps
0x0004 Control
0x0008 Alt
0x0010 NumLock
0x0030 Mod3
0x0040 Mod4
0x2000 Mode_switch

Thanks to Mar­ius Ged­mi­nas for the hint.

Rules again, and why I did not use them in the end#

Once I got this far, I pro­ceeded to add op­tion-to-sym­bol-snip­pet map­pings to the rules file, and added each op­tion to the list­ing file too. A few bugs later, I fi­nally had setxkbmap spit out the right xkb_​keymap and could in­stall the new key­board map with xkbcomp, like so:

setxkbmap -I$HOME/.xkb […] -print | xkbcomp -I$HOME/xkb - :0

I wrote a small script to au­to­mat­i­cally do that at the start of the X ses­sion and could have gone to play out­side, if it hadn’t been for the itch I felt due to the en­tire rule file stored in my con­fig­u­ra­tion. I cer­tainly did not like that, but I could also not find a way to ex­tend a rule file with ad­di­tional rules.

When I looked at the afore­men­tioned script again, it sud­denly be­came ob­vi­ous that I was go­ing a far longer path than I had to. Even though the rule sys­tem is pow­er­ful and al­lows me to e.g. au­to­mat­i­cally in­clude sym­bol maps to remap keys on my Think­Pad, based on the key­board model I con­fig­ured, the ben­e­fit (if any) did not jus­tify the ad­di­tional com­plexity.

In the end, I sim­pli­fied the script that loads the key­board map, and de­fined a de­fault xkb_keymap, as well as one for the Think­Pad, which I iden­tify by its fully-qual­i­fied host­name. If a spe­cific file is avail­able for a given host, it is used. Oth­er­wise, the script uses the default.