Keyboard layout switching

From Gentoo Wiki
Jump to: navigation, search
This page contains changes which are not marked for translation.

Other languages:
English • ‎한국어 • ‎русский

A keyboard layout maps scancodes from a keyboard into characters sent to an application. Keyboard layouts can also do more complex transformations via so called dead keys which do not output characters on their own but modify output of subsequent keys. An appropriate keyboard layout is required to support both non-QWERTY keyboards as well as QWERTY keyboards to enter characters outside of ASCII set.



Edit /etc/conf.d/keymaps which is documented but not very understandable. It appears that one should choose an appropriate keyboard map likely from /usr/share/keymaps/i386/qwerty/ as the value for keymap and then optionally also pick files from an appropriate include directory such as /usr/share/keymaps/i386/include/ as values for the extended_keymaps variable:

FILE /etc/conf.d/keymapsExample configuration

Lastly add /etc/init.d/keymaps to the boot runlevel.

root #rc-update add keymaps boot

Restart keymaps for apply changes

root #rc-service keymaps restart

If you need the terminal show non-ASCII characters you must edit /etc/conf.d/consolefont and change font

FILE /etc/conf.d/consolefontExample configuration for cyrillic font

Restart consolefont

root #rc-service consolefont restart

And add to default runlevel

root #rc-update add consolefont default

Custom keymap

To make a custom keymap look at the provided keymaps in /usr/share/keymaps:

user $vi <keymap file>.map
user $gzip <keymap file>.map
root #mv <keymap file>.map /usr/share/keymaps/<some directory>

Here is an example custom keymap which is the same as the U.S. QWERTY keymap, except the forward slash and apostrophe keys are swapped:

FILE /usr/share/keymaps/i386/qwerty/ Keymap
include ""
keycode  40 = slash            question
keycode  53 = apostrophe       quotedbl
Keycodes are likely to differ from system to system.

To find the keycodes mapped to keys view the output of dumpkeys:

user $dumpkeys -l

If the key cannot be found using the above command, run:

user $showkey

Just press the key and its keycode will be shown. When finished wait a few seconds and showkey will close.


systemd uses /etc/vconsole.conf and includes both terminal font and keyboard layout settings but lacks advanced settings found in OpenRC. Valid values should match what OpenRC supports for the corresponding variable.

FILE /etc/vconsole.confExample settings


Modern X11 applications usually use libXklavier ("klavier" being German for "keyboard") and can be configured by using setxkbmap. Furthermore X11 supports much broader sets of keyboard layouts than is supported for virtual terminals. It should be kept in mind that a proper desktop environment will do its own keyboard layout management. There is no need to directly use the aforementioned application but it can come in handy when dealing with broken or lacking keyboard layout management.


Open System Settings and navigate to the Input Devices module.

Generic desktop environment

Edit ~/.xprofile and call setxkbmap from there or setup the keyboard in Xorg configuration file (see below for examples).

Recent versions of GNOME 3 do not use libXklavier any more therefore this might not work at all or likely get overridden by GNOME. Similarly any other desktop environment might also override libXklavier configuration as part of the initialization or layout change.
~/.xprofile is a non-standard file that is sourced only when logging in via a display manager that supports it (tested only on GDM, KDM, LightDM, LXDM and SDDM) and it might be distribution specific although all common distributions seem to support this file.

lxpanel's keyboard layout handler

lxde-base/lxpanel provides a keyboard layout handler as a panel item.

Lxpanel kyboard layout handler.png

Generic X11

Using setxkbmap

These changes are non-permanent and will persist only as long as the user does not restart X11. Naturally the command can be called from a startup script to set the appropriate parameters on every start of the X server.

To query the existing configuration:

user $setxkbmap -query

Setting a keyboard layout:

user $setxkbmap lv

Setting a keyboard layout, its variant and model:

user $setxkbmap lv apostrophe -model logiultrax

Finding the supported layouts and variants or values of other xkb properties does not appear to be possible with this application, although most of them are listed in the /usr/share/X11/xkb/rules/base.lst file. To get the most complete list seems to be possible only by examining other files in /usr/share/X11/xkb/. For sake of sanity, it is advised to use of a proper desktop environment with its own keyboard layout management.

Using system-wide configured layouts and shortcut

This method is recommended for configurations without desktop environments, in other words just X11 with a window manager. Create the 10-keyboard.conf file and configure it with the appropriate keyboard settings.

FILE /etc/X11/xorg.conf.d/10-keyboard.confExample for US and brazilian layouts
Section "InputClass"
    Identifier "keyboard-all"
    Driver "evdev"
    Option "XkbLayout" "us,br"
    Option "XkbVariant" ",abnt2"
    Option "XkbOptions" "grp:shift_toggle,grp_led:scroll"
    MatchIsKeyboard "on"

