xmodmap (change key bindings)

This command is used to remap keys on your keyboard. In Appendix B [see the printed book] I show you some powerful keyboard shortcuts for editing the command line. Most of these shortcuts rely on the Ctrl key, which is hard to reach on normal keyboards. On the other hand, almost every keyboard has a CapsLock key that nobody uses. Let's find out how xmodmap works by remapping CapsLock to Ctrl!

Every key has its own unique keycode. We need to find out which keycode CapsLock has before we can remap it. Enter xev (“X events”) and press Enter. A little window will open up and the most recent input events will be printed on the terminal. Press CapsLock a couple of times. This will generate a series of KeyPress and KeyRelease events, such as:

KeyPress event, serial 38, ...

root 0xb0, subw 0x0, ...

... keycode 66 (keysym 0xffe5, Caps_Lock) ...

I've shortened the output quite a bit. The important information is in line three: keycode 66 is bound to Caps_Lock, at least on my system. Exit xev by closing the little window it spawned or pressing Ctrl-c.

Next, launch a text editor and enter the following lines:

keycode 66 = Control_L

clear Lock

add Control = Control_L

The first line tells xmodmap to remap keycode 66 to Control_L. You may need to substitute your own keycode here. The second line clears CapsLock, deactivating its original function. The third line adds Control_L to the group of Control modifiers. This last step is necessary because we mapped a new keycode to Control_L.

Don't worry if you don't understand all the details. You don't have to become an xmodmap guru just to remap some keys. You can use the above lines as a template for your own mappings. For now, save the file as ~/.xmodmaprc and close the text editor.

We're almost done! Back on the command line, enter:

xmodmap ~/.xmodmaprc

This will make the new settings take effect. Some graphical desktop environments detect the existence of an .xmodmaprc automatically and will offer you the option to load the file on every startup. If that's not the case on your system, add the above xmodmap invocation to the autostart dialog or session startup script of your desktop environment.