Remap Caps Lock to Esc in Ubuntu and Debian

I'm a regular vim user and I like to have Caps Lock mapped to an additional Escape key. Most answers for this frequently asked question only provide a CLI or desktop solution only; I use both.

CLI Remap

This setup will sort you out for console usage.

Sample keymap

To enable the remap for CLI we can use loadkeys. You may need to open xev in an X session to first get the key sequence for Esc. The below sample should work on most recent ThinkPads:

keymaps 0-127
keycode   1 = Escape
keycode   58 = Escape

Save this somewhere handy as "caps_to_esc.map". Optionally you can swap Caps Lock and Esc by setting the keycode for Escape to CtrlL_Lock, in this case keycode 1 = CtrlL_Lock would do the trick.

Warning

Before running this please read the manpage for loadkeys and understand the warning provided therein (partially quoted for clarity):

loadkeys manpage: "Note that because the changes affect all the virtual consoles, they also outlive your session. This means that even at the login prompt the key bindings may not be what the user expects."

Setup

Open up a virtual console [Ctrl]+[Alt]+[F1], then let's back-up your current keymap

1
$ sudo dumpkeys > ~/loadkeys_backup.map

We're going to apply the custom keymap to your current profile, this remaps only a couple of keys in your profile

1
$ sudo loadkeys ~/Dropbox/caps_to_esc.map

You'll be able to test this out in vim or if you use the vi readline mode test it out directly in the prompt.

Restoring previous state

Restoring your keymap to its previous state is as simple as running loadkeys once more.

1
$ sudo loadkeys ~/loadkeys_backup.map

Automatically apply keymap

Once you're happy with the setup you can get the keymap to be applied on each system startup then you can add:

1
/usr/bin/loadkeys ~/Dropbox/caps_to_esc.map

Update 2014-08-25: It may be preferable to add this to /etc/rc3.d/ instead of rc.local. If the file is mounted on a network share or encrypted volume that is yet to be mounted and cannot be accessed, then your system may lock up. Previously: "To your /etc/rc.local, make sure it's above the exit 0 statement."

Desktop Remap

In recent versions of both Debian and Ubuntu you'll need an extra utility:

1
$ sudo apt-get install gnome-tweak-tool

Run this by typing "tweak tool" in to the GNOME launcher or Ubuntu Dash, go to the Typing tab and select "Make Caps Lock an additional ESC" under the Caps Lock key behaviour dropdown.

References