:merzwaren:

Scripting Style

Last updated on March 22, 2002


Commonly Used Commands
Customizing Style Through Scripts
Attachable Events
The “Startup” Script
Editing & Debugging Scripts
Internet Resources


One of Style’s best features is its support for AppleScript (and for other scripting languages based on Apple’s Open Scripting Architecture, like Frontier). Style is scriptable, recordable and attachable; it has an easily customizable Script menu and supports Frontier’s menu sharing protocol.

This document contains some tips that may be useful if you’re planning to script Style, but it assumes you are already somewhat familiar with scripting and with the AppleScript language in particular. 90% of the HTML code of this page was automatically generated by Style itself using an HTML conversion script originally written by Bill Cheeseman.


Commonly Used Commands

You can view Style’s scripting dictionary by opening Style with the Script Editor. The dictionary, however, does not explain all the possible usages of verbs and classes. If you’re still learning AppleScript, you may want to use the Script Editor’s recording feature to see examples of valid AppleScript syntax.

Here’s a brief list of the most common commands:

set

This is probably the most important command, as it lets you modify the values of an incredible number of different objects. For example, here’s how you can change the font of the first paragraph of the front document:

 set the font of the first paragraph of the front document to "Helvetica"

or move a window to a different screen position:

 set position of document 1 to {21, 48}

or change the search string seen in Style’s Find dialog:

 set search string to "bogus"

A crucial use of the set command is to enter text in a document, at the insertion point or at an arbitrary position:

 tell front document of application "Style"

  set selection to "This is a test." -- insert text at the insertion point

  set end to "This is only a test." -- insert text at the end of the document

  set insertion point after word 25 to "Only a test." -- at an arbitrary position

 end tell

The set command is so versatile that it can even be used to replace all occurrences of a word with another word, like this:

 set every word where it is "darkness" to "light"


get

This command is a lot like set, but it just reads values without changing them. For instance:

 get font of paragraph 1 of document 1

  --> "Palatino"

In AppleScript, the word get is optional, so the above fragment can be written simply as:

 font of paragraph 1 of document 1


exists

You can use this verb to make sure an object actually exists before trying to use it. For example, many scripts act on the frontmost document, so they would fail with an error if executed with no open documents: you can use this verb to allow these scripts to fail gracefully with a meaningful message, like this:

 tell application "Style"

  if front document exists then

   -- do your thing here

  else

   display dialog "Please open a document before using this script."

  end if

 end tell


count

This verb allows a script to know how many elements of a given type are contained within a specified object. It can be written in many different forms: for example, the following fragments are all equivalent:

 count words of document 1

 count document 1 each word

 number of words of document 1


make

In Style, this command is used solely to create new documents. By default, the document is created blank, but you can optionally specify the initial text. You can also specify the initial properties of the document: for example, you can create invisible windows that can be used as “scratchpads” by your script.

 make new document

 make new document with data "Hello!"

 make new document with properties {name:"worksheet", visible:false}

The make command returns a reference to the newly created object. In Style, this reference uses an ID that’s guaranteed to remain the same throughout the lifetime of the object, even if you rename it or change its index.


open

Use this command to open files. If the file is in a foreign format (like Microsoft Word) and XTND translation is active, Style looks for a translator that can import the file. You can override the choice of the translator by using the optional “as” parameter: this amounts to choosing a particular translator from the file type pop-up menu in Style’s Open dialog.

 open file "Xanadu:Desktop Folder:Scripting Tutorial"

 open file "Xanadu:Desktop Folder:Scripting Tutorial" as "Microsoft Word 4-5"

The optional with properties parameter allows you to specify the initial properties of a document created from a file, like this:

 open file "Jean-Louis:Allegro:Apple Menu Items:Scratch Pad" with properties ¬

   {background color:yellow, auto indent:true}

You can use this parameter to open a document without showing it:

 open file "Ortekka:temp:log" with properties {visible:false}


close

Use this command to close windows. If a window contains unsaved changes, Style will display a “Save Changes” alert box. You can bypass this alert by including the optional “saving” parameter:

 close document "Steve & Bill" saving yes


save

This command lets you save documents where you specify, in one of the available file formats.

 save front document in file "Mecca:Desktop Folder:Landslide" as "Microsoft Word"

What follows the “as” parameter can be either the name of one of the installed translators, or the corresponding four-letter file type (e.g., “WDBN” for Microsoft Word documents).


print

Use this command to print documents. By default, this command puts up the familiar Print dialog box, as if you had chosen Print from the File menu. You can bypass this dialog by making sure Style is in the background when this command is issued, like this:

 tell application "Finder" to activate

 tell application "Style" to print document 1


select

