NEW APPLESCRIPT CAPABILITY

As of Mac OS X 10.7 Lion, the AppleScript Editor gave Macintosh users a new capability: script templates. This allows a user to access script templates using AppleScript Editor’s File > New From Template menu item. Script templates are saved in a protected folder where you can have any number of sub-folders to organize your templates. Apple also provides a variety of useful script templates at this location, including scripts for creating file processing droplets, Mail rule actions, iChat message responders, and more.

In our previous post we introduced readers to a script that would automate placing a script template into this protected folder on the Macintosh. The folder is located inside the application support folder for the computer administrator (Library:Application Support:Script Editor:Templates:).

Our script assumed the existence of a sub-folder named “InDesign Templates” at this location. To make the script more robust, the following version checks to see if the folder exists and, if not, creates the folder.

Add Script Template

   (*Assumes user has administrative privileges. Tests for folder, creates it if not found.*)
   set folderName to "InDesign Templates"
   try
    	set theFile to choose file with prompt "Select script template"
	set theInfo to info for theFile
	if file type of theInfo is not "osas" then
	   error "Wrong file type chosen"
	end if
	set supportFolder to path to application support as string
	set parentFolder to supportFolder & "Script Editor:Templates:"
	set folderPath to parentFolder & folderName
	tell application "Finder"
	   set itExists to exists folder folderPath
	   if itExists is false then
		set newFolder to make new folder at parentFolder with properties {name:folderName}
	   end if
	   set folderRef to folder folderPath
	   move theFile to folder folderRef
	end tell
   on error errStr
	activate
	display alert errStr
   end try

In the event you would have more than one folder for your scripts, you could make the script more flexible by having the user choose the appropriate folder for placing the template. This version gives the user the option of choosing a folder that exists or creating a new folder.

Add Script Template_Choose

   try
	set filePath to path to desktop from user domain
	set theFile to choose file with prompt "Select script template" default location filePath
	set theInfo to info for theFile
	if file type of theInfo is not "osas" then
	   error "Wrong file type chosen"
	end if
	set parentPath to (path to application support) as string
	set folderPath to (parentPath & "Script Editor:Templates:") as alias
	set folderRef to choose folder with prompt "Choose folder for templates" default location folderPath
	tell application "Finder"
	   move theFile to folderRef
	end tell
   on error errStr
	activate
	display alert "Error: " & errStr
   end try

The thing to remember about both of the above scripts is that when using a choose file or choose folder command, the optional default location parameter needs to be an alias reference–not a string. The result of a path tochoose file or choose folder command is an alias reference. To add folder references to the result of a path to statement the alias reference needs to be converted to a string. Additionally there is a third way to reference a folder and a file. That is as a folder or file object reference which is recognized by applications such as Finder and System Events. This reference includes the word “folder” or “file”. Review the two scripts above to see how alias references, text references, and file/folder object references are used.

MORE SCRIPT AUTOMATION

Script templates are more often used for general or more complex scripts. On the other hand, many scripts that you write will be constructed by using a series of handlers: code that lends itself to reuse under a host of different conditions. For instance, the Save To Favorite script developed in the previous blog would benefit by adding code to determine if a document is open in InDesign. It also needs to check to make sure that InDesign is running in a non-modal state (does not have a modal dialog window open). This can be accomplished by the following getDocRef handler:

getDocRef()

   try
      set docRef to getDocRef()
   on error errStr
      display alert errStr
      return
   end try
   --========
   --HANDLERS
   --========
   (*Returns reference to active document; otherwise generates error.*)
   on getDocRef()
	tell application "Adobe InDesign CC 2015"
	   if modal state = true then
		 error "Please close dialogs before running script"
           end if
	   if not (exists document 1) then
		 error "Requires active document"
	   else
		 return active document
	   end if
	end tell
   end getDocRef

Checking for the application’s modal state and the existence of a document is one of the first things a script might do. For this we have included a try/on error statement block with the call to the handler. The handler also includes a HANDLERS divider to help organize the script.

SCRIPT HANDLER LIBRARY

As with script templates, it is a good idea to build a library of script handlers that are readily available for your use when you start writing scripts. Macintosh provides the user with another convenience, the AppleScript Editor’s Script Folder. You can see the folders in this location using the following script:

   set theFolder to path to library folder as string
   set libFolder to theFolder & "scripts:Script Editor Scripts"
   set theLocation to libFolder as alias
   set theChoice to choose folder with prompt "Choose Folder" default location theLocation
   theChoice

