Mimsy Were the Borogoves

Hacks: Articles about programming in Python, Perl, Swift, BASIC, and whatever else I happen to feel like hacking at.

AppleScript Preview in Snow Leopard and Lion

Jerry Stratton, August 1, 2012

The one app that didn’t seem to support AppleScript control over window location was the one app it would have been most useful in: the built-in Preview application on Mac OS X.

It turns out, Preview does support AppleScript, but that support is turned off by default. Thanks to Trash Man at MacScripter.net for the commands that turn it back on:

  • sudo defaults write /Applications/Preview.app/Contents/Info NSAppleScriptEnabled -bool true
  • sudo chmod 644 /Applications/Preview.app/Contents/Info.plist
  • sudo codesign -f -s - /Applications/Preview.app

The first line enables AppleScripting Preview; the next two lines are necessary in Snow Leopard, Lion, and, presumably, above, because starting with Snow Leopard Mac OS X signs the built-in applications. When you change the default, that changes the signature, and Preview will fail to start because its signature doesn’t match what the OS expects. The next two lines re-sign Preview so that the OS will accept it.

If you use Leopard or earlier, you should only need the first line.

Once you enable scripting, we can stack PDFs or other documents in Preview directly on top of each other for easy comparison using command-~ document switching.

[toggle code]

  • tell application "Preview"
    • copy (every window whose visible is true and resizable is true) to windowList
    • copy the bounds of the first item of windowList to windowBounds
    • repeat with aLowerWindow in the rest of windowList
      • set the bounds of aLowerWindow to windowBounds
    • end repeat
  • end tell

Works great for comparing the differences between an original image and an optimized image, or for minor differences in the text of a PDF document.

Note that this is an improvement on the script in the earlier article. In the earlier script, if the first window happened to be an invisible or unmodifiable one, the script might end up resizing all of them to be too small to work with.

Update August 30, 2012: added “and resizable is true” to window query.

In response to Stack windows on top of each other: If you want to stack multiple windows directly on top of each other, it’s easy to do in any well-behaved application, such as Nisus Writer Pro, Safari, Mail, and even older applications like AppleWorks 6 and Microsoft Word X.