Swap Capslock and Leftctrl
Swap built-in keyboard Capslock and Ctrl keys.
Intro#
If I only use Gnome or KDE Plasma, I can turn on the keycode swapping toggle in the Gnome Tweaks or the KDE Settings.
However, I’d like to make the swap also persistent in TTYs and Window Managers.
I need to modify the keycode at the system level, not the desktop environment level.
To achieve this, I chose to use udev.
Another reason is that the Desktop Environment settings will apply to any connected keyboards.
However, my USB keyboard has its custom layout and doesn’t need to be modified.
The udev solution can apply key mappings to specific keyboards and remain others untouched.
How#
udev provides a way to edit custom hwdb.
The config file lies in the folder /etc/udev/hwdb.d/.
The file name should be something like 60-keyboard.hwdb.
The content might look like this.
| |
Scancode#
First, I need to determine the hardware scancode that the keyboard reports when capslock or ctrl is pressed.
The tool I used is showkey.
| |
So, the scancode of capslock is 0x3a and the scancode of leftctrl is 0x1d.
Keycode#
Keycodes are defined in /usr/include/linux/input-event-codes.h.
Also available at quirk-keymap-list.txt.
So, the keycodes are capslock and leftctrl respectively.
Mapping#
Before remapping, the scancodes and keycodes mappings are as follows.
| scancode | keycode |
|---|---|
| 0x3d | capslock |
| 0x1d | leftctrl |
After custom mapping, the mapping table should be like this.
| scancode | keycode |
|---|---|
| 0x3d | leftctrl |
| 0x1d | capslock |
Hardware ID#
If don’t mind applying the modification to all the built-in keyboards no matter what model or serial number it is. It is ok to not determine the hardware ID.
The built-in keyboard device ID should start with atkbd:dmi:.
To check the actual ID, use the evemu-describe command evemu tool.
You need to select the keyboard device by its name. For example.
| |
In the above example, the device ID should be:
| |
A general glob pattern for any AT keyboard should be:
| |
Or evdev:atkbd:dmi:* for short.
Config#
Edit the /etc/udev/hwdb.d/90-custom-keyboard.hwdb config file.
Keycodes need to be lowercase.
| |
Update hwdb#
| |
To automatically update the hwdb.
A reboot should automatically trigger systemd-hwdb-update.service.
Or manually trigger systemd-hwdb-update.service.
| |
The service will not run if /etc dir has not been changed.
Reload#
If already rebooted. The changes should be already applied and working.
If manually updated the hwdb. Also need to manually reload the hwdb.
| |
Verify#
To verify the change, can use udevadm info (#ref).
The real path of input event device /dev/input/event4 can be obtained by evemu-describe.
| |