Skip to content

Instantly share code, notes, and snippets.

@acarril
Created February 20, 2024 22:07
Show Gist options
  • Save acarril/a8abf6908ef1535829ec3d8f07ea253e to your computer and use it in GitHub Desktop.
Save acarril/a8abf6908ef1535829ec3d8f07ea253e to your computer and use it in GitHub Desktop.
Global macOS hotkey for Kitty
-- Function: Center and focus the main window of an application
function centerAndFocusMainWindow(app)
local mainWindow = app:mainWindow()
if mainWindow then
mainWindow:centerOnScreen()
mainWindow:focus()
end
end
-- Function: Watch for a specific application launch and execute a callback when launched
function watchForAppLaunch(appName, callback)
local watcher
watcher = hs.application.watcher.new(function(name, event, app)
if event == hs.application.watcher.launched and name == appName then
callback(app)
if watcher then
watcher:stop()
end
end
end)
watcher:start()
end
-- Function: Set up a watcher for an application to listen for window creation and execute a callback
function appNewWindowWatcher(app, callback)
if not app or not app:isRunning() then return end
local watcher = app:newWatcher(function(element, event)
if event == hs.uielement.watcher.windowCreated then
-- Execute the provided callback function
callback(app)
-- Optionally stop the watcher if you no longer need to listen for new windows
-- watcher:stop()
end
end)
-- Start watching for window creation events
watcher:start({hs.uielement.watcher.windowCreated})
end
-- Main keybinding to toggle Kitty
hs.hotkey.bind({ "ctrl" }, "\\", function()
-- Get application and main window objects for Kitty for program logic
app = hs.application.find("kitty", true)
if app then
mainWindow = app:mainWindow()
end
-- Logic if Kitty is running
if app then
if app:isFrontmost() and mainWindow then
app:hide()
elseif mainWindow then
mainWindow:focus()
else
appNewWindowWatcher(app, function(app)
centerAndFocusMainWindow(app)
end)
app:selectMenuItem({"Shell", "New OS Window"})
end
-- Logic if Kitty is not running
else
watchForAppLaunch("kitty", function(app)
centerAndFocusMainWindow(app)
end)
hs.application.launchOrFocus("/Applications/kitty.app")
end
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment