User Tools

Site Tools


manual:Variables

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
manual:Variables [2018/03/13 22:49]
JMichaelTX [Using Variables in Scripts]
manual:Variables [2023/09/29 04:44] (current)
peternlewis
Line 1: Line 1:
 ====== Variables ====== ====== Variables ======
  
-Keyboard Maestro ​includes variables with three different scopes of allowed access, ​in order of scopewith broadest scope first:+Like most programming languages, ​Keyboard Maestro ​allows you to create Variables to store data for use later on in the same Macroor in other Macros.
  
-^ Scope ^ Availability ^ +Variables can be set from many actions.  ​You can set variables ​to specific [[manual:Tokenstokenised]] text, to the result ​of [[manual:Calculationscalculations]], from user input, from the Keychainby searching other variables, from the [[token:CurrentClipboardclipboard]] or [[token:NamedClipboard|Named Clipboards]], as the result ​of [[:Scripting|scripts]], and from many other sources.
-| **Global**, Permanent variables | • Available Everywhere, including Scripts and Preferences. | +
-| **Password**,​ Permanent variables | • Available to macros but not displayed.\\ • Not directly accessible via AppleScript.\\ Displayed in password fields in Prompt For User Input actions. ​+
-| **Instance** Variables (v8+) | • Restricted ​ ​to ​specific ​execution sequence.\\ • Available to Macro where it was created, AND Sub-Macros in that Macro, for a given execution instance of the main macro.\\ • So these Variables are private to each execution of the same Macro, even when running simultaneously.\\ • Available to [[action:Prompt_for_User_Input|Prompt For User Input]]\\ • As of v8.0.3is available ​to scripts (when used in an Execute Script Action), [[action:​Custom_HTML_Prompt|HTML Prompt]] | +
-| **Local** Variables (v8+) | • Restricted to Macro where it was created\\ • //Not// Available to any of its Sub-Macros\\ • Available to [[action:Prompt_for_User_Input|Prompt For User Input]]\\ • As of v8.0.3is available to scripts (when used in an Execute Script Action), [[action:Custom_HTML_Prompt|HTML Prompt]] +
-| **[[manual:Dictionaries|Dictionary]]**Permanent, global in scope. | • Available Almost Everywhere, including Scripts, but //not// Preferences.\\ • Dictionaries consist of the //​Dictionary Name//, One or more pairs of //Key Name//, and //Value//\\ • Although Dictionaries are like //​Variables//,​ they are kept in a separate category called //[[manual:Dictionaries|Dictionaries]]//|+
  
-Macros can create or read existing variables, which persist and are permanently stored (except Local and Instance variables which are transient).+===== Variable Naming Rules =====
  
-Variables contain only plain un-styled text and may be used in any text field in an action, as well as in [[Calculations]] in numerical fieldor within the in [[token:Calculate|Calculate Token]].  Variable ​may be used in [[Calculations]] if they contain ​a valid number or expression.+Anywhere ​an [[:​Actions|Action]] requires ​Variableyou can enter any name you like (even though often  a default name is provided), as long as it conforms to these rules: 
 +  - Variable names must start with a letter, and then can contain letters, numbers, spaces, or underscores. 
 +  - Some Variable ​kinds require a specific prefix (see _Scope_ below). 
 +  - Variable names are case insensitive,​ but their case is remembered. 
 +  - Variable names should not include a function or operator name with spaces around it. 
 +     *(eg “ MOD ” , so “A MOD B” would not be a valid variable, although “MODULE” would be fine).
  
  
-===== Kinds of Variable ​=====+===== Scope =====
  
  
-==== Global Variables ====+Keyboard Maestro includes variables with different breadth or scopes, in order of scope, with broadest scope first:
  
