User Tools

Site Tools


manual:Scripting

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
Last revision Both sides next revision
manual:Scripting [2017/04/05 15:41]
JMichaelTX
manual:Scripting [2023/10/04 04:25]
peternlewis
Line 3: Line 3:
 ===== Executing Scripts ===== ===== Executing Scripts =====
  
-You can execute ​shells scripts, AppleScripts,​ JavaScript~~For~~Automation (JXA), JavaScript in Safari or Google Chrome, Swift Scripts, Automator Workflows, or filter the clipboard using BBEdit Text Factories. ​ You can run a script ​file or include the script as text directly in the application. ​ After pasting or typing script text into the Execute Script Action, press the <​key>​Enter</​key>​ key to compile and format the script.+The following _Execute Script_ Actions are provided to execute a variety of script ​languages:
  
-AppleScripts and shell scripts, ​JavaScript ​for Automation ​and Swift scripts, give you a powerful way of adding new facilities we have not specifically provided for, as well as controlling other applications. ​ ​JavaScript ​enables deep control over web page.+  * [[action:​Execute_an_AppleScript|Execute an AppleScript]] 
 +  * [[action:​Execute_an_Automator_Workflow|Execute an Automator Workflow]] 
 +  * [[action:​Execute_a_JavaScript_For_Automation|Execute a JavaScript ​For Automation]] 
 +  * [[action:​Execute_a_JavaScript_in_Custom_Prompt|Execute ​JavaScript ​in Custom HTML Prompt]] 
 +  * [[actions:​Execute_a_JavaScript_in_Browser|Execute a JavaScript in Browser]] 
 +  * [[action:​Execute_a_Shell_Script|Execute a Shell Script]] 
 +  * [[action:​Execute_Shortcut|Execute Shortcut]] 
 +  * [[action:​Execute_a_Swift_Script|Execute a Swift Script]] 
 +  * [[action:​Apply_a_BBEdit_Text_Factory|Apply ​BBEdit Text Factory to the Clipboard]]
  
-Shell scripts ​can execute any installed scripting language, such as perl, python, ruby or whatever. ​ Be aware that because shell scripts are executed ​in a non-interactive shell, typically none of the shell configuration files (like CODE{{{.login}}} ​or CODE{{{.profile}}}) will be executedwhich may change ​the way the shell script ​behaves.+You can specify the script to be executed either by reference to a file or as text entered directly ​in the _Execute Action_ After pasting ​or typing script text into the Execute Script Actionpress the <​key>​Enter</​key>​ key to compile and format ​the script.
  
-The results of scripts can be displayedor they can be typed or pasted in to the current selection, or saved into a variable or clipboard. ​ This allows you to insert text that depends on many factors, such as date calculations,​ file listings, SQL queries, web pages, or anything else you can imagine. ​ Alternatively,​ the results can be displayed in Notification Center, in a window, or in large type across the screen. ​ Or you can ignore the results, or execute the script asynchronously,​ leaving it running in the background.+For example, the [[action:​Execute_an_AppleScript|Execute an AppleScript]] action:
  
-You can also read and set the clipboard in a script, although the easiest way to set the clipboard to the results of a script is to select the Execute ​Script Action option to "save results to clipboard"​. ​ This works _only_ for plain text returned by the script. ​ For more complex formats, you will need to set the Clipboard directly in the script.+{{ execute-script-example.png?​nolink&​424x400 | Execute ​AppleScript Example }}
  
