7

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?

timfeirg
  • 1,426
  • 18
  • 37

1 Answers1

6
-- 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()
joshua.thomas.bird
  • 676
  • 1
  • 8
  • 22
  • The delay is so that you can use the `caps` as `ctrl` more easily; in the case that you went to hit `ctrl-c` for example, and decided against pressing it but `caps` is already pressed, you can hold it a little longer and it turns back into `ctrl`. It shouldn't interfere with anything in normal use, if its an `esc` press it will almost always be depressed for less than 0.2. If you hold it longer than that it turns back into `ctrl`. The important part of this code is that the moment you press a key other than `caps` while caps is still depressed, it changes to the `ctrl` keycode being sent. – joshua.thomas.bird Feb 13 '18 at 16:58
  • Basically if you set the delay too small you wouldn't be able to press the key and release it within the delay quickly enough to send esc. You could modify this to only send esc unless somthing else is pressed, but I prefer to think of caps as a ctrl key unless Its pressed quickly and on its own then it's esc. – joshua.thomas.bird Feb 13 '18 at 17:14