Access to this folder (and the script snippets provided by Apple) is now controlled, since OS X 10.6, as part of AppleScript Editor’s preferences. In the General panel that opens from the AppleScript Editor’s Application > Preferences menu item, make sure Show Script menu in menu bar is checked. The Show Computer scripts is optional but I suggest checking this option. Checking Show Script menu in menu bar places a script icon (Script Menu) in the computer’s top menu bar. When clicked, it opens to reveal a menu of script automation locations. (For the Script Menu, previous versions of the OS required using an AppleScript utility.)

Script Menu AppleScript Preference

The Script Menu

The Script Menu is a system-wide menu that serves as an invaluable tool for people who love to save time and energy with scripts. It provides quick access to favorite scripts and automation tools stored and displayed in an organized file listing. It can save and execute files saved in any of the following formats:

  • AppleScript scripts and applets
  • UNIX Shell script text files
  • Automator workflow files
  • Automator applets (more about Automator in future blog posts)

At the top of the Script Menu listing, the Open Scripts Folder menu item allows access to three folders you may want to take advantage of:

  • [Active application] Scripts Folder. – Access to the folder for the frontmost application. For Instance, if Finder is the frontmost application, this item will display as Open Finder Scripts Folder.
  • User Scripts Folder – The scripts folder for the current user
  • Computer Scripts Folder – located in the top-level Library folder, contents of this folder are available to all users. This is where you will find the Script Editor Scripts folder that will house your InDesign CC Handler library.

Open Scripts Folder menu list

Creating Your Handler Library

You will want to add your own library of handlers to folders inside the Script Menu. To start, add a folder named “Adobe CC Handlers” to Script Editor’s script folder. You can do this by clicking on Open Computer Scripts Folder from Script Menu > Open Scripts Folder. From there you can add a folder as you would in any Finder list. Alternatively you can use the following handy script:

“Handler Library”

   set folderName to "InDesign CC Handlers"
   set libFolder to path to library folder as string
   set scriptPath to (libFolder & "scripts:Script Editor Scripts:")
   set folderPath to scriptPath & folderName
   tell application "Finder"
      if not (exists folder folderPath) then
         make folder at scriptPath with properties {name:folderName}
      end if
      set folderRef to folder folderPath
   end tell

Once this folder is created, decide on the classifications of script handlers that you will want in your Handler Library. As a suggestion the following list is provided: set folderList to {“Documents”, “Find-Change”, “Interactive”, “Library”, “Master”, “Page”, “Page-Item”, “Place”, “Selection”, “Styles”, “Tables”, “Text”, “Transform”, “XML”}

Place your list of folder names to the top of the “Handler Library” script above.

   set folderList to {[list of folder names here]}

Just before the end tell statement, add the following:

   repeat with i from 1 to length of folderList
      make folder at folderRef with properties {name: item i of folderList)
   end repeat

Because this little script runs so fantastically fast, you will want to put a little alert at the bottom of the script:

   say "files done" using "Kathy"

Make sure that speech is enabled on your computer with the volume set to a comfortable level. Now compile the script and run. When you hear “files done” you can verify your folders are created by opening the script menu from the top menu bar.

 Script Menu Listing

ADD HANDLER TO HANDLER LIST

The neat thing about having handlers in Script Editor’s Scripts folder is that when you are working with AppleScript Editor, all you need do to add a handler to a script is to hold down the Control key and click inside of your script. Select the handler you want from the menu that pops up. To see how this works, walk through the following tutorial.

    1. Convert your handler from code to text (a string).
      Place a backslash in front of every quotation mark. For our getDocRef handler above, the text will look like the following:
   try
      set docRef to getDocRef()
   on error errStr
      display alert errStr
      return
   end try
   --========
   --HANDLERS
   --========
   (*Returns reference to active document; otherwise generates error.*)
   on getDocRef()
	tell application \"Adobe InDesign CC 2015\"
		if modal state = true then
		    error \"Please close dialogs before running script\"
		end if
		if not (exists document 1) then
		    error \"Requires active document\"
		else
		    return active document
		end if
	end tell
   end getDocRef
    1. Save the handler as getDocRef.scpt.
    2. Enter the following code into a new script to create an InDesign handler template:
   set targetString to "--XXXX"

   set scriptText to "


   --Place script here

   "

   tell application "AppleScript Editor"
	tell the front document
		set thecontents to contents
		set theOffset to offset of targetString in thecontents
		if theOffset is not 0 then
			set selection to characters theOffset thru (theOffset + ((length of targetString) - 1))
			set the contents of the selection to scriptText
		else
			set contents of selection to scriptText
		end if
	end tell
   end tell

