12

I'm trying to write a script that will replicate my OS X setup. In particular I want to remap the arrow keys to CMD + H,J,K,L.

The technique seems to be similar to this Linux solution, except the key file to modify is found in /usr/X11/share/X11/xkb/symbols/us. It's not really working as expected though and seems to be mapping the option key.

How can I remap keys via the command line in OS X?

Maros
  • 223

2 Answers2

4

Application-specific keyboard shortcuts like those from System Preferences are stored in the preference files of the corresponding application in /Users/username/Library/Preferences/, in the top-level NSUserKeyEquivalents key.

Those files can be read and written using the /usr/libexec/PlistBuddy and defaults programs on the command line.

$ defaults read com.apple.Automator NSUserKeyEquivalents
{
    "Hide Library" = "@$l";
    "Show Library" = "@$l";
}
$ defaults write com.apple.Terminal NSUserKeyEquivalents -dict-add "About Terminal" '^@$a'

Symbols and their meanings:

  • @ is Command
  • $ is Shift
  • ^ is Control
  • ~ is Option

Additionally, you can simply copy these files to other machines to take your user preferences with you.

Daniel Beck
  • 111,893
0

Using KeyRemap4MacBook, you could save this as private.xml:

<?xml version="1.0"?>
<root>
<item>
<name>test</name>
<identifier>private.test</identifier>
<autogen>--KeyToKey-- KeyCode::H, VK_COMMAND | ModifierFlag::NONE, KeyCode::CURSOR_LEFT</autogen>
<autogen>--KeyToKey-- KeyCode::H, VK_COMMAND | VK_SHIFT | ModifierFlag::NONE, KeyCode::CURSOR_LEFT, ModifierFlag::SHIFT_L</autogen>
<autogen>--KeyToKey-- KeyCode::J, VK_COMMAND | ModifierFlag::NONE, KeyCode::CURSOR_DOWN</autogen>
<autogen>--KeyToKey-- KeyCode::J, VK_COMMAND | VK_SHIFT | ModifierFlag::NONE, KeyCode::CURSOR_DOWN, ModifierFlag::SHIFT_L</autogen>
<autogen>--KeyToKey-- KeyCode::K, VK_COMMAND | ModifierFlag::NONE, KeyCode::CURSOR_UP</autogen>
<autogen>--KeyToKey-- KeyCode::K, VK_COMMAND | VK_SHIFT | ModifierFlag::NONE, KeyCode::CURSOR_UP, ModifierFlag::SHIFT_L</autogen>
<autogen>--KeyToKey-- KeyCode::L, VK_COMMAND | ModifierFlag::NONE, KeyCode::CURSOR_RIGHT</autogen>
<autogen>--KeyToKey-- KeyCode::L, VK_COMMAND | VK_SHIFT | ModifierFlag::NONE, KeyCode::CURSOR_RIGHT, ModifierFlag::SHIFT_L</autogen>
</item>
</root>

Leaving out | ModifierFlag::NONE would also change for example ⌥⌘H to ←.

See the source for the key code constants and predefined settings.

If you want to fully automate the configuration, you can enable the setting with /Library/org.pqrs/KeyRemap4MacBook/app/KeyRemap4MacBook_cli.app/Contents/MacOS/KeyRemap4MacBook_cli enable private.test.

Lri
  • 42,502
  • 8
  • 126
  • 159