83 comments

[ 2.3 ms ] story [ 164 ms ] thread
Really nice at first sight.

I'm getting melancholic vibes of AutoHotKey reading the docs, which was arguably my first entry into professional programming. Knowing nothing about coding, I built a service desk automation back then — with (network file-) shared hotkeys and a real GUI, all in one single file... good times.

Anyway, ever since switching to MacOS more than a decade ago, I've always been searching for an AHK analog for those simple keystroke automations, text-based, with just enough of a glue language to hold it all together — Automator never quite cut it for me, after wielding the full power of AHK, it always felt too limited, rigid and clicky-colory.

Even though I don't have immediate use cases for it anymore, it makes me very happy that I know where to go back now!

Have you tried AppleScript scripting? You can glue applications together and even use JavaScript if you’re not a fan of AppleScript
Did some, but the syntax wasn't my cup of tea. The _really_ great feature of AHK to me was having the triggers and the actions all in one place though, which is something I couldn't really replicate with AppleScript that only has the actions, with the triggers in Automator.

So with that runtime you could easily just write whatever would happen if you press which key combo (or do cronjob-like things managed by the runtime) and then write what happens inline.

Write it all to a single script, copy it to a coworker's computer, run it, several dozen key combos just work now.

That's something I couldn't manage to pull off in AppleScript or Automator, but then again maybe I was just too dumb.

Try Keyboard Maestro or BetterTouchTool. They remind me the most of AHK out of all the Apple options.

I also really like Hammerspoon. The desktop automation scene on macOS is strong.

I use KeyboardMaestro to run my applescript connection as well. It's the missing glue to easily assign hotkeys to scripts or make them automatically trigger when something on my mac happens
do you mean simple text-based replacements and keyboard shortcuts? as opposed to full automation?

you can set those in the keyboard settings in system preferences. i have used the text replacement tab a lot in the past. i used it to auto-insert smileys and text snippets on various platforms. i haven't used shortcuts much though. you always end up with complicated shortcuts so you don't conflict with your apps.

I have been enjoying espanso[1], which at first glance is just a text-expanding keystoke saver, but can run shell scripts when it's doing its thing. So I can type :extip anywhere and it will curl ipinfo.io then pipe the json response through jq -r and leave my current external IP in whatever app I was typing in.

1: https://espanso.org/

Holy cow, espanso looks bonkers. Open source, completely cross-platform, fully extensible... it ticks all the boxes. Might just have to try it out tonight!
I had a similar reaction, although annoyingly it seems that on my Debian system it doesn't expand text inside gnome-terminal. Inside Emacs, Firefox, and similar it does work but if it's not "everywhere" I suspect I'll get frustrated.
Was in the same boat 10 years ago. In my quest to replace AHK on MacOS, Hammerspoon is where I ended up. It's great.
I really like HS especially filling the macOS missing features place like for windows management + either opening/focusing specific applications with shortcuts.
I like hammerspoon. I’ve been using it for years and never got beyond setting up window resizing with the visual grid - which I think is like one of the very first steps in the tutorial - but I’d recommend it just for that.
Does anyone knows a cross platform tools that can map keyboard keys to mouse button? Preferably in a layer?
I’ve especially enjoyed using Hammerspoon in combination with the prebaked config “Spacehammer” (https://github.com/agzam/spacehammer), which takes a lot of inspiration from Spacemacs (and, of course, enables a systemwide “edit this text field with emacs” workflow).
Is there something like this for python?
The language used for this is incidental. The important part is all the OS interfaces exposed. If you know Python, you'll feel comfortable in Lua quickly.
Im just looking for some way to slap something like this on top of some python scripts. Currently I’m only aware of calling applescript like this for python: https://stackoverflow.com/a/41318195
Probably faster to just re-write in Lua.
I fell briefly in love with Hammerspoon, but stopped using it.

My MacOS automation is now my QMK keyboard calling Alfred workflows; I use Yabai for window management.

I admire Lua, but ran into some sharp edges learning to program in it. Still, one can get up to speed quickly if one knows other scripting languages.

Hammerspoon window management was deathly slow. Yabai is close to instantaneous.

Lua is nothing but sharp edges and gotchas. I hate Lua more than I hate JavaScript.
Doesn’t Yabai require disabling SIP?
Certain advanced features do, but a majority of its features does not require disabling SIP.
I’ve never had any problem with latency when using Hammerspoon for window management.
Hammerspoon is great. I use it to manage windows (eg set vscode and a browser side-by-side when connected to an external display, full screen when not), add a hotkey to translate selected text with Deepl, to mute sound when the machine sleeps, and to launch a terminal with an fzf-based browser history searcher that beats Firefox’s hands down.

It’s easy to use and has great docs. Lua is fun to write. HS is a really nice project.

Do you mind sharing your code for the translation and fzf-history hotkeys? Those sound like useful applications.
I love Hammerspoon. It's one of the first must-have-for-a-usable-laptop tools I set up when I get a new MacBook.

Here are the top ways I'm using it right now:

1) Hide/show apps similar to how iTerm lets you bind a hotkey to hide/show a terminal. I've got ctrl+space set to Vimcal, alt+space set to midnight.app (a time tracker I'm building), and ctrl+alt+space set to Things.

