A kind soul has pointed me to @philip’s script here via this topic.
The original version didn’t work for me on macOS with zsh. Here’s a version that does, if it helps anyone.