Ubuntu – How to programmatically swap the caps lock and esc keys

command linegnomekeyboard

I am a heavy Vim user and one of the first things I do when I start working on a clean ubuntu installation is to swap the caps lock and esc keys to reduce hand movements over the keyboard.

So far I have been doing it through the keyboard configuration dialog, but I am now writting a set of scripts that will set Ubuntu up the way I like and I have not been able to find a scriptable or programmable way to change this configuration item.

I am not looking for options that swap the keys at any other level than gnome itself, so what I am looking for is for a way to script this change and have it appear in the keyboard configuration that I used to use, should I decide to revert it manually in the future.

Best Answer

You can do this through the GUI by open the Keyboard Preferences control panel (under System -> Preferences), and select the Layout tab. Click on the Options... button to open the layout options dialog. Expand the Caps Lock key behaviour section and select Swap ESC and Caps Lock.

There are a few ways you could script this kind of thing.

Directly via Xkb

We can make the change directly with the following:

setxkbmap -option caps:swapescape

You can disable all the current layout options (which will return caps lock to its default behaviour) with:

setxkbmap -option ''

Via GConf

The keyboard preferences control panel stores its configuration via gconf, with the layout actually being applied by gnome-settings-daemon. Therefore, you can cause gnome-settings-daemon to adjust the layout by updating gconf yourself.

The relevant setting in this case appears to be /desktop/gnome/peripherals/keyboard/kbd/options. So you can set the option with:

gconftool-2 --set /desktop/gnome/peripherals/keyboard/kbd/options \
    --type list --list-type string \

In the above, <tab> should be a literal tab character rather than spaces. You can disable the behaviour again by setting the gconf key to an empty list.