Working with RTF highlights

This is posted by way of a reference for another guessable step on which I’ve just tripped. A problem arises because when no highlight is set for any character string (the default) the AppleScript property background becomes difficult to use. Run this with no highlight set and the script errors at the ‘if’ line as variable ‘x’ is not defined despite background being a property of a word object.

tell application id "com.devon-technologies.thinkpro2"
	tell selected text of think window 1
		set x to background of word 1
		if x is not missing value then
			display alert (x as string)
		else
			display alert "No highlight set"
		end if
	end tell
end tell

It doesn’t even result in the ‘missing value’ ApplEscript allegedly provides for null values. Somewhat counter-intuitively you must do this instead:

tell application id "com.devon-technologies.thinkpro2"
	tell selected text of think window 1
		set z to properties of word 1
		set x to background of z
		if x is not missing value then
			display alert (x as string)
		else
			display alert "No highlight set"
		end if
	end tell
end tell

Also, don’t try logically collapsing that extra step into one line “set x to background of properties of word 1” as that fails too. How I wish AppleScript implementation followed the object model in the sdef! IOW, you call an object’s properties from a reference to that object and not via some abstract route or interim placeholder. Perhaps at some point the info in the Dictionary could be further annotated to mark properties not-readable from their parent object

Other points. The colour values of the highlight are 16-bit RGB, so 0-65535 instead of 8-bit 0-255. Multiply 8-bit values by 257 to get a 16-bit value (I think!). To set no value, pass background an empty set.

For later readers, this will allow for some tinkering/testing en route to actual production work:

tell application id "com.devon-technologies.thinkpro2"
	tell selected text of think window 1
		 -- yellow highlight (65535 is 255 in 16-bit):
		--set background of word 1 to {65535, 65535, 0}

		-- white highlight:
		--set background of word 1 to {65535, 65535, 65535}

		-- set no highlight at all (default):
		--set background of word 1 to {}

		set z to properties of word 1
		set x to background of z
		if x is not missing value then
			display alert (x as string)
		else
			display alert "No highlight set"
		end if
	end tell
end tell

This thread, from 2006, is what tipped me off to the workaround.

HTH!

(removed; not relevant)

Interesting. However, if no highlight is set, an empty alert is set, so X is not set to missing value. However, this time SD does show X as being set to: «empty». Go figure…! So the last test posted actually fails as AppleScript seems to be unable to understand «empty». It was only be chance that my last experiment clearly resulted in «empty» being coerced to the AppleScript-understandable ‘missing value’ constant. Thanks, nonetheless.