Skip to content

Instantly share code, notes, and snippets.

@huttj
Created August 15, 2017 21:43
Show Gist options
  • Save huttj/8944f2ff6d407d75a708734b306523e3 to your computer and use it in GitHub Desktop.
Save huttj/8944f2ff6d407d75a708734b306523e3 to your computer and use it in GitHub Desktop.
I use Karabiner to swap the `Command` and `Option` keys when I have an external keyboard plugged in. It's so annoying to have to manually switch the profile, though, so this script does it for me automatically, whenever I add or remove the keyboard (or when the device wakes, in case it was added or removed while it was asleep).
function switchProfile(profile)
local karabiner = "'/Library/Application Support/org.pqrs/Karabiner-Elements/bin/karabiner_cli' --select-profile "
print('Switching profile to "' .. profile .. '"')
hs.execute(karabiner .. "'" .. profile .. "'");
end
function isKeyboard(device)
return string.find(device["productName"], 'Keyboard') ~= nil
end
function usbDeviceCallback(data)
if (isKeyboard(data)) then
if (data["eventType"] == "added") then
switchProfile('External')
elseif (data["eventType"] == "removed") then
switchProfile('Internal')
end
end
end
function runCheck()
local usb_table = hs.usb.attachedDevices()
for index, usb_device in pairs(usb_table) do
if (isKeyboard(usb_device)) then
return switchProfile('External')
end
end
switchProfile('Internal')
end
runCheck()
hs.usb.watcher.new(usbDeviceCallback):start()
hs.caffeinate.watcher.new(runCheck):start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment