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

1

8

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?

Partlow answered 12/12, 2016 at 4:10 Comment(1)
Im also wondering how to do this for Ubuntu. would be great if someone had an xmodmap script.Demilune
M
7
-- 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()
Maudiemaudlin answered 21/2, 2017 at 15:19 Comment(2)
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.Maudiemaudlin
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.Maudiemaudlin

© 2022 - 2024 — McMap. All rights reserved.