Trouble with Contents

A problem arises when you're targeting an application whose dictionary defines a contents property for one of its object types. Applications shouldn't do this; it's bad behavior, because they're overlapping with a piece of AppleScript's own built-in vocabulary. In the context of a tell block directed at such an application, there is an ambiguity as to whether the word contents will be seen as the contents of operator or the application's contents property.

Warning

I'm told that the problematic nature of the contents property is actually an AppleScript bug. And AppleScript itself is to blame for taking the lead here; it defines a contents property for its selection-object class, luring application developers into doing the same sort of thing.

An example of such an offender is BBEdit. In BBEdit, when you ask for a text element such as a word, it gives you a reference rather than a string. That's good, because it's then possible to access that element in its context and do things to it. But then BBEdit does something bad: it defines the contents property as your way of obtaining the actual string. But it can be quite tricky to get AppleScript to ask BBEdit for the contents of something, because it often sees this as an attempt to dereference a reference instead.

So this works to obtain an actual string:

tell application "BBEdit"
    set w to contents of word 4 of window 1
end tell
w -- "test"

But this doesn't:

tell application "BBEdit" set w to contents of (get word 4 of ...

Get AppleScript: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.