I have a file called ~/.speedswapper which contains the following:
! Swap caps lock and escape remove Lock = Caps_Lock keysym Escape = Caps_Lock keysym Caps_Lock = Escape add Lock = Caps_Lock
...when I run
xmodmap ~/.speedswapper, this switches the esc and Caps Lock keys. I have this line in my ~/.profile, so that whenever I log in these keys are switched.
However, if I plug in an external USB keyboard, this setting doesn't seem to persist. My laptop's keyboard works perfectly well, but I have to run the command again in order for the external keyboard to switch the two keys. Fortunately, doing so doesn't seem to affect my laptop's keyboard -- they seem to synchronise.
One solution would be to find some way to run that xmodmap command whenever an external keyboard is plugged in, but I'd be open to another keyswapping solution, if it would be more robust. OS is Ubuntu 13.04.
Given justbrowsing's comment, it looks like this can be achieved by writing a udev rule -- I think I have to use the RUN option, and that it should be triggered on /dev/hidraw0 or /dev/hidraw1, which are the devices that appear when I plug my keyboard in... but I'm still trying to wrap my head around the concept, so I'd appreciate any help from someone who knows what they're doing with udev.