Passing a filename to a macro, returning a value

I have created a macro which reads a .txt file into a variable, replaces all CR with commas, and then selects a random item from this comma-separated list. It works just as I need it to.

Now I would like to abstract this macro so that if I pass it the path of any .txt file, it will perform its task and return the randomly-selected item.

What's the best manner of accomplishing this? Thanks in advance.

One method would be to acquire the path of the currently selected file using the %FinderSelection% token.

I'll know the file paths in advance. What I'm hoping to do is to set up this macro (call it Choose Random Item) so that I can pass it a file path from a different macro. Then Choose Random Item will send back a random selection to the macro which invoked it, and I'll read that value into a variable the calling macro will make use of. Should I be redefining a global variable each time, or is there some tidier way to accomplish this?

That's one option. Another is to use an instance variable, as it will persist throughout the run. Another is to set up the random picker as a subroutine that returns a result to the macro that called it.

A subroutine looks like it might be the way to go. I haven't tried messing around with subroutines in KM; I'll have to dig into it.

The main reason I want to abstract the actions of Choose Random is that I'm doing some cleanup and other things in there too—e.g. checking for empty lines or duplicates, sorting alphabetically—and if I decide to improve that functionality I want it to all in one place.

I do want the selected value to persist until I explicitly ask for a new choice, so I may even end up writing the current value into its own file. Then it could survive crashes or reboots.


I’d definitely recommend using a subroutine. Since you already have a macro it would be easy to turn it into a subroutine.

No need for a file: global variables persist across reboots and even crashes since they’re already automatically saved to a file by KM.

1 Like