Skip to content

Instantly share code, notes, and snippets.

@dmmeteo
Created November 4, 2023 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmmeteo/99ff6c58ba864edf23be5006a89e3c56 to your computer and use it in GitHub Desktop.
Save dmmeteo/99ff6c58ba864edf23be5006a89e3c56 to your computer and use it in GitHub Desktop.
Hammerspoon configuration to switch keyboard languages with shortcuts(left CMD, right CMD, right Option)
-- Hammerspoon configuration to switch keyboard languages with shortcuts
-- Table to keep track of the last modifiers and if another key was pressed
local lastModifiers = {}
local otherKeyPressed = false
-- Function to handle single taps on modifier keys
local function singleTapHandler(event)
local newModifiers = event:getFlags()
local keyCode = event:getKeyCode()
-- If other keys are pressed along with modifiers, we set a flag
if event:getType() == hs.eventtap.event.types.keyDown then
otherKeyPressed = true
end
-- When all keys are released, check if it was a single modifier tap
if event:getType() == hs.eventtap.event.types.flagsChanged and not next(newModifiers) then
if not otherKeyPressed then -- no other keys were pressed
if lastModifiers["cmd"] and not newModifiers["cmd"] then -- CMD was released
if keyCode == 55 then -- left CMD
hs.keycodes.setLayout('ABC')
elseif keyCode == 54 then -- right CMD
hs.keycodes.setLayout('Ukrainian – Legacy')
end
elseif lastModifiers["alt"] and not newModifiers["alt"] then -- Option was released
if keyCode == 61 then -- right Option
hs.keycodes.setLayout('Russian')
end
end
end
-- Reset the flag when all keys are released
otherKeyPressed = false
end
-- Update the lastModifiers table
lastModifiers = newModifiers
end
-- Event tap to catch keyDown and flagsChanged events
eventTap = hs.eventtap.new({hs.eventtap.event.types.flagsChanged, hs.eventtap.event.types.keyDown}, singleTapHandler)
-- Start the event tap
eventTap:start()
-- Display a message to indicate the config has been loaded
hs.alert.show("Language switcher loaded")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment