Execute on Clipboard Change One Time Only?

I'm trying to write a macro that will remove the cruft from certain URLs when they're copied to the clipboard. I created a new macro that runs on clipboard change, and I basically have it working, except ... the last step would be to place the decrufted URL back on the clipboard.

And, of course, as soon as I do that, the macro runs again because the clipboard changed. Enter infinite loop.

I've tried a semaphore lock/unlock, which didn't work. I've tried setting a variable to 1 just before I paste to the clipboard, and modifying the macro so it won't run if that variable is 1 (and i then set it to 0 at the end of the macro). That didn't work.

I could decruft on paste, but I'd really prefer to store the simplified URL on the clipboard. Is there some way to say "don't run if triggered by a macro?" Or some other simple solution I'm overlooking?


There is an action called “break from loop” put it in the end.

That doesn't work either—the macro terminates, but then it relaunches because the clipboard has changed.


Hi @griffman - I've done this in the past so here's an example macro for you to customise as you please.

Just remember to place the actions for massaging the clipboard contents in between the red comment actions - and obviously replace the teal-coloured action as required.

One other comment - the Pause action's duration may need tweaking depending on how fast your Mac is. The slower your Mac, the bigger the pause.

Hope that helps!

Test Process Clipboard.kmmacros (6.5 KB)

What about disabling the macro when it runs and re-enabling it when it ends? This quick and dirty test macro I put together to do something similar seems to work for me:

Automatically Remove URL Cruft.kmmacros (3.0 KB)


Thanks to both @tiffle and @gglick — both solutions work! In the end, I went with the macro disabling method, as it's a bit quicker and eliminates a global variable. I never considered disabling a macro while it was running; it seems like it'd simply stop at that point, but it works perfectly.



That's very clever @gglick - another tool for my toolbox!

1 Like

It makes perfect sense that you'd think that, as the reality can be somewhat counter intuitive. My understanding is that the reason it works is because KM always executes macros in their own self-contained instance, so any changes made to a macro don't affect any instances that are already running. Put another way, having the macro disable itself this way prevents KM from spawning any more instances of that macro until it's enabled again at the end, without interfering with the instance that's doing the disabling and enabling, if that makes sense.


It does, and it's working great - and this trick will be useful in some of my other macros as well, so thanks again!


1 Like