The most common use for this verb is to move the insertion point or to select a range of text, as in:

 tell front document of application "Style"

  select beginning -- move the insertion point to the beginning of the document

  select end -- move the insertion point to the end of the document

  select before word 5 -- move the insertion point before the fifth word

  select after selection -- collapse the selection

  select paragraph 2 -- highlight the second paragraph

  select ( text from character 12 to character 25 ) -- select an arbitrary range

 end tell

This multi-purpose verb can also be used to select (choose) menu items:

 select menu item "Show Clipboard" of menu "Edit"

although in most cases, there is a more direct way to accomplish the same task: for example, the above script can be written more effectively as:

 show clipboard

And finally, you can select a window to bring it to the front, as in:

 select window "Credits"


quit

Use this command to quit Style. You can optionally specify whether changes to open documents should be saved or not before quitting.

 quit saving yes

 quit saving no


show/hide

These verbs allow you to show and hide windows. They’re essentially a more natural way of setting the visible property of windows:

 hide window "Scripting Tips" -- is equivalent to:

 set the visible of window "Scripting Tips" to false

The “show” command can also be used to scroll the selected text into view, as in:

 tell front document of application "Style"

  select beginning -- move the insertion point

  show selection -- scroll to bring the insertion point into view, if necessary

 end tell


search

Use this command to find occurrences of words in a given document or text range, as in:

 tell application "Style"

  search document "Presidential Campaign" looking for "President Bush"

  search second paragraph of front document looking for "Style"

 end tell

Note that the text to search must be preceded by looking for. The search starts at the current insertion point: to start from the beginning of the document, just use select beginning to move the insertion point before starting the search. If the search is successful, the first match is selected and search returns true, otherwise, the current selection isn’t changed and search returns false.

One way to replace all occurrences of a given word with another is to use search in a repeat loop, like this:

 tell document "Presidential Campaign" of application "Style"

  select beginning

  repeat while search looking for "President Bush"

   set selection to "President Clinton"

  end repeat

 end tell

Although you can do the same thing faster using a filtered reference:

 tell document "Presidential Campaign" of application "Style"

  set every text where it = "President Bush" to "President Clinton"

 end tell

The search command may take two optional parameters: whole words and exact match: if used, these parameters override the global settings specified in Style’s Find dialog for the duration of the search command.

 search document 1 looking for "Powell" with exact match and whole words

 search document 1 looking for "Pow" with exact match without whole words


The “current item” keyword

Style supports a special keyword, current item, that lets you refer to the current list element when processing lists (obtained through the use of ranges, filtered references, or the every keyword). In many cases, current item allows you to accomplish with a single Apple event what would previously require a repeat loop (and thus, several Apple events).

For example, suppose you want to add line numbers to a document. You could use a repeat loop like this:

 tell application "Style"

  repeat with p in paragraphs of front document

   set beginning of p to index of p & ": "

  end repeat

 end tell

Although this script works, the more lines you have in your document, the more Apple events it generates, and since Apple events are slow, the whole script becomes slow.

Now, here’s how you can rewrite the above script using the current item keyword:

 tell front document of application "Style"

  set paragraphs to {index of current item, ": ", current item}

 end tell

With each iteration, Style replaces current item with the paragraph being processed. The beauty of this technique is that it uses a single Apple event, and the loop is now performed directly by Style with native, compiled code.

Here’s how you could shorten long words by inserting an ellipsis after the eighth character:

 set every word of front document whose length > 10 to ¬

   {text from character 1 to character 8 of current item, ¬

    "", last character of current item}

And finally, this is how you could add HTML tags to runs of bold text:

 set style runs whose style contains bold to {"<b>", current item, "</b>"}


Customizing Style Through Scripts

Style’s support for AppleScript goes beyond scriptability and recordability: Style is also attachable, which means you can attach scripts to Style, even while it’s running, to modify the way it handles certain commands, like close and save. You can attach scripts either to the application object, or to individual documents. When an event is sent to an object that has a script attached to it, Style looks in the script for a handler for that event. If a suitable handler is found, the event is sent to the script handler, rather than being processed as usual. An example will make this clear. Suppose you want to override the way the close event is handled so that Style beeps instead of closing windows. Here’s how you could do this with a script:

 tell application "Style"

  

  script myAttachment

   on close of myWindow

    beep 1

   end close

  end script

  

  set script of it to myAttachment

  

 end tell

Note the portion of the script beginning with “script myAttachment” and ending with “end script”: that’s called a script object in AppleScript jargon. A script object can contain one or more handlers: in the example above, there’s only one handler, for the close event, beginning with “on close” and ending with “end close”.

