How to programmatically swap the caps lock and esc keys?

Solution 1:

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 \
    '[caps<tab>caps:swapescape]'

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.