-Global ​Variables are permanently ​stored on your Mac drive (like a file), and are available ​for read/write in any Macro or Action, not just the Macro where the Variable was created. ​ These variables persist ​between logins and restarts of your Mac. +^ Scope ^ Availability ^ 
- +| **Global**, permanent variables | • Accessible basically everywhere, including Scripts.\\ • Permanently ​stored on your Mac drive. \\ • Available ​for read/write in any Macro or Action, not just the Macro where the Variable was created. ​\\ * Persist ​between logins and restarts of your Mac. \\ • You can also see and edit variables in the Preferences.\\ • You can see global variables in the [[Windows#​Value_Inspector_Window |Value Inspector]]| 
-Variable names must start with a letter, ​and then can contain letters, numbers, spaces, or underscores. ​ Variable names are case insensitive,​ but their case is remembered. Variable names should not include a function or operator name with spaces around it (eg " MOD " , so "A MOD B" would not be a valid variable, although "​MODULE"​ would be fine)+| **Password**, semi-permanent variables | • Name must begin or end with “PW” or “password” (case insensitive).\\ • Stored only in memory. \\ • Available ​to macros but not displayed.\\ • Not directly accessible via AppleScript. \\ • Concealed in password fields in Prompt For User Input actions.\\ • Not saved to disk. | 
- +| **[[#​Instance_Variables|Instance Variables]]**, local to a specific macro execution instance | • Name must begin with “instance” ​(case insensitive).\\ • Restricted  ​to a specific execution sequence.\\ • Available to the Macro where it was created ​and Sub-Macros of that Macro, ​for a given execution ​instance of the main macro.\\ • These variables are private ​to each execution ​of the same Macroeven when running simultaneously.\\ • Accessible by [[action:​Prompt_for_User_Input|Prompt For User Input]]\\ • Accessible by scripts (when used in an Execute Script Action).\\ • Accessible by [[action:Custom_HTML_Prompt|Custom HTML Prompt]].\\ • Accessible by AppleScript with the `instance` specifier. | 
-==== Password ​Variables ==== +| **[[#Local_Variables|Local Variables ]]**, local to a specific macro | • Name must begin with "​local"​ (case insensitive)\\ • Restricted to the specific Macro it is in.\\ • //Not// available to any of its Sub-Macros\\ • Same accessibility as Instance Variables. |
- +
-Variables with names that start or end with “Password” or “PW” are considered passwords – their values will not be stored ​(except ​in memory) and they cannot be read directly by shell scripts or AppleScripts,​ though their consequences can easily be extracted, eg with the Set Clipboard ​to Text action, so you should clear them as soon as they have served their purpose ​The ​Prompt For User Input dialog will display such variables in a password field+
- +
-==== Instance Variables ​(v8+) ==== +
- +
-Variables ​with names that start with "​Instance" ​(trailing space not necessaryare considered private ​to a specific execution sequence. ​ Each time the macro is run, they will start empty but their value can be seen and changed by other macros within the same execution sequence (for example, if you execute ​macro using the Execute Macro action, that macro can see and change the instance ​variable). ​ Since two instances ​of a macro can be running at the same time, this is useful ​to ensure they each have their own version ​of the variable. +
- +
-Since Local and Instance variables are transientthey are not shown in the [[manual:Preferences#Variables_Preferences| Variables ​preferences pane]].+
  
 +Macros can create or read existing variables, which persist and are permanently stored (except Local and Instance variables which are transient, and Password variables which are never saved to disk).
  
-==== Local Variables ​(v8+) ====+Variables ​contain only plain, un-styled, text and may be used in any token text field in an action, as well as in [[Calculations]] in a numerical field if they contain a valid number or expression.
  
-Variables with names that start with "​Local"​ (trailing space not necessary) are considered local to a specific execution ​of a specific ​macro.  Each time the macro is runthey will start empty and no other macro will see or be able to change values.+Since multiple instances ​of a macro could be running at the same time, using Local or Instance variables should generally ​be preferred so that each execution instance has its own independent variables.
  
-**Note that //Local// and //Instance// Variables are available in scripts ​//only// when the script is called in an //Execute Script// Action.**+(i) Note that Local and Instance Variables are available in scripts only when the script is called in an Execute Script ​action, unless you specify the execution instance explicitly.
  
-For a good discussion on the new Version 8 Local and Instance Variablessee this Forum topic:\\ +(!) Note that while Password variables are not directly available to scripts, their contents can easily be extracted, eg with the Set Clipboard to Text actionso you should clear them as soon as they have served their purpose.
-[[https://​forum.keyboardmaestro.com/​t/​km8-local-and-instance-variables/​7946|KM8:​ Local and Instance Variables]]+
  
 ===== Setting Variables ===== ===== Setting Variables =====
Line 48: Line 40:
 Variables are usually created and set by [[:​Actions|Macro Actions]], but can also be set by [[#​Using_Variables_in_Scripts|scripts]]. ​ The Action that sets a variable will create it if need be.  Variables do not need to be declared in any way. Variables are usually created and set by [[:​Actions|Macro Actions]], but can also be set by [[#​Using_Variables_in_Scripts|scripts]]. ​ The Action that sets a variable will create it if need be.  Variables do not need to be declared in any way.
  
-The most direction Action ​to set a variable is the [[action:​Set_Variable_to_Text|Set Variable to Text]] action.+The most direct action ​to set a variable is the [[action:​Set_Variable_to_Text|Set Variable to Text]] action.
  
 {{ :​token:​km-wiki-set-variable-action.png?​nolink |}} {{ :​token:​km-wiki-set-variable-action.png?​nolink |}}
Line 54: Line 46:
 This action processes the tokens and backslashed characters in the text and sets the variable. ​ As will all [[:​Text_Fields|text fields]], if you wish to use another variable in the text you must use the [[token:​Variable|%Variable%]] token, eg `The value is %Variable%VarName%`. ​ This action processes the tokens and backslashed characters in the text and sets the variable. ​ As will all [[:​Text_Fields|text fields]], if you wish to use another variable in the text you must use the [[token:​Variable|%Variable%]] token, eg `The value is %Variable%VarName%`. ​
  
-You can also use the [[action:​Set_Variable_to_Calculation]] action. ​ This action evaluates the numeric expression and then sets the variable to the result. ​ As with all numeric fields, if you wish to use another variable in the calculation,​ you use the variable unadorned, eg `VarName * 3`.+You can also use the [[action:​Set_Variable_to_Calculation|Set Variable to Calculation]] action. ​ This action evaluates the numeric expression and then sets the variable to the result. ​ As with all numeric fields, if you wish to use another variable in the calculation,​ you use the variable unadorned, eg `VarName * 3`.
  
-There are many other actions that set variables.+There are many other [[:Actions|actions]] that set variables.
  
 ===== Using Variables ===== ===== Using Variables =====
  
-There are many Macro Actions that can use variables. ​ Some of these explicitly provide for entry of the variable name, but most provide for a more general text entry that accepts either token text or a numeric expression. ​ +There are many Macro Actions that can use variables. ​ Some of these explicitly provide for entry of the variable name, but most provide for a more general text entry that accepts either token text or a numeric expression.
  
 When editing a field: When editing a field:
Line 70: Line 62:
 ==== Variables in Text Fields ==== ==== Variables in Text Fields ====
  
-Variables can be used in text fields using the [[token:​Variable|%Variable%]] token.  The //​%Variable%//​`<VariableName>`% token allows you to include a variable in the text, +Variables can be used in text fields using the [[token:​Variable|%Variable%]] token, for example the //​%Variable%//​`VariableName`% token includes the value of the `VariableName` variable ​in the text.
- ​where ​`<VariableName>is the name of the variable, and this is replaced by the value of the variable.+
  
 For Example, using the [[action:​Insert_Text|Insert Text]] Action: For Example, using the [[action:​Insert_Text|Insert Text]] Action:
Line 82: Line 73:
  
  
-While technically all Variables are just strings, you can access a variable as if it were an array (v7.2+) ​by setting the Variable to a delimited list of text, and then using the following notation:+While technically all Variables are just strings, you can access a variable as if it were an array by setting the Variable to a delimited list of text, and then using the following notation:
  
 `%Variable%<​VariableName>​[<​IndexNumber>​]%` `%Variable%<​VariableName>​[<​IndexNumber>​]%`
Line 108: Line 99:
  
 {{:​manual:​variable-array-example-for-each.png?​nolink|}} {{:​manual:​variable-array-example-for-each.png?​nolink|}}
- 
-For a **real-world example**, see this Forum post:  [Combine Two Lists Using KM Variable Array](https://​forum.keyboardmaestro.com/​t/​easiest-way-to-align-2-collections/​8372/​5) 
  
 ==== Variables in Calculation Fields ==== ==== Variables in Calculation Fields ====
  
-Variables can be used in calculations if their value holds a number or a numeric expression that can be evaluated. ​ Variables are used *unadorned* in calculations,​ for example `My Variable * 7`.  +Variables can be used in calculations if their value holds a number or a numeric expression that can be evaluated. ​ Variables are used *unadorned* in calculations,​ for example `My Variable * 7`.
  
 You can also access variables in a token field numerically using the [[token:​Calculate|%Calculate%]] token. ​ **It is important to note that calculations can contain only numeric values**. ​ When you use the [[token:​Calculate|%Calculate%]] token to reference a variable or variable array element, it will convert the element to a number. You can also access variables in a token field numerically using the [[token:​Calculate|%Calculate%]] token. ​ **It is important to note that calculations can contain only numeric values**. ​ When you use the [[token:​Calculate|%Calculate%]] token to reference a variable or variable array element, it will convert the element to a number.
Line 119: Line 108:
 === Variable Dot Notation === === Variable Dot Notation ===
  
-In a Calculation field you can reference the numbers in a variable (which is always a string) using dot notation:+In a Calculation field you can reference the numbers in a variable ​which contains a coordinate or rectangle ​(which is always a string, eg "​100,​100,​200,​200"​) using dot notation:
  
 | Variable.x | x coordinate | | Variable.x | x coordinate |
Line 137: Line 126:
 ==== Using Variables in Scripts ==== ==== Using Variables in Scripts ====
  
-Variables ​values can be accessed from scripts you execute with Keyboard Maestro via environment variables, and from AppleScript using AppleScript commands to the Keyboard Maestro Engine, and from web browser JavaScript you execute with Keyboard Maestro via the document.kmvar dictionary, see the [[Scripting]] section for more details.+Variable ​values can be accessed from scripts you execute with Keyboard Maestro via environment variables, and from AppleScript using AppleScript commands to the Keyboard Maestro Engine, and from web browser JavaScript you execute with Keyboard Maestro via the `kmvardictionary, see the [[Scripting]] section for more details.
  
 You can get and set Keyboard Maestro Variables (Global, Local, and Instance) in these types of scripts: You can get and set Keyboard Maestro Variables (Global, Local, and Instance) in these types of scripts:
Line 151: Line 140:
 ===== Deleting Variables ===== ===== Deleting Variables =====
  
-  ​* //Global// Variables, ​including ​//​Password//​ Variables, continue to exist (remained stored) until their value is set to `""​`, ​the empty string. +* //Global// Variables ​continue to exist (remained stored) until their value is set to the empty stringeven when the Keyboard Maestro Engine is quit and relaunched. 
-    * Setting a Variable to `%Delete%` does //not// technically delete it.  It continues to exist. ​ It is just //hidden// from view in all of the Variable lists and in the //​Preferences//​. +//​Password//​ Variables, continue to exist (remained stored) until their value is set to the empty string, or until you quit the Keyboard Maestro Engine
-    * However, a Variable set to `%Delete%` will behave as if it does //not// exist in most Actions, like a [[action:​If_Then_Else|If Then Else]] Action using a //Variable Condition// comparing to //exists//+* Setting a Variable to `%Delete%` does //not// technically delete it.  It continues to exist. ​ It is just //hidden// from view in all of the Variable lists and in the //​Preferences//​. 
-  * //​Dictionaries//​ continue to exist as long as there is at least one //Key// that has a value that is not `""​`. +* However, a Variable set to `%Delete%` will behave as if it does //not// exist in most Actions, like a [[action:​If_Then_Else|If Then Else]] Action using a //Variable Condition// comparing to //exists//.
-  * //​Dictionary Keys// continue to exist until their value is set to `""​`.+
  
  
-It may be a good idea to set a Variable to `""​` do if you no longer need it, or if it contains sensitive information (like a password) or a large value (like a file or web page contents).+It may be a good idea to set a Variable to the empty string ​if you no longer need it, or if it contains sensitive information (like a password) or a large value (like a file or web page contents).
  
 Perhaps the best way to avoid variable clutter and eliminate sensitive and/or large values is to use either //Local// or //​Instance//​ Variables when you do not need the Variable after completion of the Macro in which the Variable is used. Perhaps the best way to avoid variable clutter and eliminate sensitive and/or large values is to use either //Local// or //​Instance//​ Variables when you do not need the Variable after completion of the Macro in which the Variable is used.
Line 164: Line 152:
 ===== Inserting In Actions ===== ===== Inserting In Actions =====
  
-You can add a variable to an action using the [[Menus#Edit_Insert_Variable|Insert Variable menu]] ​in the [[Menus#Edit|Edit menu]] or [[Menus#​Edit_Insert_Function_Variable|Variable menu]] in the [[Menus#​Edit_Insert_Function|Insert Function ​sub-menu]] ​in the [[Menus#Edit|Edit menu]] or [[Menus#​Edit_Insert_Token_Variable|Variable menu]] in the [[Menus#​Edit_Insert_Token|Insert Token sub-menu]] in the [[Menus#​Edit|Edit ​menu]], or by selecting from the popup menu next to some variable fields.+You can add a variable to an action using the [[Menus#Insert_Variable|Edit ➤ Insert Variable menu]] ​or [[Menus#Insert_Function|Edit ➤ Insert Function ​➤ Variable ​menu]] ​or [[Menus#Insert_Token|Edit ➤ Insert Token ➤ Variable ​menu]], or by selecting from the popup menu next to some variable fields.
  
 Fields that expect just a variable show a small BUTTON{{{V}}} in the field while editing it, and you can use Type Completion to complete variable names in such fields. Fields that expect just a variable show a small BUTTON{{{V}}} in the field while editing it, and you can use Type Completion to complete variable names in such fields.
  
-===== Accessing in the Preferences Window ​=====+===== View Your Entire List of Variables ​===== 
 + 
 +You can add, delete, see or change global variables in the [[Windows#​Preferences_Variables_Pane|Variables preference pane]] that have been created by your macros and scripts. 
 + 
 +Local and Instance Variables are _not_ accessible from the Preferences Window.
  
-Variables are created on demand, but you can add, delete, see or change global variables in the [[Windows#​Preferences_Variables_Pane|Variables preference pane]].+===== Watching a Variable’s Value =====
  
-Local and Instance Variables are _not_ accessible from either ​the Preferences Window or from Scripting.+You can use the [[Windows#​Value_Inspector_Window |Value Inspector]] to watch the value of a global variable.
  
manual/Variables.1520995744.txt.gz · Last modified: 2018/03/13 22:49 by JMichaelTX