Apple's Technical Note TN2450 describes how to remap keys. It is important to know that Right Command is also Right GUI. Running the following command will switch Right Command and Right Alt (if you also want to do the Left Command and Left Alt, refer to the technical note to get the hex values and the Python code below to do the or
operation).
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x7000000e7,"HIDKeyboardModifierMappingDst":0x7000000e6},{"HIDKeyboardModifierMappingSrc":0x7000000e6,"HIDKeyboardModifierMappingDst":0x7000000e7}]}'
The table at the bottom of the Technical Note has a list of hex values for each key.
Here is the command to change in the same time the GB to US layout ie.:
- map plus-minus key to tilda
- map tilda to shift
- map r-command to r-alt
- map r-alt to r-command
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000035,"HIDKeyboardModifierMappingDst":0x7000000e1},{"HIDKeyboardModifierMappingSrc":0x7000000e7,"HIDKeyboardModifierMappingDst":0x7000000e6},{"HIDKeyboardModifierMappingSrc":0x7000000e6,"HIDKeyboardModifierMappingDst":0x7000000e7},{"HIDKeyboardModifierMappingSrc":0x700000064,"HIDKeyboardModifierMappingDst":0x700000035}]}'
And here is more explanation on what is what:
{
"UserKeyMapping": [
# Map "Grave Accent and Tilde" located next to right Shift to the Shift
{
"HIDKeyboardModifierMappingSrc": 0x700000035, # Tilde
"HIDKeyboardModifierMappingDst": 0x7000000e1 # Shift
},
# Map "Right GUI" (Command) to the right Alt
{
"HIDKeyboardModifierMappingSrc": 0x7000000e7, # Right GUI
"HIDKeyboardModifierMappingDst": 0x7000000e6 # Right Alt
},
# And back
{
"HIDKeyboardModifierMappingSrc": 0x7000000e6,
"HIDKeyboardModifierMappingDst": 0x7000000e7
},
# Map "Plus/Minus" (below ESC) to "Grave Accent and Tilde"
{
"HIDKeyboardModifierMappingSrc": 0x700000064, # Plus/Minus - this is not to be found in the table
"HIDKeyboardModifierMappingDst": 0x700000035 # Tilde
}]
}
If you want to restore the original state you can just:
hidutil property --set '{"UserKeyMapping":[]}'
Credit: https://apple.stackexchange.com/a/283331