Search code examples
macos-sierrahammerspoon

hammerspoon remap control key: sends esc when pressed alone, send control when pressed with other keys


This is a extremely useful remap in my opinion, since you almost never type control alone, why not remap it to esc?

Since karabiner is gone I've been trying to restore my favourite feature using hammerspoon, I think this can be achieved but I just can't get it to work, does anyone know how to do this properly?


Solution

  • -- Sends "escape" if "caps lock" is held for less than .2 seconds, and no other keys are pressed.
    
    local send_escape = false
    local last_mods = {}
    local control_key_timer = hs.timer.delayed.new(0.2, function()
        send_escape = false
    end)
    
    hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, function(evt)
        local new_mods = evt:getFlags()
        if last_mods["ctrl"] == new_mods["ctrl"] then
            return false
        end
        if not last_mods["ctrl"] then
            last_mods = new_mods
            send_escape = true
            control_key_timer:start()
        else
            if send_escape then
                hs.eventtap.keyStroke({}, "escape")
            end
            last_mods = new_mods
            control_key_timer:stop()
        end
        return false
    end):start()
    
    
    hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(evt)
        send_escape = false
        return false
    end):start()