Scripting within Keyboard Maestro

Hi guys thanks for approving the membership :slight_smile:

I’ve started working with Keyboard Maestro (KBM) and one of the macros I’m looking to produce is one to open a specific Apple note, position it on screen, size it, and close the main notes window leaving the single note on screen.

KBM can do a lot of this, but for some parts I’ve had to start learning Apple Script.

The first bit of script opens Notes and shows the note I want:

tell application "Notes"
	show note "~Scratchpad~"
end tell

I then use KBM to Float the selected note, and use another piece of Apple script to position and size the note:

tell application "Notes" to set the bounds of the front window to {2900, 80, 3300, 800}

Finally another bit of script to close the main Notes app window:

tell application "Notes"
	repeat until note = "~Scratchpad~"
		close window 2
		exit repeat
	end repeat
end tell

Ideally what I’m looking to find out is:

  1. Is there a more elegant bit of sizing code that I can use to set the note to the minimum supported width and to a height of the text contained within the note.

  2. The bit of code to close the main app widow is a modification of code I found on the web, so is likely not the best solution. A ‘proper way’ of completing the closure would be appreciated:)

So guys any assistance would be appreciated :slight_smile:

dbrewood. I’ve included my suggestion below. A few comments:

  • I don’t know of a way to resize the window to fit the text (but see possible workaround below).
  • I don’t have Keyboard Maestro and so I used GUI scripting to float the note.
  • I don’t believe the repeat loop is needed.
set theNote to "~Scratchpad~"

tell application "Notes"
	activate
	try
		show note theNote
	on error
		display dialog "The note " & quote & theNote & quote & "was not found" buttons {"OK"} cancel button 1 default button 1 with icon stop
	end try
end tell

tell application "System Events" to tell process "Notes"
	click menu item "Float Selected Note" of menu "Window" of menu bar 1
end tell

-- a short delay may be needed at this point

tell application "Notes"
	set the bounds of window 1 to {80, 80, 880, 880}
	close (windows 2 thru -1)
end tell

As regards resizing the window to fit the text, a possible workaround (if the paragraphs are approximately equal in size) is to count the number of paragraphs in the note and then to set window sizes through trial-and-error testing. For example,

set theNote to "~Scratchpad~"
set ppp to 20 -- ppp is pixels per paragraph - test with different values

tell application "Notes"
	set noteText to (plaintext of note theNote)
	set paragraphCount to count (paragraphs of noteText)
	set bounds of window 1 to {80, 80, 880, (80 + (paragraphCount * ppp))}
end tell

My thanks, I had to make some adjustments so it’d work with KBM but it helped a lot. Many, many thanks!