Notice the beginning and ending quotes that surround –Place Script here. Library handlers are designed to work with Script Editor only. The method used above for providing these handlers to Script Editor is simplified from sample code provided by Apple. As with other sample scripts, use at your own risk.

  1. Save this script to the desktop with the name “ScriptLibTemplate.scpt”.
    Later, you may want to add this to template to those available from your AppleScript Templates collection.
  2. Copy the code from the “ScriptLibTemplate” into a new script.
  3. Copy the text (string) version of your handler and paste it into the new script.
    Paste the copied script to replace the code from the template that says “–Place script here”.
  4. Compile the script.
    The script should compile without error. If it does error, look for quotes that are not escaped (with a slash in front).
    Make sure the handler code you added has a quotation mark above and below (is enclosed in quotation marks provided by the template).
  5. Save your script with the handler to the desktop with the name “getDocRef.scpt”

FILE THE HANDLER

Now that you have the handler created and saved on the desktop, you can add it to the appropriate folder in your Handler Library (in AppleScript’s scripts folder). Hopefully you have created a folder named “Documents” in the scripts folder as the getDocRef handler would be a perfect candidate for this classification.

  1. Click on the small script icon for the Script Menu in the top menu of your computer.
  2. Navigate to Script Editor Scripts and then to the Documents folder inside your InDesign CC Handlers folder.
  3. Click on the Documents folder to open it.
  4. Drag your handler file to the folder.

Alternatively, you can use the following script to move the handler file to the appropriate folder in your Handler library.

File InDesign Handler script

Copy the following script to a new AppleScript Editor file:

   set libFolder to (path to library folder) as string
   set folderPath to (libFolder & "scripts:Script Editor Scripts:InDesign CC Handlers") as alias
   set tempPath to path to desktop from user domain
   set handlerFile to choose file with prompt "Choose handler script" default location tempPath
   set theInfo to info for handlerFile
   if file type of theInfo is not "osas" then
	error "Wrong file type chosen"
   end if
   set folderRef to choose folder with prompt "Choose folder for handler" default location folderPath
   tell application "Finder"
	move handlerFile to folderRef
   end tell

Compile the script. Save it to the Desktop as “File InDesign Handler.scpt”

When you run the script, choose your getDocRef.scpt file when prompted to “Choose handler script”. You will then be prompted to choose a folder from within your script handler library. Choose the folder “Documents” if available. If not, create it.

TRY OUT YOUR AUTOMATION

Create a new script using the handler you just saved.

  1. Start a new file in AppleScript Editor.
  2. Hold down the Control key and click in the editor window.
    You will be presented with a menu of the items in Script Editor’s scripts folder.
  3. Navigate to your Documents folder inside your InDesign CC Handlers folder and choose the getDocRef file.
  4. With Adobe InDesign CC 2015 running in the background, compile your script and run it.
  5. If you don’t have an active document open, you will get a message that the script “Requires active document”.
  6. Make sure there is an active document open in InDesign CC 2015 and test the script again.

MORE AUTOMATION

To run a script from the Script Menu, just click on its listing.

You can further organize your scripts by adding folders to any one or more of the folders accessed from this menu.

You may want to add your File InDesign Handler script to one; perhaps in a folder of your own named “Files-Folders” or maybe “Favorites”

Try it Out

  1. Create a folder called Favorites in your User Scripts folder.
    From the Script Menu, choose Open Scripts Folder > Open User Scripts Folder.
    With the Scripts window frontmost, select File > New Folder from the Finder.
    An untitled folder will be created in your Scripts folder window.
  2. Update the name of the untitled folder created
  3. Drag the File InDesign Handler script from your desktop to the folder.
  4. Click on the Script Menu icon. The folder you created should now be part of the top level listing.
  5. Click on the listing for the File InDesign Handler. The script should run and present the system file chooser for choosing the Handler to file.
  6. Cancel out of the dialog unless you have a handler handy to file to your Handlers Library.
  7. Any time you want to save a Handler for your InDesign scripts, use ScriptLibTemplate to create the handler and file it using the File InDesign Handler script.

Note: If you double-click on a script entry in the Script Menu, the script will open in Script Editor.

ON YOUR OWN

You may also want to add another folder or two to the Script Menu. Your Favorites folder might be a good place to place your favorite AddScriptTemplate script.

For practice, create a simple script handler such as a display dialog script to get a string response from the user. Using the ScriptLibTemplate template, create a Handler file for your handler. Once created, save the handler file to the desktop. Now run the File InDesign Handler script you saved in your folder for the Script Menu. When the script runs you will be asked to choose the handler file, and then the folder into which you want the handler saved. Once the script terminates, check to make sure the handler was saved in the folder designated. (From AppleScript Editor’s File menu choose New (Command + N). Control+Click in the editing window and select the handler from your InDesign CC Handlers folder. Double-check your handler to make sure it works as anticipated. Sit back and think of all the ways having script templates and script handlers easily accessible in convenient locations on your computer will save you hours when it comes to writing scripts.