-For more information about using the Clipboard in scripts, see: +**There are two setup options:*
-  ​[AppleScript Clipboard Commands suite](https://​developer.apple.com/​library/​mac/​documentation/​AppleScript/​Conceptual/​AppleScriptLangGuide/​reference/​ASLR_cmds.html+^ Setup Option ^ Choices\\ ​(Default shown first^ 
-  * [Shell Scripts Pasteboard Commands: pbcopy, pbpaste](https://​developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/pbpaste.1.html)+| Script location | Execute text script ​(type or paste script into Action text field)\\ Execute script file (This may be faster if it is a compiled script file `.scpt`) | 
 +| Script Results | Ignored.\\ Displayed in a floating window.\\ Displayed briefly in a Notification.\\ Displayed large across the screen.\\ Typed in the current text field that has focus.\\ Pasted in text field that has focus.\\ Saved to a Keyboard Maestro Variable.\\ Appended to a Keyboard Maestro Variable.\\ Saved to the System or a Named Clipboard.\\ Saved to a file.\\ Ignore the results and run //Asynchronously// (the script runs while the macro continues on to the next //Action//)|
  
-Variables can be accessed from shell scripts via the environment variables in the form $KMVAR‗Variable‗Name where KMVAR‗ is prefixed, and spaces are converted to underscores. ​ AppleScripts can also access the environment variables using the CODE{{{system attribute}}} command, but note that CODE{{{system attribute}}} is not safe for international characters.+==== Using the Clipboard ====
  
-Note that the total size of the variables stored ​in the environment is limited ​to 100K, so larger variables may be excluded ​to ensure ​the variables do not take up excessive amounts ​of environment space since this is limited ​by the system.+You can also read and set the clipboard ​in a script, although ​the easiest way to set the clipboard ​to the results ​of a script ​is to select the Execute Script Action option to "save results to clipboard"​. ​ This works for plain text and some images returned ​by the script. ​ For more complex formats, you will need to set the Clipboard directly in the script.
  
-Variables whose names start with "​ENV‗"​ override regular environment variables (eg "​ENV‗PATH"​ overrides ​the regular "​PATH"​ environment variable).+For more information about using the Clipboard in scripts, see: 
 +  * [AppleScript Clipboard Commands suite](https://​developer.apple.com/​library/​mac/​documentation/​AppleScript/​Conceptual/​AppleScriptLangGuide/​reference/​ASLR_cmds.html) 
 +  * The unix man pages for pbcopy, pbpaste.
  
-===== AppleScript =====+==== Automating Applications and Adding Functionality to Keyboard Maestro ​====
  
 +AppleScripts,​ JavaScript for Automation scripts, Shell scripts, and Swift scripts, give you a powerful way of adding new facilities we have not specifically provided for, as well as controlling other applications.  ​
  
-For most recent methods and examples, see [[:​AppleScript|Using AppleScript to Get and Set Keyboard Maestro Variables]]+===== Web Page Interactions =====
  
-=== Get or Set Variables Using Version 7.1+ ===+The [[actions:​Execute_a_JavaScript_in_Browser|Execute a JavaScript in Browser]] actions enable deep control over a web page, as well as extracting specific data from both the page contents and HTML.
  
-Keyboard Maestro 7.1+ Provides the Most Compact Methods of Using AppleScript+===== Shell Scripts =====
  
-<code applescript>​ +Shell scripts can execute any installed scripting language, such as perl, python, ruby or whatever. ​ Be aware that because shell scripts are executed in a non-interactive shelltypically none of the shell configuration files (like CODE{{{.login}}} or CODE{{{.profile}}}) ​will be executedwhich may change the way the shell script behaves.
-tell application "​Keyboard Maestro Engine"​ +
-  --- GET VARIABLE --- +
-  -- IF KM Variable does NOT exist, the AS Variable ​will be set to empty string -- +
-  set calcResult to getvariable "​Calculation Result"​ +
-   +
-  --- SET VARIABLE --- +
-  -- IF KM Variable does NOT existit will be created -- +
-  setvariable "​Calculation Result"​ to (calcResult + 10) +
-end tell +
-</​code>​+
  
-**AppleScript Scripts Usable with Keyboard Maestro 7.0.2+**+Variables can be accessed from shell scripts via the environment variables in the form $KMVAR‗Variable‗Name where KMVAR‗ is prefixed, and spaces are converted to underscores ​AppleScripts can also access the environment variables using the CODE{{{system attribute}}} command, but note that CODE{{{system attribute}}} is not safe for international characters.
  
-=== Create Variable ===+Note that the total size of the variables stored in the environment is limited by the system to 100K, so larger variables may be excluded to ensure the variables do not take up excessive amounts of environment space.
  
 +Variables whose names start with "​ENV‗"​ override regular environment variables (eg "​ENV‗PATH"​ overrides the regular "​PATH"​ environment variable).
  
-<code applescript>​ +===== AppleScript =====
-tell application "​Keyboard Maestro Engine"​ +
-  make variable with properties {name:"​Calculation Result",​ value:"​57"​} +
-end tell +
-</​code>​+
  
-=== GET/SET Variable ===+AppleScripts ​ can perform many tasks on the Mac and control many applications.
  
 +You can read and write [[Variables|variables]],​ [[Dictionaries|dictionaries]] and control the Keyboard Maestro engine with AppleScript:​
  
 <code applescript>​ <code applescript>​
 tell application "​Keyboard Maestro Engine"​ tell application "​Keyboard Maestro Engine"​
-  set kmVarRef ​to make variable with properties {name:"​Calculation Result"​} +  set calcResult ​to getvariable ​"​Calculation Result"​ 
-  set oldValue ​to value of kmVarRef +  ​-- If the Keyboard Maestro Variable does not exist, the AppleScript Variable will be set to empty string 
-  ​set value of kmVarRef ​to 10+  ​ 
 +  setvariable "​Calculation Result" ​to (calcResult + 10
 +  -- If the Keyboard Maestro Variable does not exist, it will be created
 end tell end tell
 </​code>​ </​code>​
  
-=== Delete Variable ​==+===== JavaScript for Automation ​=====
- +
-<code applescript>​ +
-tell application "​Keyboard Maestro Engine"​ +
-  delete variable "​Calculation Result"​ +
-end tell +
-</​code>​ +
- +
- +
-===== JXA =====+
  
 JavaScript for Automation (JXA) can access Variables with: JavaScript for Automation (JXA) can access Variables with:
Line 84: Line 77:
 kme.setvariable('​Calculation Result',​ { to: 10 }); kme.setvariable('​Calculation Result',​ { to: 10 });
 </​code>​ </​code>​
 +
 +For details on JXA, see [[:​JavaScript for Automation]]. This provides an introduction to JXA and comparison with AppleScript.
  
 ===== JavaScript ===== ===== JavaScript =====
  
-JavaScript in web browsers can access the variable values by using the document.kmvar dictionary, like document.kmvar.Variable‗Name (spaces are converted to underscores).+JavaScript in web browsers can access the variable values by using the kmvar dictionary, like kmvar.Variable‗Name (spaces are converted to underscores), but they have no way to write values back to variables, except by returning a result from the script.
  
 ===== User Interaction ===== ===== User Interaction =====
Line 104: Line 99:
 See also the [[Variables]] section. See also the [[Variables]] section.
  
-===== Controlling Keyboard Maestro via Scripting =====+===== Controlling Keyboard Maestro ​Engine ​via Scripting =====
  
-The primary scripting interface to Keyboard Maestro is the Keyboard Maestro Engine’s CODE{{{do script}}} support. ​ You can ask Keyboard Maestro to:+The primary scripting interface to Keyboard Maestro ​Engine ​is the Keyboard Maestro Engine’s CODE{{{do script}}} support. ​ You can ask Keyboard Maestro ​Engine ​to:
  
 * execute a macro by name * execute a macro by name
Line 112: Line 107:
 * execute an action given its XML code * execute an action given its XML code
  
-Note in most cases you must ask “Keyboard Maestro Engine”, not “Keyboard Maestro”.+Note in most cases you must tell “Keyboard Maestro Engine”, not “Keyboard Maestro”.
  
 The easiest way is to use the name, for example: The easiest way is to use the name, for example:
Line 132: Line 127:
 </​code>​ </​code>​
  
-The CODE{{{do script}}} will not return until the macro is finished executing.+The CODE{{{do script}}} will not return until the macro is finished executing. The [[action:​Return_Result|Return Result]] action can be used to return a result to the AppleScipt.
  
-You can pass an optional parameter using the CODE{{{with parameter}}} clause, which you can read in the macro as the [[/token/TriggerValue|%TriggerValue% token]].+You can pass an optional parameter using the CODE{{{with parameter}}} clause, which you can read in the macro as the [[token:TriggerValue|%TriggerValue% token]].
  
 You can determine a macro’s UID by selecting it and choosing [[Menus#​Edit_Copy_as_Copy_UID|Copy UID command]] in the [[Menus#​Edit_Copy_as|Copy as sub-menu]] in the [[Menus#​Edit|Edit menu]]. You can determine a macro’s UID by selecting it and choosing [[Menus#​Edit_Copy_as_Copy_UID|Copy UID command]] in the [[Menus#​Edit_Copy_as|Copy as sub-menu]] in the [[Menus#​Edit|Edit menu]].
- 
-You can trigger a macro using the kmtrigger: scheme with a URL like `kmtrigger://​macro=MacroName&​value=Value` (the value is accessible via the CODE{{{%TriggerValue%}}} Token). 
  
 An even more powerful way to script Keyboard Maestro is to execute specific actions based on their XML code.  This allows you to construct any action, including changing the action on the fly, without having to create a macro first. ​ A simple example would be: An even more powerful way to script Keyboard Maestro is to execute specific actions based on their XML code.  This allows you to construct any action, including changing the action on the fly, without having to create a macro first. ​ A simple example would be:
Line 148: Line 141:
 </​code>​ </​code>​
  
-The easiest way to determine the appropriate XML is to create an example action in an example macro and then export ​the macro.+The easiest way to determine the appropriate XML is to create an example action in an example macro and then choose [[Menus#​Edit_Copy_as_XML|Copy as XML]] in the [[Menus#​Edit_Copy_as|Copy as sub-menu]] in the [[Menus#​Edit|Edit menu]].
  
 You can read information about the existing macros using the CODE{{{gethotkeys}}} and CODE{{{getmacros}}} commands. ​ See the Keyboard Maestro Engine AppleScript dictionary for more information. You can read information about the existing macros using the CODE{{{gethotkeys}}} and CODE{{{getmacros}}} commands. ​ See the Keyboard Maestro Engine AppleScript dictionary for more information.
  
-You can disable or enable a Macro or Macro Group from AppleScript with: 
  
-<code applescript>​ +===== Using Keyboard Maestro ​Facilities from AppleScript =====
-tell application "Keyboard Maestro+
-  setMacroEnable "​Macro/​Macro Group Group Name or UID" with/​without enable +
-end tell +
-</​code>​+
  
-This actually asks the editor ​to disable or enable the macro or macro group, so the change is both visible and permanent.+Keyboard Maestro Engine makes several of its facilities available ​to AppleScript.
  
-Alternatively you can use the [[/​action/​Set_Macro_Enable|Set Macro Enable action]]. +You can ask it to play sound with:
- +
-You can start editing ​Macro or Macro Group from AppleScript ​with:+
  
 <code applescript>​ <code applescript>​
-tell application "​Keyboard Maestro"​ +tell application "​Keyboard Maestro ​Engine
-  ​editMacro ​"Macro/Macro Group Name or UID"+  ​play sound alias "Harddisk:​System:​Library:​Sounds:​Glass.aiff"
 end tell end tell
 </​code>​ </​code>​
  
-You can ask Keyboard Maestro Engine to reload the macros ​with:+You can ask Keyboard Maestro Engine to perform a calculation for you with:
  
 <code applescript>​ <code applescript>​
 tell application "​Keyboard Maestro Engine"​ tell application "​Keyboard Maestro Engine"​
-  ​reload+  ​set n to calculate "​JULIANDATE()"​
 end tell end tell
 </​code>​ </​code>​
  
-You can also import macros, get the selected macros, ​or delete a macro or macro group from AppleScript. ​ See the Keyboard Maestro AppleScript dictionary for more information. +or process tokens ​with:
- +
-===== Using Keyboard Maestro Facilities from AppleScript ===== +
- +
-Keyboard Maestro Engine makes several of its facilities available to AppleScript. +
- +
-You can ask it to play a sound with:+
  
 <code applescript>​ <code applescript>​
 tell application "​Keyboard Maestro Engine"​ tell application "​Keyboard Maestro Engine"​
-  ​play sound alias "Harddisk:​System:​Library:​Sounds:​Glass.aiff"+  ​process tokens ​"%LongDate%"
 end tell end tell
 </​code>​ </​code>​
  
-You can ask Keyboard Maestro Engine to perform a calculation for you with:+The `calculate` and `process tokens` commands can also take an `instance` parameter (v10.0+) to specify the instance for local variable access. 
 + 
 +You can ask Keyboard Maestro Engine to find strings in other scripts:
  
 <code applescript>​ <code applescript>​
 tell application "​Keyboard Maestro Engine"​ tell application "​Keyboard Maestro Engine"​
-  set n to calculate ​"JULIANDATE()"+   count found in "The Source" ​for "​.e"​ with regex
 end tell end tell
 </​code>​ </​code>​
  
-You can ask Keyboard Maestro Engine to process tokens for you with:+And you can search and replace ​with:
  
 <code applescript>​ <code applescript>​
 tell application "​Keyboard Maestro Engine"​ tell application "​Keyboard Maestro Engine"​
-  set clip to process tokens ​"%PastClipboard%3%"+ search "​3+4"​ for "​(\\d+)"​ replace ​"%CalculateFormat%CALCULATE(\\1)%Currency%" ​with regex and process tokens
 end tell end tell
 </​code>​ </​code>​
  
-===== URL Schemes ​=====+===== Controlling Keyboard Maestro via Scripting ​=====
  
-==== Editor ====+Macro Groups, Smart Groups, Macros, Triggers, Actions are all available via AppleScript. ​ So you have deep control over controlling the Keyboard Maestro editor itself, allowing you to automate creating macros in a variety of different ways.
  
-Another way you can control Keyboard Maestro Editor ss using the "​`keyboardmaestro`"​ URL scheme, which supports the following formats:+You can disable or enable a Macro Group (or similarly Macro) from AppleScript with:
  
-^ Example Editor URL Command ^ Description ^ +<code applescript>​ 
-| `keyboardmaestro://​u=support%40stairways.com/​s=ABCDEFGH0123456789` | enter your username/​serial number. | +tell application "​Keyboard Maestro"​ 
-| `keyboardmaestro://​m=Activate%20Application%20Switcher`\\ `keyboardmaestro://​m=D2F427A1-51E3-4719-820B-4C25B6FF7329` | edit a specific macro or macro group.\\ You may used either the Macro Nameor UUID. | +  set enabled of macro group "Macro Group Group Name or UID" to true/false 
-| `keyboardmaestro:​//​q=Activate` | filter macros with this keyword. | +end tell 
-| `keyboardmaestro://​g=All%20Macros/​q=Activate` | select a macro group and filter macros with this keyword. | +</code>
-| `keyboardmaestro://​a=Execute` | filter actions with this keyword. | +
-| `keyboardmaestro://​c=All%20Actions/a=Execute` | select action category and filter actions with this keyword. |+
  
----+Alternatively you can use the [[action:​Set_Macro_or_Group_Enable|Set Macro Enable action]].
  
-==== Triggers ====+You can rename, create, delete, duplicate macro groups and macros. ​ You can add and remove actions. ​ You can get or set the selection.
  
-You can trigger ​macro (that is Active and Enabled) using the "​`kmtrigger`"​ URL scheme.\\ +You can start editing ​a Macro or Macro Group from AppleScript with:
-The URL uses this format:\\ +
-`kmtrigger://​macro=<​Macro Name or UUID>​[&<​Trigger Value>]`+
  
-where +<code applescript>​ 
-  ​* `<Macro Name or UUID>` is either the Macro Name, OR, its UUID\\ +tell application "​Keyboard Maestro"​ 
-  * `<Trigger Value>` is the _optional_ Trigger Value +  ​editMacro "​Macro/​Macro Group Name or UID" 
-  * `[ ]` are _not_ included. ​ Used only to show _optional_ parameters +end tell 
-  * `&` must precede the Trigger Value, if it is provided.+</code>
  
-Note both Macro Name and Trigger Value must be URL encoded.+See the Keyboard Maestro AppleScript dictionary for more information.
  
-You can easily get the Trigger URL by clicking on the "Or by Script"​ Trigger option, and selecting "Or by URL".+===== Controlling Keyboard Maestro Engine via Scripting =====
  
-{{:​manual:​km-7.3-macro-trigger-url-setup.png?​nolink|}} +You can adjust Keyboard Maestro Engine windows ​with:
- +
-{{:​manual:​km-7.3-macro-trigger-url-results.png?​nolink|}} +
- +
-^ Example Trigger URL Command ^ Description ^ +
-| `kmtrigger://​macro=Your%20Macro%20Name` | Using the Macro Name | +
-| `kmtrigger://​macro=224AA8CB-07EB-4C92-8201-68FED82B6E9F` | Using the Macro UUID | +
-| `kmtrigger://​macro=Your%20Macro%20Name&​value=Your%20Trigger%20Value` | Using Macro Name with Trigger Value | +
-| `kmtrigger://​macro=224AA8CB-07EB-4C92-8201-68FED82B6E9F&​value=Your%20Trigger%20Value` | Using Macro UUID with Trigger Value  |+
  
 +<code applescript>​
 +tell application "​Keyboard Maestro Engine"​
 +    set bounds of window "​Clipboard History Switcher"​ to {1000, 50, 2000, 1200}
 +end tell
 +</​code>​
  
-See also the [[Calculations]] and [[Tokens]] sections. 
  
manual/Scripting.txt · Last modified: 2023/10/04 04:27 by peternlewis