Let macro behave differently on second and following executions

I have this very simple macro that can be executed from a pallet that is displayed when a certain dialogue box is opened. It selects all text in an input box and reduces the selection with one character at the end of the selection:

It would be nice if this macro can be used multiple times, each time the selection will be further reduced with one extra character (from the right).

How can I achieve this?

I can think of this solution, but find it a little clumsy (a lot of code):

  • Set a variable firstExecution is True when the macro is executed one time, make sure that the CMD+A isn't executed if firstExecution is True.
  • Create a second macro that is triggered when the specific dialogue box is closed and that sets the variable firstExecution to False again.

Perhaps it is better to use a counter.

Edit: How about this approach: first I determine the length of any existing selection. Then I simulate Command+A and determine the length again. If the first selection is smaller, I reduce the selection by the difference plus one.

Hey Hans,

Any complex solution is likely to require a lot of code and logic, and quite often something that seems like it should be simple turns out to be more than a little bit complex.  :sunglasses:

In this case you say you will always reduce the number of characters by 1 (from the right)?

So – looking slightly outside the box a simple solution would be to use a regular expression that eats the rightmost character upon each execution.

No character counting required.


Reduce String Length by 1 Character from the Right.kmmacros (5.3 KB)

1 Like

Hello Christopher,

Thanks for your help! I'm actually not trying to reduce a string but to reduce a selection. (I'm sure that your macro will come in handy for any of my other purposes :wink: ).

I went a long way with my macro, calculating lengths of selections and comparing and then I started anew and wrote something quite simple, that actually worked:

So, what's so special about this?

Blush :blush:, nothing ... except when you use this snippet in two input boxes at the 'same' time:

Then you'll have this: on a click, the selection in two input boxes is shrunk:

And the nice thing is that you can click multiple times, to further shrink the selections.

On a side note: The dialogue box shown will add both the long forms (here the plural) and any existing selection(s), the short forms (here the singular). Quite nifty.

Select but last char.kmmacros (11.6 KB)

Hey Hans,

You tend to learn a lot when you do that.  :smile:

What software are you working with in the GIF?


Hello Chris,

I was just about to post this link :wink: :

It's CafeTran Espresso 2018, the translation editor in which I'm working 99,9% percent of the time when I'm sitting behind my Mac (in the other 0,1% procent I'm playing with KM):