The example above configures US and Brazilian keyboard layouts with Left Shift+Right Shift as shortcut to alternate between them. Brazilian layout is signalled by Scroll Lock LED on the keyboard.

Additional configuration possibilities

There are a number of variants and options available which can be used while configuring the keyboard mappings. Most of those can be found in the /usr/share/X11/xkb/rules/base.lst file.

For example, the US layout with possibility to write some international characters can be configured by using the variant altgr-intl:

FILE /etc/X11/xorg.conf.d/10-keyboard.confAltGr-international variant for US layout
    Option "XkbLayout" "us,br"
    Option "XkbVariant" "altgr-intl,abnt2"

Right Alt is then used as a modifier for typing international characters.

Xorg provides the option to type international and various symbol characters by composition - which means by pressing compose key followed by a sequence of characters. To enable composition add the compose:<compose_key> option:

FILE /etc/X11/xorg.conf.d/10-keyboard.confEnabling key composition
Option "XkbOptions" "grp:shift_toggle,grp_led:scroll,compose:sclk"

The compose:sclk option above configures Scroll Lock as compose key. With this setting:

  • Press Scroll Lock then type 'oo' to get degree sign '°'
  • Press Scroll Lock then type 'oc' to get copyright sign '©'
  • Press Scroll Lock then type ':)' to get smiling face '☺'
  • Press Scroll Lock then type '^2' to get superscript 2 ('²')
  • Press Scroll Lock then type '_2' to get subscript 2 ('₂')
  • Press Scroll Lock then type 'di' to get diameter sign '⌀'

... and many more. The /usr/share/X11/locale/compose.dir file lists all possible composition sources.

Enhancing an X keyboard layout

This is necessary when more far-reaching changes have to be made to the keyboard layout, such as adding key assignments, or adding actions to function keys. Since such changes are actually enhancements to the source files of a package, it is recommended to use the epatch_user mechanism so that these amendments are preserved when the package is next updated.

The fundamentals

The relevant Gentoo package is x11-misc/xkeyboard-config. Configuring a keyboard under X is more complicated than doing the same for a virtual console. The pertinent configuration files can be found in /usr/share/X11/xkb in these subdirectories:

These files associate key codes with symbolic names - it is unlikely that anyone wants to change this.
This is the physical shape of the keyboard, used by some software for drawing diagrams of it - it is also unlikely that anyone wants to change this.
The files here create "types". Used in a key declaration, a type specifies which combinations of shift keys can be used with the key.
These files specify the actual key assignments.
The files here specify "actions" (such as switching to a virtual terminal), giving them names, which can be assigned to keys.
These files, given parameters such as the keyboard type, and a language, activate the appropriate specifications in the other directories.

A fuller description of the files in these directories can be found at An Unreliable Guide to XKB Configuration by Doug Palmer. It is a lot better than its name suggests. Further documentation can be found at xkeyboard-config's home page at

Xkb gives keys names like "<AC01>" which means "key in the Alphanumeric area, in row C (i.e. third row from the bottom, the row CapsLock is on), and key number 01, the first key at the left of the row". This key is A in an English layout. Keys in other areas have other names, such as "<FK05>" for F5, or "<LCTL>" for the left control key.

Adding key assignments

As an example, this section will enhance the British English keyboard layout such that typing a, o, or u with AltGr will generate the German umlaut letters ä, ö, and ü. It should also do the Right Thing for the upper case versions. The keys to enhance are A (<AC01>), O (<AD09>) and U (<AD07>). (The character ß is already assigned to AltGr+S.)

The names of the umlauted letters in xkb are "adiaeresis" and so on. These names can be found in the file /usr/include/X11/keysymdef.h, though the leading "XK_"s have to be removed to get the names.

Identify the right file in the symbols directory. Most of these files are named as two letter country codes (such as gb for Great Britain) so guess the one which matches the keyboard layout currently selected in X. In this example, symbols/gb is enhanced.

With the information above, create new entries by copying the existing scheme in symbols/gb. In this example, these entries should be added into the section called "basic". From its content, it is easy to guess that the four items in the braces and brackets within the entry for each key are for regular (without other key combinations), Shift, AltGr, and Shift+AltGr respectively:

FILE /usr/share/X11/xkb/symbols/gbTypical key entry
key <AE02>	{ [         2,   quotedbl,  twosuperior,    oneeighth]	};

After making the additions, the section looks like this:

