_       _       
  (_) ___ | |_ ____
  | |/ _ \| __|_  /
  | | (_) | |_ / / 
 _/ |\___/ \__/___|
|__/               

How to swap Caps Lock and Esc keyboard keys in X windows on Raspbian (Debian)

When using the text editor Vim, it can be useful to swap the Caps Lock and Esc keys on the keyboard. The Caps Lock key, which is conveniently located adjacent to the keyboard's home row, is typically used relatively infrequently, whereas the Esc key is used all the time in Vim to exit from Normal mode.

To swap the keys in X windows, run the following commands:

xmodmap -e "clear Lock"
xmodmap -e "keycode 9 = Caps_Lock NoSymbol Caps_Lock"
xmodmap -e "keycode 66 = Escape NoSymbol Escape"

That won't affect the keyboard mapping in the console outside X windows.


Alternative method that requires root access and affects all users on the system, but applies the change in tty console as well as in X windows:

sudo vim /etc/defaults/keyboard

Modify the XKBOPTIONS line, as shown below:

XKBMODEL="pc105"
XKBLAYOUT="gb"
XKBVARIANT=""
XKBOPTIONS="caps:swapescape"
BACKSPACE="guess"

To ensure the new setting is applied, delete some cached console configuration files:

sudo rm /etc/console-setup/cached_*

When the system is rebooted, the Esc and Caps Lock keys should be swapped in X windows and in the text console.