macoshammerspoon

Hammerspoon bind "cmd" & "shift" without any other key


I want to use hammerspoon to replicate Windows' language switching using Alt and Shift. For this I want to add a hotkey bind for command and shift, but all my attempts fail.

I tried:

hs.hotkey.bind({"cmd", "shift"}, "", function()
    performAction()
end)

and

hs.hotkey.bind({"cmd"}, "shift", function()
    performAction()
end)

But nothing works.


Solution

  • philsnow's answer gave me most of the building blocks I needed, here's the code I used to map cmd -> cmd + shift -> shift -> nothing to switch between languages like in Windows. For anyone needing something similar, this code worked for me to switch toggle languages.

    function same_keys(t1, t2)
        return _same_keys_oneway(t1, t2) and _same_keys_oneway(t2, t1)
        end
        
        function _same_keys_oneway(t1, t2)
        for k, _ in pairs(t1) do
            local found = false
            for j, _ in pairs(t2) do
                if k == j then found = true end
            end
            if found == false then return false end
        end
        return true
    end
    
    nMinus1 = {}
    nMinus2 = {}
    nMinus3 = {}
    
    function tablelength(T)
        local count = 0
        for _ in pairs(T) do count = count + 1 end
        return count
    end
    
    function switchLanguage()
        local lay = hs.keycodes.currentLayout()
        print(lay)
        if lay == "ABC" then
          hs.keycodes.setLayout("Hebrew – PC")
        else
          hs.keycodes.setLayout("ABC")
        end
    end
    
    etap = hs.eventtap.new(
       {
          hs.eventtap.event.types.flagsChanged,
       },
       function(ev)
          local flags = ev:getFlags()
    
          if tablelength(flags) == 0 then
             if (same_keys(nMinus1, {shift = true}) 
                    and same_keys(nMinus2, {cmd = true, shift = true})
                    and same_keys(nMinus3, {cmd = true})) then
                switchLanguage()
             end
          end
          nMinus3 = nMinus2
          nMinus2 = nMinus1
          nMinus1 = flags
       end
    ):start()