Using KM Variable in AppleScript Action?

When I use a KM Variable in an Applescript action it gets converted to a string as soon as I hit enter. How does this help in the future if the variable changes?

1 Like

Well, it doesn't help because you need to use a different way to get KM variables into your AppleScripts.

The wiki tells you exactly how to do it here: AppleScript

just as you did with the DND-Scripts variable.

1 Like

Thanks for your help.

I still don't fully understand. This action works:


but if I hit "Enter" while the cursor is in the action the variable still updates to a string:

I am used to hitting "Enter" to verify the script is correct. Guess I should not do that in this case.

Edit:
Well, even if I do not hit "Enter", if I close the macro and reopen it the variable still changes to a string.

Hey Ray,

Yes it does. When an AppleScript compiles it pulls the necessary scripting terminology from the requisite application, therefore it must know what that application is.

Tell-by-variable techniques are nearly as old as AppleScript (1993), because this issue has come up before.

Here's one solution – create your script as text and then run it using AppleScript's run script command:

tell application "Keyboard Maestro Engine"
   set dndScriptsFolder to getvariable "DND_Scripts"
   set dndPhotoshop to getvariable "DND_Photoshop"
end tell

set PSFile to dndScriptsFolder & "/doAction_Show Filters.jsx"

set asCmdStr to "

tell application \"" & dndPhotoshop & "\"
   activate
   do javascript file PSFile
end tell

"
run script asCmdStr

This works, because the text is uncompiled. Compilation occurs when the run script command runs.

This slows down the script a bit, but that's negligible in a small script like yours.


Since Bundle-IDs don't change that often you can use the App ID instead of its name:

tell application id "com.barebones.bbedit"
   activate
end tell

You can also use this technique if you have more than one version of an app – or anticipate a differently named upgrade to an app.

set myAppName to "BBEdit"

using terms from application "BBEdit"
   tell application myAppName
      activate
   end tell
end using terms from

This works well IF the different versions have sufficiently similar AppleScript dictionaries.

-Chris

2 Likes

Thanks @ccstone, I'll give it a try. Much to learn.

Hey Ray,

One final method for systems having more than one app with the same name and Bundle-ID.

You can tell each app specifically by path:

tell application "/Applications/Applications_Chris/Text_Editors/BBEdit/BBEdit.app"
   activate
end tell
tell application "/Applications/Applications_Chris/Text_Editors/BBEdit/ BBEdit Beta/BBEdit.app"
   activate
end tell

-Chris

1 Like