To see attachability in action, paste this script into a blank Script Editor window and run it, then try closing a Style window (either by clicking the close box or by choosing “Close” from the File menu): Style will beep and the window won’t close.

In this case, the close handler completely overrides Style’s built-in behavior: in most cases, however, you only want to add to the default processing rather than replace it. In AppleScript, this can be done using the continue statement, like this:

 tell application "Style"

  

  script myAttachment

   on close of myWindow

    beep 1

    continue close myWindow

   end close

  end script

  

  set script of it to myAttachment

  

 end tell

The statement “continue close myWindow” tells Style to resume processing of the close event normally. Using this statement you can add custom pre- and post-processing to various common operations without disrupting the application’s logic.


Attachable Events

An attachment script can intercept most of the events that Style sends to itself during normal operation, including quit, make new document, open, close and save. In addition, an attachment script can intercept user-defined events sent from external sources. In this case, you must specify the event using its four-letter event class and four-letter event ID rather than its name, because your custom event is not listed in Style’s dictionary.

For example, suppose you want Style to respond to the GetURL event defined in the dictionary of many Internet applications. By default, Style ignores this event, but if a handler for it is present, Style will give that handler a chance to process the event. Here’s how such a handler could be written:

 tell application "Style"

  

  script GetURLAttachment

   on «event GURLGURL» myURL

    activate

    set contents of clipboard to myURL

   end «event GURLGURL»

  end script

  

  set script of it to GetURLAttachment

  

 end tell

The expression «event GURLGURL» is a special AppleScript notation for specifying an event using its event class and event ID: for the GetURL event, both the class and the ID are “GURL”. The GetURL event takes a URL as its only parameter.

If you have Internet Config installed, here’s how you can see this script in action: open Internet Config, go to the “Helpers” panel, set the helper for “mailto” to Style and save your Internet preferences. From now on, Internet Config will try to open all URLs beginning with “mailto:” (that is, email addresses) with Style, by sending a GetURL event to it. Now command-click a mailto URL in any Internet Config-aware application (like Style itself): this will trigger the above attachment and the URL will be copied to the clipboard. No big deal, but this (admittedly convoluted) example gives you a glimpse of the many things that can be accomplished with AppleScript and attachability.


The “Startup” Script

When Style starts up, it looks for a compiled script called “Startup” in the Style folder. If this script exists, Style loads it and executes it before handling any other command. For example, you can use a startup script to assign a keyboard equivalent of your choice to the “Page Setup” menu item, like this:

 tell application "Style"

  set keyboard equivalent of menu item "Page Setup..." of menu "File" to "L"

 end tell

The startup script is a natural place for attachment scripts, since attachments are lost when Style quits and need to be re-attached every time Style is launched.

If you put an attachment in the startup script, you can override the run event sent by the Finder when the application icon is double-clicked, since Style executes the startup script before processing the run event. By default, Style handles this event by opening a new blank window. This startup script forces Style to show the Open dialog instead:

 tell application "Style"

  

  script startupAttachment

   on run

    select menu item "Open..." of menu "File"

   end run

  end script

  

  set script of it to startupAttachment

  

 end tell

Cool, huh?


Editing and Debugging Scripts

To edit a script in the Script menu from within Style, hold down the option key while you choose the script from the menu. The script will open in the Script Editor.

If Style encounters an error during the execution of the startup script or a script invoked through the Script menu, it puts up an alert box with an “Edit” button. Clicking this button (or typing command-E) opens the script in the Script Editor and highlights the offending line.

If you use a third-party AppleScript editor (like Script Debugger or Scripter), you may want your scripts to open in that editor. To do this, make sure the script files have the correct creator type (the four-letter code that uniquely identifies an application). You can even force Style to edit all scripts in the editor of your choice, regardless of their creator type. To do this, you have to edit the “PREF” resource in the “Style Preferences” file with ResEdit, changing the “Preferred Script Editor” field from “****” to the creator type of the editor (for example, “asDB” for Script Debugger).


AppleScript Resources on the Internet

A couple of good starting points for finding AppleScript-related resources on the Internet are Apple’s own website and Bill Cheeseman’s excellent AppleScript Sourcebook. The Late Night Software website, home of the powerful Script Debugger 2.0 development environment, is also worth a mention.

Whether you’re just starting to learn AppleScript or you’re already an experienced scripter, you may want to subscribe to the MacScripting mailing list, a forum devoted to the discussion of AppleScript, Frontier and other OSA scripting languages. To subscribe, send a message to: the listserver at Dartmouth. The body of the message should contain the following text: subscribe macscrpt <your name> (Replace <your name> with your real name.)


Valid XHTML 1.0! Copyright © 1998-2002 Merzwaren