2) Start/stop playing my work playlist of lofi hiphop. I got tired of the friction around opening Spotify, going into my work playlist, hitting play, waiting several moments for the playlist to load, etc, so I downloaded a bunch of mp3s from YouTube and put them in ~/Music/work/. Now my work music is a single keyboard shortcut (semicolon+m) and a few miliseconds away.

3) Set up screen recording. There are a few things that need to happen before I start a screen recording (opening CamHead.app, setting my screen resolution, and showing the dock at a certain height so I can later crop the video to 16:9) and I have it all bound to a single hotkey (semicolon+r). I've got another hotkey set up to unset it (semicolon+e).

4) You may have noticed I'm using keyboard shortcuts with semicolon as a modifier key. That's done with Hammerspoon too! I've got an extra layer of hotkeys available to me to set up whatever else I can think of in the future. The code I wrote to use semicolon like this sometimes breaks if I try to type too many actual semicolons in a row but I usually rely on JS Beautify to add those for me.

Would love to see the source for these! They sound like great uses
Semicolon actually seems pretty awesome as an extra modifier key. Will give that a go in QMK, ty!
> I got tired of the friction around opening Spotify, going into my work playlist, hitting play, waiting several moments for the playlist to load, etc, so I downloaded a bunch of mp3s from YouTube and put them in ~/Music/work/. Now my work music is a single keyboard shortcut (semicolon+m) and a few miliseconds away.

Aka how everyone did it before Spotify took off.

But actually, I'm told time and again that Spotify has some APIs to control it—presumably when desktop apps are used (dunno for sure because don't use it myself). Personally I'd use Alfred for that over shortcuts.

Yes. There are terminal applications to control Spotify. You need to add an API key in order to use them/it. So apparently you can write your own controller.

The Spotify app also has to be running in order to use the terminal application (at least the one that I tried).

Just curious do people use these types of automations to help with coding/software engineering? If so, in what way?
I use a Hammerspoon-based clipboard manager which is incredibly helpful
(comment deleted)
I like Hammerspoon, but it's a bit of a pain to write the scripts with Lua - I don't use the language often and it usually takes a while to figure out syntax and necessary stdlib/Hammerspoon functions. Does someone have a hint on how to set up e.g. VSCode or IJ with Lua support and completion for Hammerspoon functions?
I’ve been learning Lua as part of Advent of Code. Honestly, the language has its quirks buts it’s so tiny that you could pick it up quite quickly. It’s become enjoyable to write —- I recommend!
(comment deleted)
Since we've hit the front page of HN again, I've just released Hammerspoon 0.9.92, which contains a few fixes and some additions, but mostly refactored a significant amount of internal project structure to allow our build system to be replaced with something that isn't 5 years old and terrible.

As a result, it's possible that something broke which we didn't find in our internal testing. Please file GitHub issues :)

Happy Christmas y'all!

Please forgive what may be a naive question:

Speaking of old and terrible... Are you planning to keep the project in Objective-C long term? Any chance of migrating to Swift?

Merry Christmas and thanks for a great project.

I don’t think that’s a naive question at all, it’s something I’ve been thinking about a lot recently.

We have something like 70k-75k lines of ObjC and plain C in Hammerspoon, written at various times over the last 7ish years, with varying architectural styles as we’ve figured out better ways of doing things.

I would love to have it all ported to Swift with a single, consistent architecture, but it’s a heck of a lot of work!

I’ve been experimenting with some ideas for how the Swift might look, but to really justify all that work I think we’d need to revamp how our user-facing API works, so we’d also be forcing all our users to rewrite their Lua configs.

In summary… ¯\_(ツ)_/¯

Decision tree so you can stop pondering:

Does the current situation hinder progress?

- Yes: A lot?

  - Yes: rewrite

  - No: don't rewrite
- No: Don't rewrite
IDK i ported my objC code to swift and didn't see much of a benefit. If anything it was more work because I relied heavily on objC dynamism.
Thank you so much for Hammerspoon! It regularly makes my life much, much easier.

Only thing I'd wish is for it to be ported to Windows and be 100% compatible with my existing scripts. ;)

Hammerspoon (and Alfred) are the 2 apps that practically guarantee I'll never leave macOS. Just too damn useful. Thank you
Thank you very much for your work! I am slowly oscillating between Keyboard Maestro and Hammerspoon, as well as between Alfred and Launchbar, but currently I am again in the Hammerspoon/Launchbar side of the pool :)

One side I've noticed Hammesrpoon is a bit difficult to work with is debugging it can be done with logging to the console, but is not very convenient. Are there plans to introduce something more advanced at some point in the future?

I've used ZeroBrane to debug HS in the past: https://github.com/Hammerspoon/hammerspoon/issues/1268
Ah, almost, but it seems that ZeroBrane Studio is not arm-ready :(

dlopen(/Applications/ZeroBraneStudio.app/Contents/ZeroBraneStudio/bin/clibs53/socket/core.dylib, 0x0006): tried: '/Applications/ZeroBraneStudio.app/Contents/ZeroBraneStudio/bin/clibs53/socket/core.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), '/usr/lib/core.dylib' (no such file)

I've been using Phoenix (https://github.com/kasper/phoenix), which is hackable in JavaScript (here's my config: https://gist.github.com/rcarmo/5132874cdaf2755e42907508802e8...) and has a smaller scope (only window management), but haven't found it compelling enough to keep hacking at my config, so I'm back to Moom (https://manytricks.com/moom/), which would be perfect if it supported chaining sequences of sizing instructions (i.e., tile a window twice to the left to turn it from 1/2 to 1/3 width).
One of my more useful things, cmd+shift+m and cmd+shift+u to minimize all windows and un-minimize all windows of the active application. The un-minimize gets used more often (e.g. I may have a few Chrome windows minimized during my workday that I want to un-minimize en masse after work is done).

    local cmdShift = {'cmd', 'shift'}

    hs.hotkey.bind(cmdShift, 'm', function()
      local app = hs.application.frontmostApplication()

      for _, window in pairs(app:allWindows()) do
        window:minimize()
      end
    end)

    hs.hotkey.bind(cmdShift, 'u', function()
      local app = hs.application.frontmostApplication()

      for _, window in pairs(app:allWindows()) do
        window:unminimize()
      end
    end)
Interesting, I knew about cmd+option+m which does the minimizing part already. Weirdly doesn't seem to be an un-minimize shortcut though.
> Weirdly doesn't seem to be an un-minimize shortcut though.

Yup, the existing minimize shortcut's missing twin led me to learn a bit more Lua so I could implement it :)

Another fun thing you can do is install Hammerspoon as your URL handler, and make certain URLs open in different Chrome profiles--any work websites open in my work Chrome profile, websites related to a game I play opens in a Chrome profile specific to that, and anything else opens up in a personal Chrome profile.

I've also setup cmd+shift+1/2/3 to brings the aforementioned profiles into the foreground, so e.g. cmd+shift+2 brings my work Chrome profile to the foreground.

For anyone else trying to determine how to switch between Chrome profiles on macOS, I found a superuser post [0] In short you can run:

    open -a "Google Chrome" --args --profile-directory=$NAME
where $NAME for your current Chrome profile can be found by looking at Profile Path in chrome://version. The last directory in Profile Path is $NAME. The default $NAME is "Default" and another profile could be "Profile 5".

[0] https://superuser.com/questions/377186/how-do-i-start-chrome...

yup this is very similar to what I ended up with:

    -- open Chrome Canary with a specific named Profile
    function canaryWithProfile(profile, url)
      local t = hs.task.new("/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
      nil,
      function() return false end,
      { "--profile-directory=" .. profile, url })
      t:start()
    end

    -- open Chrome with a specific named Profile
    function chromeWithProfile(profile, url)
      local t = hs.task.new("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
      nil,
      function() return false end,
      { "--profile-directory=" .. profile, url })
      t:start()
    end
Love Hammerspoon! I wish there was an easier way to find great scripts, though. They seem to be all over the internet in random places.
If anyone cares, here's my config: https://github.com/kbd/setup/blob/master/HOME/.hammerspoon/i...

It shows off a tiny bit of what you can do with Hammerspoon:

  - window and app management
    - keyboard shortcuts for common apps (eg. hyper+T for text editor, hyper+B for browser, hyper+S for shell)
    - if you can code a tiny bit of Lua there's no need for apps like Spectacle, Rectangle, Moom, etc. because it's easy to position apps wherever you want. eg. hyper+L arranges my browser+editor+terminal in a standard layout, and I have other shortcuts to set apps to halves or thirds of the screen, or to another monitor.
  - fuzzy-find popups (like Alfred/fzf) are built-in. I use it to choose audio input/output.
  - a replacement for Caffeine (menubar icon to keep computer from going to sleep)
I have my "hyper" key bound to caps lock using Karabiner Elements (but it still works as a normal caps lock if you hold it for half a second). Here's that config: https://github.com/kbd/setup/blob/master/HOME/.config/karabi...
Thank you so much for your sample config. I recently got a Macbook for work, and coming back to non-tiling wm has been a challenge, especially with multiple monitors. With this config I am finally back to my comfortable meta+{h,l} tiling, dedicated shortcuts for applications and easy way to move application between monitors. And it took less than 10 minutes. Excellent way to start a Monday.
Awesome, you made my day better knowing that it helped someone. Thanks for your comment!

FWIW the rest of my (Mac-based) system config is all open source (both the files I linked are in the same repo) so feel free to steal anything else.

Thanks! I have perused some of the configs and will definitely take a few snippets from zshrc. Also, kdiff3 looks quite interesting. I have been relying on vimdiff/colordiff.
Don't miss https://github.com/dandavison/delta. I use gui diff tools much less nowadays because I can get such great diffs in the terminal.
Yeah, I found myself gravitating more towards lazygit with the default bundled diff utility, but I believe it has the option to plug an external one. Thanks, will check delta out!
I'm a big fan of Hammerspoon.

At least a few years ago, OS X's window management when plugging/unplugging external monitors was pretty bad.

Thanks to Hammerspoon, I don't have to think about it at all - I plug in monitors when I want to and all my windows resize and move themselves based on rules I defined.

It means stepping away from my desk or coming back to it is a no-brainer.

Maybe it's not needed these days, but it sure was a lifesaver back when I first adopted it.

My config, if people are interested:

https://github.com/NateEag/dotfiles/blob/master/src/.hammers...

Fyi applescript offers a JS engine
Love Hammerspoon, I have a small snippet to store bookmarks. I copy the url, open the shortcut, add tags and it is saved to sql lite file.

  local function insertDB(db, linkval, value)
    local url = tostring(linkVal)
    local categ = tostring(value)
  db:exec[=[
           INSERT INTO bookmarks VALUES (NULL,`url`,`categ`) 
    ]=]
   end


  hs.hotkey.bind({"alt", "ctrl"}, "S", function()
    db = hs.sqlite3.open('/dropbox/user/bookmarks.db')
    local insert_stmt = assert( db:prepare("INSERT INTO 
  bookmarks VALUES (NULL, ?, ?)") )

  local url = hs.pasteboard.getContents()

  local tag, value = hs.dialog.textPrompt(url, "Please enter 
  category:");

  if tag == 'OK' then
  insert_stmt:bind_values(url, value)
  insert_stmt:step()
  insert_stmt:reset()
  -- insertDB(db, linkVal, value) 
 end
end)