macOS: Remap a key
27th November 2024You can use hidutil
to remap keys in macOS without using a third party application.
List current mappings, will return (null)
if no mappings are present:
$ hidutil property --get "UserKeyMapping"
(null)
Set a mapping, in this case, make Caps Lock
(0x39
) work as F24
(0x73
) instead:
$ hidutil property --set '{"UserKeyMapping":
[{"HIDKeyboardModifierMappingSrc":0x700000039, "HIDKeyboardModifierMappingDst":0x700000073}]
}'
To set multiple mappings, add corresponding objects to the array.
See this table for a full list of keys and their IDs. Some common ones include:
Name | Id |
---|---|
Enter |
0x28 |
Escape |
0x29 |
Backspace |
0x2A |
Tab |
0x2B |
Space |
0x2C |
Caps Lock |
0x39 |
Left Control |
0xE0 |
Left Shift |
0xE1 |
Left Option |
0xE2 |
Left Cmd |
0xE3 |
Right Control |
0xE4 |
Right Shift |
0xE5 |
Right Option |
0xE6 |
Right Cmd |
0xE7 |
To make the change persistent between boots, you need to create a plist, for example ~/Desktop/com.karltarvas.hidutil.plist
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.karltarvas.hidutil</string>
<key>ProgramArguments</key>
<!-- Map Caps Lock to F24 so we can use it for push to talk -->
<array>
<string>/usr/bin/hidutil</string>
<string>property</string>
<string>--set</string>
<string>{
"UserKeyMapping": [
{
"HIDKeyboardModifierMappingSrc": 0x700000039,
"HIDKeyboardModifierMappingDst": 0x700000073
}
]
}</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/tmp/com.karltarvas.hidutil.err</string>
<key>StandardOutPath</key>
<string>/tmp/com.karltarvas.hidutil.out</string>
</dict>
</plist>
Then copy that plist to ~/Library/LaunchAgents
and load it:
$ cp ~/Desktop/com.karltarvas.hidutil.plist ~/Library/LaunchAgents/com.karltarvas.hidutil.plist
$ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.karltarvas.hidutil.plist