MacOS – How to remap a key in macOS Sierra, e.g., Right Alt to Right Control

keybindingskeyboardmacos

I used to use Karabiner to remap Right Alt to Right Control (as an Emacs user I use Control MUCH more that Alt) but updating to Sierra broke this. Downgrading is not an option.

How do I manually remap keys in Sierra? I specifically would like to remap Right Alt to Right Control.

Best Answer

Apple's Technical Note TN2450 describes how to remap keys. Running the following command will remap Right Alt to be Right Control.

hidutil property --set '{"UserKeyMapping":
    [{"HIDKeyboardModifierMappingSrc":0x7000000e6,
      "HIDKeyboardModifierMappingDst":0x7000000e4}]
}'

Note that the above command is not switching the Right Alt and Right Control. They will both be Right Control. If you have a MacBook, you will not notice this until plugging in an external keyboard. If you want to switch Right Alt and Right Control, you need to add a second switch command, like the following.

hidutil property --set '{"UserKeyMapping":
    [{"HIDKeyboardModifierMappingSrc":0x7000000e4,
      "HIDKeyboardModifierMappingDst":0x7000000e6},
     {"HIDKeyboardModifierMappingSrc":0x7000000e6,
      "HIDKeyboardModifierMappingDst":0x7000000e4}]
}'

The table at the bottom of the Technical Note has a list of hex values for each key. To generalize the above answer to switch any keys, you must or the hex value from that list together with 0x700000000. The following Python code demonstrates one way to do this.

In [1]: def convert(val):
   ...:     int_val = int(val, 16)
   ...:     int_ref = 0x700000000
   ...:
   ...:     return hex(int_ref | int_val)
   ...:

In [2]: r_alt = '0xE6'

In [3]: print(convert(r_alt))
0x7000000e6