Skip to content

Instantly share code, notes, and snippets.

@dmgerman
Last active May 16, 2024 18:38
Show Gist options
  • Save dmgerman/08e8735d7bf1869bc4eb6c02944ea404 to your computer and use it in GitHub Desktop.
Save dmgerman/08e8735d7bf1869bc4eb6c02944ea404 to your computer and use it in GitHub Desktop.
hammerspoon, switch to an but issue the hotkey to the app too
function is_front_by_bundle_id(bundleID)
local currentWindow = hs.window.focusedWindow()
local currentBundle = nil
if currentWindow then
currentBundle = currentWindow:application():bundleID()
end
return currentBundle == bundleID
end
function switch_by_bundle_id(bundleID)
print("Switching by bundle id" .. bundleID)
local currentWindow = hs.window.focusedWindow()
local currentBundle = nil
if currentWindow then
currentBundle = currentWindow:application():bundleID()
end
-- is it current Window?
if currentBundle and (currentBundle == bundleID) then
return true
end
-- currentWIndow is not of this bundle
local apps = hs.application.applicationsForBundleID(bundleID)
if apps and (#apps > 0) then
apps[1]:activate()
print("activated: "..bundleID)
return true
else
hs.alert("not application with bundleId found: " .. bundleID)
end
return false
end
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(bundleID .. " was not able to be front before command")
end
end)
end
bind_key_to_app("org.gnu.Emacs", {"ctrl", "cmd"}, "c")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment