iTerm2 URL matching is pretty neat

For many years, other developers told me about iTerm2 and I ignored them. I really shouldn’t have. The stock macOS Terminal was fine, I thought. What a mistake.

There’s lots to love about iTerm2, including the ability to script it in Python. But a really amazing quick win is the support for Triggers. Triggers allow you to set a regular expression that gets acted on every time they appear in the terminal.

Some uses cases for this are already documented on the web: looking for common exception/error names and highlighting them to make debugging quicker and doing similarly for network errors.

I have a simpler use case: GitHub pull requests. GitHub has two CLI tools: hub and gh. gh is official and has a lot of fancy features, but when I’ve tried it, I’ve found it less pleasant to use. I don’t really use most of the functionality of GitHub PRs—assigning labels, setting milestones, linking PRs to projects etc. (And on the occasions I need to, I can just do that from the web UI.)

Usually, I just write up a PR message and submit, and friendly robots do the rest. So the complexity added by gh is too much. With hub, you can just type hub pull-request (I haven’t aliased git to hub), then it opens a text editor (vim), you prepare the PR, and save and exit. Hub submits it, and spits out the URL of the PR.

I then usually take that URL and either post it on Slack, open it and tweak it a bit, or some combination of the two.

Triggers just make that process slightly quicker.

I set up a trigger to match on and then use the “Run command” trigger to run open \0 and it’ll automatically open in a browser.

(If you want to, you can restrict it just to your routine PRs by changing it to|youremployer)/.+/pull/.+ And if you use GitLab or Bitbucket or your own self-hosted repository, and you have a tool that acts similarly to hub, it is trivial to change the URL for that.)

Initially, I set up a trigger that would find any HTTP(S) URL and copy it to the clipboard (and pop up a notification using terminal-notifier). I turned this off becuase it got really annoying. It would match in both the output and input, and if you pulled down some HTML with curl, it’d match hundreds of URLs and flood one’s notifications.

I found another solution for the other URLs: iTerm2 has a “Find URLs” command. You invoke it with Opt-Cmd-U. It’ll highlight all the URLs on screen, and select the most recent one. You can hit Cmd-G to go to previous URLs, and Cmd-C to copy.

With the combination of the above, I now have: auto-opening URLs for my own GitHub PRs, and autohyperlinked URLs that I can click with mouse/trackpad, and a trivial keyboard combo to get URLs out of command line output without using the mouse. The time saved not having to manually get URLs out of command line output is worth the switching cost alone.