Changing modifier keys from the command line

keyboard

As a heavy Emacs user, I like to remap my Caps Lock key to function as the Ctrl key. There is a convenient dialog in the Keyboard Preference Pane to do that. But the problem is that this setting gets lost after someone logs into another account that hasn't this preference set.

So is there any way of doing the same as the preference pane dialog from the command line?

Best Answer

Changing preferences and running, defaults -currentHost read -g shows you what changes are being written. I was going to write up a short bash script to automate it, but it looks like I was beaten to the punch:

#!/bin/bash                                                                      

mappingplist=com.apple.keyboard.modifiermapping

if [ $1 == "emacs" ]; then
    echo "Switching to emacs modifiers"
    defaults -currentHost write -g $mappingplist '(                              
                {                                                                
            HIDKeyboardModifierMappingDst = 4;                                   
            HIDKeyboardModifierMappingSrc = 2; },                                
                {                                                                
            HIDKeyboardModifierMappingDst = 12;                                  
            HIDKeyboardModifierMappingSrc = 10;                                  
        },                                                                       
                {                                                                
            HIDKeyboardModifierMappingDst = 2;                                   
            HIDKeyboardModifierMappingSrc = 4;                                   
        },                                                                       
                {                                                                
            HIDKeyboardModifierMappingDst = 10;                                  
            HIDKeyboardModifierMappingSrc = 12;                                  
        })'


else
    echo "Switching to default modifiers"
    defaults -currentHost delete -g $mappingplist
fi

The script takes one argument, if the argument is emacs, then it swaps command and control, if the argument is anything else it restores the defaults.

http://forums.macrumors.com/showthread.php?t=949280