FILE /usr/share/X11/xkb/symbols/gbExample for enhancing the British English keyboard
default  partial alphanumeric_keys
xkb_symbols "basic" {
    // Describes the differences between a very simple en_US
    // keyboard and a very simple U.K. keyboard layout defined by
    // the SVR4 European Language Supplement and sometimes also
    // known as the IBM 166 layout.
    include "latin"
    name[Group1]="English (UK)";
    key <AE02>	{ [         2,   quotedbl,  twosuperior,    oneeighth ]	};
    key <AE03>	{ [         3,   sterling, threesuperior,    sterling ]	};
    key <AE04>	{ [         4,     dollar,     EuroSign,   onequarter ]	};
    key <AC11>	{ [apostrophe,         at, dead_circumflex, dead_caron]	};
    key <TLDE>	{ [     grave,    notsign,          bar,          bar ]	};
    key <BKSL>	{ [numbersign, asciitilde,   dead_grave,   dead_breve ]	};
    key <LSGT>	{ [ backslash,        bar,          bar,    brokenbar ]	};
// Keys inserted by ACM, 2015-10-23.
    key <AD07>  { [         u,          U,   udiaeresis,   Udiaeresis ] };
    key <AD09>  { [         o,          O,   odiaeresis,   Odiaeresis ] };
    key <AC01>  { [         a,          A,   adiaeresis,   Adiaeresis ] };
// End of insertion 2015-10-23
    include "level3(ralt_switch_multikey)"

Having saved this file, restart X Windows. A typical desktop environment, XFCE, re-reads the above configuration files each time it starts. Should there be errors, error messages will be written to the normal stderr - if X Windows is started from the command line, stderr will be the virtual terminal it was started from.

Adding actions to function keys

As an example, add the actions "switch to virtual terminal n" (where n > 12) to the function keys F1 - F12 when Ctrl, Alt, and Shift are all selected. The same effect should also occur when AltGr and Fn are selected.

First, search for the file in the symbols directory which handles the existing assignments for the Function keys. This file is symbols/srvr_ctrl. The entry in this file for F1, which is intended to be modified, is:

FILE /usr/share/X11/xkb/symbols/srvr_ctrlExisting entry for F1
key <FK01> {
	symbols[Group1]= [ F1, F1, F1, F1, XF86_Switch_VT_1 ]

There are two things to note with this entry:

  • It is of type "CTRL+ALT"; it thus takes the standard four shift key settings with Shift and AltGr, plus a fifth setting of Ctrl+Alt. Since the goal is to use Ctrl+Alt+Shift, and there is no suitable existing type, a new one needs to be created.
  • The "action" XF86_Switch_VT_1 is just a defined symbol in the xkb system. Its semantics are given to it by an entry in a file in the compat directory, namely compat/xfree86. There is no symbol XF86_Switch_VT_13 (or higher) - instead, steal the otherwise unused existing symbols F13, F14, ..., F24.
Creating the new type CTRL+ALT+SHIFT

Having located "CTRL+ALT" in types/pc, it is easy enough to copy it, rename the copy to "CTRL+ALT+SHIFT" and extend this to allow the modifier key combination Ctrl+Alt+Shift. The result looks like this:

FILE /usr/share/X11/xkb/types/pcCreating a new type
        modifiers = Control+Alt+Shift+LevelThree;
        map[None] = Level1;
        map[Shift] = Level2;
        map[LevelThree] = Level3;
        map[Shift+LevelThree] = Level4;
        map[Control+Alt] = Level5;
        map[Shift+Control+Alt] = Level6;
        preserve[Shift] = Shift;
        preserve[Shift+LevelThree] = Shift;
        level_name[Level1] = "Base";
        level_name[Level2] = "Shift";
        level_name[Level3] = "Alt Base";
        level_name[Level4] = "Shift Alt";
        level_name[Level5] = "Ctrl+Alt";
        level_name[Level6] = "Ctrl+Alt+Shift";
Activating the symbols F13, ..., F24

The symbol XF86_Switch_VT_1 is swiftly located in compat/xfree86. It is a simple matter to copy its form, creating assignments for the symbols F13, ..., F24. The definition for the first of these symbols, F13, in compat/xfree86 then looks like:

FILE /usr/share/X11/xkb/compat/xfree86Assigning an action to a symbol
interpret  F13 {
        action = SwitchScreen(Screen=13, !SameServer);

Analogous definitions for F14, ..., F24 should also be put into the file.

Amending the entries in symbols for keys F1, ..., F12

Now that the new type CTRL+ALT+SHIFT and definitions for the symbols F13, ..., F24 are defined, amend the key definitions for the function keys in symbols/srvr_ctrl. The one for F1 is mentioned below, analogous definitions also need to be inserted for the other function keys:

FILE /usr/share/X11/xkb/symbols/srvr_ctrlRedefinition of function key
key <FK01> {
	symbols[Group1]= [ F1, F1, F13, F1, XF86_Switch_VT_1, F13 ]

After making these changes to types/pc, compat/xfree86, and symbols/srvr_ctrl, and restarting the X server, switching from X directly to virtual terminals 13 and above is now possible - provided that these have been configured in the /etc/inittab (or systemd equivalent) of course.