Creating a custom keyboard layout in Linux

Sometimes you might want to modify the keyboard layout, for example to add non standard characters that you're often using or if you're writing in 2 different languages you might combine all their special characters in one keyboard layout. In my case I bought a keyboard that had the escape key mapped by default to the Home Page special key and I found irritating having to press the Fn key every time I needed to use the escape button.

I'm using the Lubuntu Linux distribution that uses the X keyboard extension to enable multiple keyboard layouts.

First, run the xev command and filter only the keyboard events for a clearer log:

xev -event keyboard

When pressing a key it shows the keycode that is being sent and also the symbol of they key that is interpreted. In my case, using the standard US layout, the key 180 maps to the X86HomePage. The xev tool logs both the KeyPress and KeyRelease event:

With this information we can look for the key symbol that we can use to modify the layout. In the directory "/usr/share/X11/xkb/keycodes" we can find the mapping in the evdev file.

cat /usr/share/X11/xkb/keycodes/evdev | grep 180

The output shows that the keycode 180 is mapped to the symbol <I180>:

 <I180> = 180;   // #define KEY_HOMEPAGE            172

Now, there is an easy way to map the key to the escape button:

xmodmap -e "keycode 180 = Escape"

To make the changes persistent we can save the command in the ~/.Xmodmap file

However, we than can also define the layout in the "/usr/share/X11/xkb/symbols" folder

The easiest way to go about it is to copy the one of the files that you can build upon. For example the standard US layout and then remove the contents of the layout.

One of the layouts marked with default will be the main one and it also can have other variants.

default  partial alphanumeric_keys modifier_keys
xkb_symbols "basic" {

    name[Group1]= "Custom Keyboard Layout";

    include "us(basic)";
    include "eurosign(5)";

    key <I180> {        [ Escape                        ]        };
};

In the code we're first importing the US layout, then adding the Euro sign on the 5 button and finally mapping the I180 key to the Escape button. We can save the file as "cust" for example.

After we save the file we should enable the configuration in the rules folder base.lst file, otherwise the configuration will not be available.

We're looking for the layout section and adding the name of the file with the description of the Layout:

! layout
  cust           Custom keyboard layout

And with this the layout should be one of the choices in the layout selector.