08/23/13 20:00:20

Naming Your Keyboard Maestro Variables

Keyboard Maestro 5 introduced variables to its set of features. These variables are really great for us scripters! They are implemented in a way that a variable can be initiated from within Keyboard Maestro[1], which can then be used in other actions such as Shell and AppleScript scripts. One variable, manipulated with everything your Mac has to offer.

Variables can be used with the %Variable%variable name% syntax. Calculations, such as screen coordinates and frames, whether the Mac is online, Safari tabs, etc, can also be used for some nifty things, and they can set variables! There’s a lot to check out with calculations. Calculations, can even have two elements, in which case the variables can be accessed as array. (%Variable%variable name%1%)
In Shell and AppleScript’s this looks similar. Please refer to the documentation for this. A Shell script can access variables like so: $KMVAR_variable_name or so $_ENV["KMVAR_variable_name"].

Which brings us to the point of this article: naming best practices.

Keyboard Maestro variables can have whitespace characters in their name. This is good for human readability. It also makes for better UX in User Input dialogs. Whitespace characters are converted to underscores in scripts. From a Shell or AppleScript’ers point of view these don’t look “natural”.

As I’ve been working on Markdown for Keyboard Maestro 2, Keyboard Maestro introduced a new feature for variable names. Everything that is before two underscores in a variable name will not be shown in User Input actions.


Variable name: MMD__Title Case

Will be displayed as: Title Case:

This variable can accessed from an AppleScript like so:

tell application "Keyboard Maestro Engine"
    set MMDTitleCase to make variable with properties {name:"MMD__Title Case"}
    set MMDTitleCaseValue to value of MMDTitleCase
end tell

So the best practice recommendation: start your scripts by assigning Keyboard Maestro variables to script variables.

In Markdown for Keyboard Maestro all variables are prefixed with MMD__ and they use space in their variable name. Prefix groups of variables with the same prefix. This way it is easier to keep track of belonging variables, e.g. in PreferencesVariables.

As a last best practice recommendation: as a good programmer, clean up after your work. Set variables to %Delete% when they are not needed anymore.

  1. A Prompt for User Input, Set Variable to Text, or a Set Variable to Calculation action.  ↩