KM 8.0.4 Scripting Changes

Continuing the discussion from Keyboard Maestro 8.0.4:

Added Search & Replace and Count/Find facility to Keyboard Maestro Engine AppleScript dictionary.

@peternlewis, many thanks for this update, and for this scripting change.

Does this have any impact on an KM object, or is it just a tool for search and replace of text in general? An example of using this new command would be great!

Are there any other scripting changes?

From the SD6 Dictionary for Keyboard Maestro Engine:

1 Like

My impression is that it's the latter, though I would love to be wrong. In the meantime, I did already find a way to make use of this new ability to eliminate the need for the Satimage.osx in this script, which I posted earlier in Optimisation of user input selection - #20 by gglick

set MacroNames to {}
set MacroUUIDs to {}

tell application "Keyboard Maestro"
	repeat with i in (every macro whose name starts with "Search")
		set end of MacroNames to name of i
		set end of MacroUUIDs to id of i
	end repeat
end tell

set MacrosAndUUIDs to {}
repeat with i from 1 to count MacroNames
	set end of MacrosAndUUIDs to (item i of MacroNames) & ": " & (item i of MacroUUIDs)
end repeat

choose from list MacrosAndUUIDs with multiple selections allowed
set SelectedMacros to result

--Part that uses KM 8.0.4's new Search & Replace capability:

repeat with i from 1 to (length of SelectedMacros)
	tell application "Keyboard Maestro Engine"
		set MacroToRun to search item i of SelectedMacros for ".*: ([A-Z0-9-]+)$" replace "$1" with regex
		do script MacroToRun
	end tell
end repeat

It worked exactly as I expected, which was great. This one addition will make a lot of scripting solutions significantly more useful to KM users, since we'll no longer have to ask people to install the Satimage.osx just to get regex capabilities in AppleScript. Thanks, @peternlewis!

It is a tool to be used by AppleScripts.

There are some examples added to the Scripting user manual section, specifically:

tell application "Keyboard Maestro Engine"
   count found in "The Source" for ".e" with regex
end tell
tell application "Keyboard Maestro Engine"
	search "3+4" for "(\\d+)" replace "%CalculateFormat%CALCULATE(\\1)%Currency%" with regex and process tokens
	-- the parameter to CALCULATE is “backslash backlash one”.  The forum display is mucked up.
	-- the doubled backslashes are processed by AppleScript into a single backslash
end tell

That is the idea. Satimage does lots of good things, and is no doubt worth having for them, but shouldn't be necessary just for basic search and replace, which should really be handled natively in AppleScript.

3 Likes

Actually, if you include ASObjC as part of "native AppleScript", then you don't have to install any 3rd party tools to get any of the RegEx tools, like find, change. I have ASObjC RegEx handlers for these if anyone is interested.

1 Like