binding a key sequence to an App

31 views
Skip to first unread message

dmg

unread,
May 14, 2024, 3:33:46 PM5/14/24
to Hammerspoon
I want to share this function, hopefully some will find it useful.

My use case is the following: I want a key to be bound to an app:

- if the App is the frontmost app
- key sequence is passed to the app
- otherwise
- bring the app to the front
- "pass through" the key to the app

Here is the code, with an example of how I bind Ctrl-Cmd C to emacs.

bundleKeys = {}

function bound_key_issue(hotKey, key1, key2)
hotKey:disable()
hs.eventtap.keyStroke(key1, key2)
hotKey:enable()
end

function bind_key_to_app(bundleID, key1, key2)

bundleKeys[bundleID] = hs.hotkey.bind(key1, key2, function ()

local hotkey = bundleKeys[bundleID]

if not hotkey then
hs.alert("Bug: bundleID key not found but it has been defined.
Simply generating event" .. bundleID)
hs.eventtap.keyStroke(key1, key2)
return
end

if not switch_by_bundle_id(bundleID) then
hs.alert(bundleID .. " app is not running. Simply generating event")
bound_key_issue(hotkey, key1, key2)
return
end
-- at this point app is running, we are just waiting for it
-- at most 1 second
local count = 0
while count < 10 and not is_front_by_bundle_id(bundleID) do
hs.timer.usleep(100)
count = count + 1
end

if is_front_by_bundle_id(bundleID) then
bound_key_issue(hotkey, key1, key2)
else
hs.alert("EMacs was not able to be front before command")
end
end)
end

bind_key_to_app("org.gnu.Emacs", {"ctrl", "cmd"}, "c")


--
--dmg

---
D M German
http://turingmachine.org

M N

unread,
Jul 29, 2024, 9:51:47 AM7/29/24
to Hammerspoon
hs.alert("EMacs was not able to be front before command")
should be:
hs.alert(bundleID .. " was not able to be front before command")

with your code `bundleKeys[bundleID] = ` is only one shortcut per bundleid possible.

why you sage the hotkey info in `bundleKeys`?
Reply all
Reply to author
Forward
0 new messages