Skip to content

Instantly share code, notes, and snippets.

@malloc47
Last active January 27, 2020 23:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malloc47/14d88266c16d0f55775e52073e933191 to your computer and use it in GitHub Desktop.
Save malloc47/14d88266c16d0f55775e52073e933191 to your computer and use it in GitHub Desktop.
OS X Sierra Keybindings Per Application Using Hammerspoon

OS X Sierra + VirtualBox + Hammerspoon

I prefer different modifier keybindings for my VM vs. native OS X, but VirtualBox (unlike VMWare/Parallels) passes the keyboard through to the VM natively without the ability to remap it on the way through.

Apparently one would normally use Karabiner to do all manner of trickery to remap keys per application etc. but support for this utility was broken in OS X Sierra. Instead, I use a pair of scripts:

  • switch.sh uses the built-in hidutil on OS X to remap modifier keys immediately when invoked

  • init.lua is a lua script run by Hammerspoon that subscribes to window switching events and calls switch.sh if it finds the VM window.

What does switch.sh remap specifically?

In OS X:

  • Caps Lock -> Command

In the VM:

  • Caps Lock -> Control
  • Command -> Alt
  • Alt -> Command

Why not use XYZ?

Because it doesn't work under this very specific set of conditions for this very specific set of problems.

windowWatcher = hs.application.watcher.new(function(name, eventType, app)
if eventType ~= hs.application.watcher.activated then return end
if name == "VirtualBox VM" then
os.execute("~/bin/switch.sh linux")
else
os.execute("~/bin/switch.sh")
end
end)
windowWatcher:start()
#!/bin/bash
if [ "$1" == "linux" ] ; then
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x7000000E0},{"HIDKeyboardModifierMappingSrc":0x7000000E3,"HIDKeyboardModifierMappingDst":0x7000000E2},{"HIDKeyboardModifierMappingSrc":0x7000000E2,"HIDKeyboardModifierMappingDst":0x7000000E3}]}'
else
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x7000000E3}]}'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment