Using Hammerspoon to switch apps (part 2)

A while ago I had posted how I use Hammerspoon to switch apps.

Essentially I have a list of shortcuts defined like this:

And I can press Ctrl+Cmd+C to switch to Visual Studio Code, Ctrl+Cmd+F to switch to Firefox, and so on. That’s how I began things, but as I detailed in that post I then extended this to switch between apps. Thus, in the above example, the first time I press Ctrl+Cmd+W I switch to Workflowy, but if I am already on Workflowy and I press these keys it will take me to Microsoft Word. Which is so neat coz I have an app switcher of sorts that just switches between these apps.

Moreover, if there are multiple windows it will switch between these. So Ctrl+Cmd+O will take me to Outlook, press it again and it will either do nothing, or if there’s another window it will switch to that. Press again, and if there’s yet another window it will take me that, else take me back to the first window. Very neat!

There is a catch in that if there are more than one window of an application, and I have defined a second one too for that key, it won’t switch to that second application. So Ctrl+Cmd+C will take me to Visual Studio Code, pressing again will take me to the second window if it exists, pressing again will take me back to the first window (assuming only two windows). I won’t ever go to Calendar until I have just one window of Visual Studio Code.

The keys can also launch an application if it’s not open. For instance, press Ctrl+Cmd+O and if Outlook is not open it will launch and switch to it. :) This behaviour is what I now wanted to fine tune. I came across this blog post by Christian Sellig where here uses Hammerspoon to switch between XCode windows and if XCode isn’t already launched it won’t open it. That’s a good idea, but I wanted to take it one step further and have it as an optional thing.

That’s to say, with things like Outlook which are work related, I don’t want to press Ctrl+Cmd+O on a weekend and suddenly be faced with work emails; but I am ok with Ctrl+Cmd+F launching Firefox if it isn’t running.

So I came up with this variant:

If a program has an asterisk next to it, don’t launch it if it isn’t already running. Else feel free to lauch it.

To achieve this I had to modify my previous script a bit.

I’ve highlighted the parts I added. But I changed the other code too slightly so there will be some difference to what I put in the previous post. Basically I added code to check for the existence of the asterisk and accordingly not do anything.

I love programming in Lua. I haven’t done much except with Hammerspoon, but it’s very neat in a way and I like it.