");
}
}
}
//Close the text file.
myTextFile.close();
}
38
Text and Type
Text objects
39
}
}
}
function myFindTag (myStyleName, myStyleToTagMapping){
var myTag = "";
var myDone = false;
var myCounter = 0;
do{
if(myStyleToTagMapping[myCounter][0] == myStyleName){
myTag = myStyleToTagMapping[myCounter][1];
break;
}
myCounter ++;
} while((myDone == false)||(myCounter < myStyleToTagMapping.length))
return myTag;
}
Text objects
The following diagram shows a view of InCopy’s text-object model. There are two main types of text
object: layout objects (text frames) and text-stream objects (stories, insertion points, characters, and words,
for example). The diagram uses the natural-language terms for the objects; when you write scripts, you will
use the corresponding terms from your scripting language:
document
story
spread, page, layer
insertion points
characters
text containers
text frame
words
insertion points
lines
characters
paragraphs
words
text columns
lines
text style ranges
paragraphs
texts
text columns
notes
text style ranges
texts
notes
For any text-stream object, the parent of the object is the story containing the object. To get a reference
to the text frame (or text frames) containing a given text object, use the parentTextFrames property.
For a text frame, the parent of the text frame usually is the page or spread containing the text frame. If the
text frame is inside a group or was pasted inside another page item, the parent of the text frame is the
Text and Type
Text objects
40
containing page item. If the text frame was converted to an anchored frame, the parent of the text frame
is the character containing the anchored frame.
Selections
Usually, InCopy scripts act on a text selection. The following script shows how to determine the type of the
current selection. Unlike many other sample scripts, this script does not actually do anything; it simply
presents a selection filtering routine you can use in your own scripts. (For the complete script, see
TextSelection.)
//Shows how to determine whether the current selection is a text selection.
//Check to see if any documents are open.
if (app.documents.length != 0){
//If the selection contains more than one item, the selection
//is not text selected with the Type tool.
if (app.selection.length != 0){
//Evaluate the selection based on its type.
switch (app.selection[0].constructor.name){
case "InsertionPoint":
case "Character":
case "Word":
case "TextStyleRange":
case "Line":
case "Paragraph":
case "TextColumn":
case "Text":
case "Story":
//The object is a text object; display the text object type.
//A practical script would do something with the selection,
//or pass the selection on to a function.
alert("Selection is a " + app.selection[0].constructor.name);
//If the selection is inside a note, the parent of the selection
//will be a note object.
if(app.selection[0].parent.constructor.name == "Note"){
alert("Selection is inside a note.");
}
break;
default:
alert("The selected object is not a text object. Select some text and try
again.");
break;
}
}
else{
alert("Please select some text and try again.");
}
}
else{
alert("No documents are open.");
}
Moving and copying text
To move a text object to another location in text, use the move method. To copy the text, use the
duplicate method (which has exactly the same parameters as the move method). The following script
fragment shows how it works (for the complete script, see MoveText):
Text and Type
Text objects
41
//Create an example document.
var myDocument = app.documents.add();
//Create a series of paragraphs in the default story.
var myStory = myDocument.stories.item(0);
myStory.contents = "WordA\rWordB\rWordC\rWordD\r";
//Move WordC before WordA.
myStory.paragraphs.item(2).move(LocationOptions.before, myStory.paragraphs.item(0));
//Move WordB after WordD (into the same paragraph).
myStory.paragraphs.item(2).move(LocationOptions.after,
myStory.paragraphs.item(-1).words.item(0));
//Note that moving text removes it from its original location.
When you want to transfer formatted text from one document to another, you also can use the move
method. Using the move or duplicate method is better than using copy and paste; to use copy and paste,
you must make the document visible and select the text you want to copy. Using move or duplicate is
much faster and more robust. The following script shows how to move text from one document to another
using move and duplicate (for the complete script, see MoveTextBetweenDocuments):
//Moves formatted text from one document to another.
var mySourceDocument = app.documents.add();
//Add text to the default story.
var mySourceStory = mySourceDocument.stories.item(0);
mySourceStory.contents = "This is the source text.\rThis text is not the source text.";
mySourceStory.paragraphs.item(0).pointSize = 24;
//Create a new document to move the text to.
var myTargetDocument = app.documents.add();
var myTargetStory = myTargetDocument.stories.item(0);
myTargetStory.contents = "This is the target text. Insert the source text after this
paragraph.\r";
mySourceStory.paragraphs.item(0).duplicate(LocationOptions.after,
myTargetStory.insertionPoints.item(-1));
One way to copy unformatted text from one text object to another is to get the contents property of a
text object, then use that string to set the contents property of another text object. The following script
shows how to do this (for the complete script, see CopyUnformattedText):
//Shows how to remove formatting from text as you move it
//to other locations in a document.
//Create an example document.
var myDocument = app.documents.add();
var myStory = myDocument.stories.item(0);
myStory.contents = "This is a formatted string.\rText pasted after this text will
retain its formatting.\r\rText moved to the following line will take on the formatting
of the insertion point.\rItalic: ";
//Apply formatting to the first paragraph.
myStory.paragraphs.item(0).fontStyle = "Bold";
//Apply formatting to the last paragraph.
myStory.paragraphs.item(-1).fontStyle = "Italic";
//Copy from one frame to another using a simple copy.
app.select(myStory.paragraphs.item(0).words.item(0));
app.copy();
app.select(myStory.paragraphs.item(1).insertionPoints.item(-1));
app.paste();
//Copy the unformatted string from the first word to the end of the story
//by getting and setting the contents of text objects. Note that this does
//not really copy the text; it replicates the text string from one text
//location to another.
myStory.insertionPoints.item(-1).contents =
myStory.paragraphs.item(0).words.item(0).contents;
Text and Type
Text objects
42
Text objects and iteration
When your script moves, deletes, or adds text while iterating through a series of text objects, you can
easily end up with invalid text references. The following script demonstrates this problem (for the
complete script, see TextIterationWrong):
//Shows how *not* to iterate through text.
var myDocument = app.documents.add();
var myString = "Paragraph 1.\rDelete this paragraph.\rParagraph 2.\rParagraph
3.\rParagraph 4.\rParagraph 5.\rDelete this paragraph.\rParagraph 6.\r";
var myStory = myDocument.stories.item(0);
myStory.contents = myString;
//The following for loop will fail to format all of the paragraphs.
for(var myParagraphCounter = 0; myParagraphCounter < myStory.paragraphs.length;
myParagraphCounter ++){
if(myStory.paragraphs.item(myParagraphCounter).words.item(0).contents ==
"Delete"){
myStory.paragraphs.item(myParagraphCounter).remove();
}
else{
myStory.paragraphs.item(myParagraphCounter).pointSize = 24;
}
}
In the preceding example, some paragraphs are left unformatted. How does this happen? The loop in the
script iterates through the paragraphs from the first paragraph in the story to the last. As it does so, it
deletes paragraphs beginning with “Delete.” When the script deletes the second paragraph, the third
paragraph moves up to take its place. When the loop counter reaches 2, the script processes the paragraph
that had been the fourth paragraph in the story; the original third paragraph is now the second paragraph
and is skipped.
To avoid this problem, iterate backward through the text objects, as shown in the following script (from
the TextIterationRight tutorial script):
//Shows the correct way to iterate through text.
var myDocument = app.documents.add();
var myString = "Paragraph 1.\rDelete this paragraph.\rParagraph 2.\rParagraph
3.\rParagraph 4.\rParagraph 5.\rDelete this paragraph.\rParagraph 6.\r";
var myStory = myDocument.stories.item(0);
myStory.contents = myString;
//The following for loop will format all of the paragraphs by iterating
//backwards through the paragraphs in the story.
for(var myParagraphCounter = myStory.paragraphs.length-1; myParagraphCounter >= 0;
myParagraphCounter --){
if(myStory.paragraphs.item(myParagraphCounter).words.item(0).contents ==
"Delete"){
myStory.paragraphs.item(myParagraphCounter).remove();
}
else{
myStory.paragraphs.item(myParagraphCounter).pointSize = 24;
}
}
Text and Type
Formatting text
43
Formatting text
In the previous sections of this chapter, we added text to a document and worked with stories and text
objects. In this section, we apply formatting to text. All the typesetting capabilities of InCopy are available
to scripting.
Setting text defaults
You can set text defaults for both the application and each document. Text defaults for the application
determine the text defaults in all new documents. Text defaults for a document set the formatting of all
new text objects in that document. (For the complete script, see TextDefaults.)
//Sets the text defaults of the application, which set the default formatting
//for all new documents. Existing text frames are unaffected.
//Set the measurement units to points.
app.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;
app.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
//To set the text formatting defaults for a document, replace "app"
//in the following lines with a reference to a document.
with(app.textDefaults){
alignToBaseline = true;
//Because the font might not be available, it's usually best
//to apply the font within a try...catch structure. Fill in the
//name of a font on your system.
try{
appliedFont = app.fonts.item("Minion Pro");
}
catch(e){}
//Because the font style might not be available, it's usually best
//to apply the font style within a try...catch structure.
try{
fontStyle = "Regular";
}
catch(e){}
//Because the language might not be available, it's usually best
//to apply the language within a try...catch structure.
try{
appliedLanguage = "English: USA";
}
catch(e){}
autoLeading = 100;
balanceRaggedLines = false;
baselineShift = 0;
capitalization = Capitalization.normal;
composer = "Adobe Paragraph Composer";
desiredGlyphScaling = 100;
desiredLetterSpacing = 0;
desiredWordSpacing = 100;
dropCapCharacters = 0;
if(dropCapCharacters != 0){
dropCapLines = 3;
//Assumes the application has a default character style named "myDropCap"
dropCapStyle = app.characterStyles.item("myDropCap");
}
fillColor = app.colors.item("Black");
fillTint = 100;
firstLineIndent = 14;
Text and Type
Formatting text
gridAlignFirstLineOnly = false;
horizontalScale = 100;
hyphenateAfterFirst = 3;
hyphenateBeforeLast = 4;
hyphenateCapitalizedWords = false;
hyphenateLadderLimit = 1;
hyphenateWordsLongerThan = 5;
hyphenation = true;
hyphenationZone = 36;
hyphenWeight = 9;
justification = Justification.leftAlign;
keepAllLinesTogether = false;
keepLinesTogether = true;
keepFirstLines = 2;
keepLastLines = 2;
keepWithNext = 0;
kerningMethod = "Optical";
kerningValue = 0;
leading = 14;
leftIndent = 0;
ligatures = true;
maximumGlyphScaling = 100;
maximumLetterSpacing = 0;
maximumWordSpacing = 160;
minimumGlyphScaling = 100;
minimumLetterSpacing = 0;
minimumWordSpacing = 80;
noBreak = false;
otfContextualAlternate = true;
otfDiscretionaryLigature = false;
otfFigureStyle = OTFFigureStyle.proportionalOldstyle;
otfFraction = true;
otfHistorical = false;
otfOrdinal = false;
otfSlashedZero = false;
otfSwash = false;
otfTitling = false;
overprintFill = false;
overprintStroke = false;
pointSize = 11;
position = Position.normal;
rightIndent = 0;
ruleAbove = false;
if(ruleAbove == true){
ruleAboveColor = app.colors.item("Black");
ruleAboveGapColor = app.swatches.item("None");
ruleAboveGapOverprint = false;
ruleAboveGapTint = 100;
ruleAboveLeftIndent = 0;
ruleAboveLineWeight = .25;
ruleAboveOffset = 14;
ruleAboveOverprint = false;
ruleAboveRightIndent = 0;
ruleAboveTint = 100;
ruleAboveType = app.strokeStyles.item("Solid");
ruleAboveWidth = RuleWidth.columnWidth;
}
ruleBelow = false;
if(ruleBelow == true){
ruleBelowColor = app.colors.item("Black");
44
Text and Type
Formatting text
45
ruleBelowGapColor = app.swatches.item("None");
ruleBelowGapOverprint = false;
ruleBelowGapTint = 100;
ruleBelowLeftIndent = 0;
ruleBelowLineWeight = .25;
ruleBelowOffset = 0;
ruleBelowOverprint = false;
ruleBelowRightIndent = 0;
ruleBelowTint = 100;
ruleBelowType = app.strokeStyles.item("Solid");
ruleBelowWidth = RuleWidth.columnWidth;
}
singleWordJustification = SingleWordJustification.leftAlign;
skew = 0;
spaceAfter = 0;
spaceBefore = 0;
startParagraph = StartParagraph.anywhere;
strikeThru = false;
if(strikeThru == true){
strikeThroughColor = app.colors.item("Black");
strikeThroughGapColor = app.swatches.item("None");
strikeThroughGapOverprint = false;
strikeThroughGapTint = 100;
strikeThroughOffset = 3;
strikeThroughOverprint = false;
strikeThroughTint = 100;
strikeThroughType = app.strokeStyles.item("Solid");
strikeThroughWeight = .25;
}
strokeColor = app.swatches.item("None");
strokeTint = 100;
strokeWeight = 0;
tracking = 0;
underline = false;
if(underline == true){
underlineColor = app.colors.item("Black");
underlineGapColor = app.swatches.item("None");
underlineGapOverprint = false;
underlineGapTint = 100;
underlineOffset = 3;
underlineOverprint = false;
underlineTint = 100;
underlineType = app.strokeStyles.item("Solid");
underlineWeight = .25
}
verticalScale = 100;
}
Fonts
The fonts collection of an InCopy application object contains all fonts accessible to InCopy. By contrast, the
fonts collection of a document contains only those fonts used in the document. The fonts collection of a
document also contains any missing fonts—fonts used in the document that are not accessible to InCopy.
The following script shows the difference between application fonts and document fonts (for the
complete script, see FontCollections):
Text and Type
Formatting text
46
//Shows the difference between the fonts collection of the application
//and the fonts collection of a document.
var myApplicationFonts = app.fonts;
var myDocument = app.documents.add();
var myStory = myDocument.stories.item(0);
var myDocumentFonts = myDocument.fonts;
var myFontNames = myApplicationFonts.everyItem().name;
if(myDocumentFonts.length > 0){
var myDocumentFontNames = myDocumentFonts.everyItem().name;
var myString = "Document Fonts:\r";
for(var myCounter = 0;myCounterfontStyle, where familyName is the name
of the font family, is a tab character, and fontStyle is the name of the font style. For example:
"Adobe Caslon ProSemibold Italic"
Applying a font
To apply a local font change to a range of text, use the appliedFont property, as shown in the following
script fragment (from the ApplyFont tutorial script):
//Given a font name "myFontName" and a text object "myText"
myText.appliedFont = app.fonts.item(myFontName);
You also can apply a font by specifying the font-family name and font style, as shown in the following
script fragment:
myText.appliedFont = app.fonts.item("Adobe Caslon Pro");
myText.fontStyle = "Semibold Italic";
Changing text properties
Text objects in InCopy have literally dozens of properties corresponding to their formatting attributes.
Even a single insertion point features properties that affect the formatting of text—up to and including
properties of the paragraph containing the insertion point. The SetTextProperties tutorial script shows
how to set every property of a text object. A fragment of the script follows:
Text and Type
Formatting text
//Shows how to set all read/write properties of a text object.
var myDocument = app.documents.add();
var myStory = myDocument.stories.item(0);
myStory.contents = "x";
var myTextObject = myStory.characters.item(0);
myTextObject.alignToBaseline = false;
myTextObject.appliedCharacterStyle = myDocument.characterStyles.item("[None]");
myTextObject.appliedFont = app.fonts.item("Minion ProRegular");
myTextObject.appliedLanguage = app.languagesWithVendors.item("English: USA");
myTextObject.appliedNumberingList = myDocument.numberingLists.item("[Default]");
myTextObject.appliedParagraphStyle = myDocument.paragraphStyles.item("[No Paragraph
Style]");
myTextObject.autoLeading = 120;
myTextObject.balanceRaggedLines = BalanceLinesStyle.noBalancing;
myTextObject.baselineShift = 0;
myTextObject.bulletsAlignment = ListAlignment.leftAlign;
myTextObject.bulletsAndNumberingListType = ListType.noList;
myTextObject.bulletsCharacterStyle = myDocument.characterStyles.item("[None]");
myTextObject.bulletsTextAfter = "^t";
myTextObject.capitalization = Capitalization.normal;
myTextObject.composer = "Adobe Paragraph Composer";
myTextObject.desiredGlyphScaling = 100;
myTextObject.desiredLetterSpacing = 0;
myTextObject.desiredWordSpacing = 100;
myTextObject.dropCapCharacters = 0;
myTextObject.dropCapLines = 0;
myTextObject.dropCapStyle = myDocument.characterStyles.item("[None]");
myTextObject.dropcapDetail = 0;
//More text properties in the tutorial script.
Changing text color
You can apply colors to the fill and stroke of text characters, as shown in the following script fragment
(from the TextColors tutorial script):
//Given two colors "myColorA" and "myColorB"...
var myStory = myDocument.stories.item(0);
//Enter text in the text frame.
myStory.contents = "Text\rColor"
var myText = myStory.paragraphs.item(0)
myText.pointSize = 72;
myText.justification = Justification.centerAlign;
//Apply a color to the fill of the text.
myText.fillColor = myColorA;
//Use the itemByRange method to apply the color to the stroke of the text.
myText.strokeColor = myColorB;
var myText = myStory.paragraphs.item(1)
myText.strokeWeight = 3;
myText.pointSize = 144;
myText.justification = Justification.centerAlign;
myText.fillColor = myColorB;
myText.strokeColor = myColorA;
myText.strokeWeight = 3;
47
Text and Type
Formatting text
48
Creating and applying styles
While you can use scripting to apply local formatting—as in some of the examples earlier in this
chapter—you probably will want to use character and paragraph styles to format your text. Using styles
creates a link between the formatted text and the style, which makes it easier to redefine the style, collect
the text formatted with a given style, or find and/or change the text. Paragraph and character styles are
key to text-formatting productivity and should be a central part of any script that applies text formatting.
The following script fragment shows how to create and apply paragraph and character styles (for the
complete script, see CreateStyles):
//Shows how to create and apply a paragraph style and a character style.
var myParagraphStyle, myCharacterStyle, myColor, myName;
//Create an example document.
var myDocument = app.documents.add();
//Create a color for use by one of the paragraph styles we'll create.
try{
myColor = myDocument.colors.item("Red");
//If the color does not exist, trying to get its name generates an error.
myName = myColor.name;
}
catch (myError){
//The color style did not exist, so create it.
myColor = myDocument.colors.add({name:"Red", model:ColorModel.process,
colorValue:[0, 100, 100, 0]});
}
var myStory = myDocument.stories.item(0);
//Fill the text frame with placeholder text.
myStory.textContainers[0].contents = "Normal text. Text with a character style applied
to it. More normal text.";
//Create a character style named "myCharacterStyle" if
//no style by that name already exists.
try{
myCharacterStyle = myDocument.characterStyles.item("myCharacterStyle");
//If the style does not exist, trying to get its name generates an error.
myName = myCharacterStyle.name;
}
catch (myError){
//The style did not exist, so create it.
myCharacterStyle = myDocument.characterStyles.add({name:"myCharacterStyle"});
}
//At this point, the variable myCharacterStyle contains a reference to a
//character-style object, which you can now use to specify formatting.
myCharacterStyle.fillColor = myColor;
//Create a paragraph style named "myParagraphStyle" if
//no style by that name already exists.
try{
myParagraphStyle = myDocument.paragraphStyles.item("myParagraphStyle");
Text and Type
Formatting text
49
//If the paragraph style does not exist, trying to get its name generates
//an error.
myName = myParagraphStyle.name;
}
catch (myError){
//The paragraph style did not exist, so create it.
myParagraphStyle = myDocument.paragraphStyles.add({name:"myParagraphStyle"});
}
//At this point, the variable myParagraphStyle contains a reference to a
//paragraph-style object, which you can now use to specify formatting.
myStory.texts.item(0).applyParagraphStyle(myParagraphStyle, true);
var myStartCharacter = myStory.characters.item(13);
var myEndCharacter = myStory.characters.item(54);
myStory.texts.itemByRange(myStartCharacter,
myEndCharacter).applyCharacterStyle(myCharacterStyle);
Why use the applyParagraphStyle method instead of setting the appliedParagraphStyle property of
the text object? The method gives the ability to override existing formatting; setting the property to a style
retains local formatting.
Why check for the existence of a style when creating a new document? It always is possible that the style
exists as an application default style. If it does, trying to create a new style with the same name results in an
error.
Nested styles apply character-style formatting to a paragraph according to a pattern. The following script
fragment shows how to create a paragraph style containing nested styles (for the complete script, see
NestedStyles):
//At this point, the variable myParagraphStyle contains a reference to a
//paragraph-style object, which you can now use to specify formatting.var myNestedStyle
= myParagraphStyle.nestedStyles.add({appliedCharacterStyle:myCharacterStyle,
delimiter:".", inclusive:true, repetition:1});
var myStartCharacter = myStory.characters.item(0);
var myEndCharacter = myStory.characters.item(-1);
//Use the itemByRange method to apply the paragraph to all text in the
//story. (Note the story object does not have the applyStyle method.)
myStory.texts.itemByRange(myStartCharacter,
myEndCharacter).applyParagraphStyle(myParagraphStyle, true);
Deleting a style
When you delete a style using the user interface, you can choose how you want to format any text tagged
with that style. InCopy scripting works the same way, as shown in the following script fragment (from the
RemoveStyle tutorial script):
//Remove the paragraph style myParagraphStyleA and replace with myParagraphStyleB.
myParagraphStyleA.remove(myDocument.paragraphStyles.item("myParagraphStyleB"));
Importing paragraph and character styles
You can import paragraph and character styles from other InCopy documents. The following script
fragment shows how (for the complete script, see ImportTextStyles):
Text and Type
Finding and changing text
50
//Import the styles from the saved document.
//importStyles parameters:
//Format as ImportFormat enumeration. Options for text styles are:
//
ImportFormat.paragraphStylesFormat
//
ImportFormat.characterStylesFormat
//
ImportFormat.textStylesFormat
//From as File
//GlobalStrategy as GlobalClashResolutionStrategy enumeration. Options are:
//
GlobalClashResolutionStrategy.doNotLoadTheStyle
//
GlobalClashResolutionStrategy.loadAllWithOverwrite
//
GlobalClashResolutionStrategy.loadAllWithRename
myDocument.importStyles(ImportFormat.textStylesFormat, File(myFilePath),
GlobalClashResolutionStrategy.loadAllWithOverwrite);
Finding and changing text
The find/change feature is one of the most powerful InCopy tools for working with text. It is fully
supported by scripting, and scripts can use find/change to go far beyond what can be done using the
InCopy user interface. InCopy has three ways of searching for text:
You can find text and text formatting and change it to other text and/or text formatting. This type of
find and change operation uses the findTextPreferences and changeTextPreferences objects to
specify parameters for the findText and changeText methods.
You can find text using regular expressions, or “grep.” This type of find and change operation uses the
findGrepPreferences and changeGrepPreferences objects to specify parameters for the findGrep
and changeGrep methods.
You can find specific glyphs (and their formatting) and replace them with other glyphs and formatting.
This type of find and change operation uses thefindGlyphPreferences and
changeGlyphPreferences objects to specify parameters for the findGlyph and changeGlyph
methods.
All find and change methods take a single optional parameter, reverseOrder, which specifies the order in
which the results of the search are returned. If you are processing the results of a find or change operation
in a way that adds or removes text from a story, you might face the problem of invalid text references, as
discussed in “Text objects and iteration” on page 42. In this case, you can either construct your loops to
iterate backward through the collection of returned text objects, or you can have the search operation
return the results in reverse order and then iterate through the collection normally.
Find/change preferences
Before searching for text, you probably will want to clear find and change preferences, to make sure the
settings from previous searches have no effect on your search. You also need to set a few find and change
preferences to specify the text, formatting, regular expression, or glyph you want to find and/or change. A
typical find/change operation involves the following steps:
1. Clear the find/change preferences. Depending on the type of find/change operation, this can take one
of the following three forms:
Text and Type
Finding and changing text
//find/change text preferences
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//find/change grep preferences
app.findGrepPreferences = NothingEnum.nothing;
app.changeGrepPreferences = NothingEnum.nothing;
//find/change glyph preferences
app.findGlyphPreferences = NothingEnum.nothing;
app.changeGlyphPreferences = NothingEnum.nothing;
2. Set up find/change parameters.
3. Execute the find/change operation.
4. Clear find/change preferences again.
Finding text
The following script fragment shows how to find a specified string of text. While the script fragment
searches the entire document, you also can search stories, text frames, paragraphs, text columns, or any
other text object. The findText method and its parameters are the same for all text objects. (For the
complete script, see FindText.)
//Clear the find/change preferences.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//Search the document for the string "Text".
app.findTextPreferences.findWhat = "text";
//Set the find options.
app.findChangeTextOptions.caseSensitive = false;
app.findChangeTextOptions.includeFootnotes = false;
app.findChangeTextOptions.includeHiddenLayers = false;
app.findChangeTextOptions.includeLockedLayersForFind = false;
app.findChangeTextOptions.includeLockedStoriesForFind = false;
app.findChangeTextOptions.includeMasterPages = false;
app.findChangeTextOptions.wholeWord = false;
var myFoundItems = app.documents.item(0).findText();
alert("Found " + myFoundItems.length + " instances of the search string.");
The following script fragment shows how to find a specified string of text and replace it with a different
string (for the complete script, see ChangeText):
51
Text and Type
Finding and changing text
//Clear the find/change preferences.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeTextOptions.caseSensitive = false;
app.findChangeTextOptions.includeFootnotes = false;
app.findChangeTextOptions.includeHiddenLayers = false;
app.findChangeTextOptions.includeLockedLayersForFind = false;
app.findChangeTextOptions.includeLockedStoriesForFind = false;
app.findChangeTextOptions.includeMasterPages = false;
app.findChangeTextOptions.wholeWord = false;
//Search the document for the string "copy" and change it to "text".
app.findTextPreferences.findWhat = "copy";
app.changeTextPreferences.changeTo = "text";
app.documents.item(0).changeText();
//Clear the find/change preferences after the search.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
Finding and changing formatting
To find and change text formatting, you set other properties of the findTextPreferences and
changeTextPreferences objects, as shown in the following script fragment (from the
FindChangeFormatting tutorial script):
//Clear the find/change preferences.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeTextOptions.caseSensitive = false;
app.findChangeTextOptions.includeFootnotes = false;
app.findChangeTextOptions.includeHiddenLayers = false;
app.findChangeTextOptions.includeLockedLayersForFind = false;
app.findChangeTextOptions.includeLockedStoriesForFind = false;
app.findChangeTextOptions.includeMasterPages = false;
app.findChangeTextOptions.wholeWord = false;
//Search the document for the 24 point text and change it to 10 point text.
app.findTextPreferences.pointSize = 24;
app.changeTextPreferences.pointSize = 10;
app.documents.item(0).changeText();
//Clear the find/change preferences after the search.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
You also can search for a string of text and apply formatting, as shown in the following script fragment
(from the FindChangeStringFormatting tutorial script):
52
Text and Type
Finding and changing text
53
//Clear the find/change preferences.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeTextOptions.caseSensitive = false;
app.findChangeTextOptions.includeFootnotes = false;
app.findChangeTextOptions.includeHiddenLayers = false;
app.findChangeTextOptions.includeLockedLayersForFind = false;
app.findChangeTextOptions.includeLockedStoriesForFind = false;
app.findChangeTextOptions.includeMasterPages = false;
app.findChangeTextOptions.wholeWord = false;
app.findTextPreferences.findWhat = "WIDGET^9^9^9^9";
//The following line will only work if your default font
//has a font style named "Bold" if not, change the text to
//a font style used by your default font.
app.changeTextPreferences.fontStyle = "Bold";
//Search the document. In this example, we'll use the
//InCopy search metacharacter "^9" to find any digit.
var myFoundItems = app.documents.item(0).changeText();
alert("Changed " + myFoundItems.length + " instances of the search string.");
//Clear the find/change preferences after the search.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
Using grep
InCopy supports regular expression find/change through the findGrep and changeGrep methods.
Regular-expression find and change also can find text with a specified format or replace text formatting
with formatting specified in the properties of the changeGrepPreferences object. The following script
fragment shows how to use these methods and the related preferences objects (for the complete script,
see FindGrep):
//Clear the find/change preferences.
app.findGrepPreferences = NothingEnum.nothing;
app.changeGrepPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeGrepOptions.includeFootnotes = false;
app.findChangeGrepOptions.includeHiddenLayers = false;
app.findChangeGrepOptions.includeLockedLayersForFind = false;
app.findChangeGrepOptions.includeLockedStoriesForFind = false;
app.findChangeGrepOptions.includeMasterPages = false;
//Regular expression for finding an email address.
app.findGrepPreferences.findWhat = "(?i)[A-Z]*?@[A-Z]*?[.]...";
//Apply the change to 24-point text only.
app.findGrepPreferences.pointSize = 24;
app.changeGrepPreferences.underline = true;
app.documents.item(0).changeGrep();
//Clear the find/change preferences after the search.
app.findGrepPreferences = NothingEnum.nothing;
app.changeGrepPreferences = NothingEnum.nothing;
NOTE: The findChangeGrepOptions object lacks two properties of the findChangeTextOptions object:
wholeWord and caseSensitive. This is because you can set these options using the regular expression
string itself. Use (?i) to turn case sensitivity on and (?-i) to turn case sensitivity off. Use \> to match the
beginning of a word and \< to match the end of a word, or use \b to match a word boundary.
One handy use for grep find/change is to convert text markup (that is, some form of tagging plain text
with formatting instructions) into InCopy formatted text. PageMaker paragraph tags (which are not the
Text and Type
Finding and changing text
54
same as PageMaker tagged text-format files) are an example of a simplified text-markup scheme. In a text
file marked up using this scheme, paragraph style names appear at the start of a paragraph, as shown in
these examples:
This is a heading.
This is body text.
We can create a script that uses grep find in conjunction with text find/change operations to apply
formatting to the text and remove the markup tags, as shown in the following script fragment (from the
ReadPMTags tutorial script):
function myReadPMTags(myStory){
var myName, myString, myStyle, myStyleName;
var myDocument = app.documents.item(0);
//Reset the findGrepPreferences to ensure that previous settings
//do not affect the search.
app.findGrepPreferences = NothingEnum.nothing;
app.changeGrepPreferences = NothingEnum.nothing;
//Find the tags (since this is a JavaScript string, backslashes must be escaped).
app.findGrepPreferences.findWhat = "(?i)^<\\s*\\w+\\s*>";
var myFoundItems = myStory.findGrep();
if(myFoundItems.length != 0){
var myFoundTags = new Array;
for(var myCounter = 0; myCounter 1){
for(var myCounter = 1; myCounter < myArray.length; myCounter ++){
if(myArray[myCounter] != myNewArray[myNewArray.length -1]){
myNewArray.push(myArray[myCounter]);
}
}
}
return myNewArray;
}
Using glyph search
You can find and change individual characters in a specific font using the findGlyph and changeGlyph
methods and the associated findGlyphPreferences and changeGlyphPreferences objects. The
following scripts fragment shows how to find and change a glyph in a sample document (for the complete
script, see FindChangeGlyphs):
//Clear glyph search preferences.
app.findGlyphPreferences = NothingEnum.nothing;
app.changeGlyphPreferences = NothingEnum.nothing;
var myDocument = app.documents.item(0);
//You must provide a font that is used in the document for the
//appliedFont property of the findGlyphPreferences object.
app.findGlyphPreferences.appliedFont = app.fonts.item("Minion ProRegular");
//Provide the glyph ID, not the glyph Unicode value.
app.findGlyphPreferences.glyphID = 500;
//The appliedFont of the changeGlyphPreferences object can be
//any font available to the application.
app.changeGlyphPreferences.appliedFont = app.fonts.item("Times New RomanRegular");
app.changeGlyphPreferences.glyphID = 374;
myDocument.changeGlyph();
//Clear glyph search preferences.
app.findGlyphPreferences = NothingEnum.nothing;
app.changeGlyphPreferences = NothingEnum.nothing;
Tables
Tables can be created from existing text using the convertTextToTable method, or an empty table can
be created at any insertion point in a story. The following script fragment shows three different ways to
create a table (for the complete script, see MakeTable):
Text and Type
Tables
56
var myStory = myDocument.stories.item(0);
var myStartCharacter = myStory.paragraphs.item(6).characters.item(0);
var myEndCharacter = myStory.paragraphs.item(6).characters.item(-2);
var myText = myStory.texts.itemByRange(myStartCharacter, myEndCharacter);
//The convertToTable method takes three parameters:
//[ColumnSeparator as string]
//[RowSeparator as string]
//[NumberOfColumns as integer] (only used if the ColumnSeparator
//and RowSeparator values are the same)
//In the last paragraph in the story, columns are separated by commas
//and rows are separated by semicolons, so we provide those characters
//to the method as parameters.
var myTable = myText.convertToTable(",",";");
var myStartCharacter = myStory.paragraphs.item(1).characters.item(0);
var myEndCharacter = myStory.paragraphs.item(4).characters.item(-2);
var myText = myStory.texts.itemByRange(myStartCharacter, myEndCharacter);
//In the second through the fifth paragraphs, colums are separated by
//tabs and rows are separated by returns. These are the default delimiter
//parameters, so we don't need to provide them to the method.
var myTable = myText.convertToTable();
//You can also explicitly add a table--you don't have to convert text to a table.
var myTable = myStory.insertionPoints.item(-1).tables.add();
myTable.columnCount = 3;
myTable.bodyRowCount = 3;
The following script fragment shows how to merge table cells (for the complete script, see
MergeTableCells):
var myDocument = app.documents.add();
var myStory = myDocument.stories.item(0);
var myString = "Table\r";
myStory.contents = myString;
var myTable = myStory.insertionPoints.item(-1).tables.add();
myTable.columnCount = 4;
myTable.bodyRowCount = 4;
//Merge all cells in the first column.
myTable.cells.item(0).merge(myTable.columns.item(0).cells.item(-1));
//Convert column 2 into 2 cells (rather than 4).
myTable.columns.item(1).cells.item(-1).merge(myTable.columns.item(1).cells.item(-2));
myTable.columns.item(1).cells.item(0).merge(myTable.columns.item(1).cells.item(1));
//Merge the last two cells in row 1.
myTable.rows.item(0).cells.item(-2).merge(myTable.rows.item(0).cells.item(-1));
//Merge the last two cells in row 3.
myTable.rows.item(2).cells.item(-2).merge(myTable.rows.item(2).cells.item(-1));
The following script fragment shows how to split table cells (for the complete script, see SplitTableCells):
myTable.cells.item(0).split(HorizontalOrVertical.horizontal);
myTable.columns.item(0).split(HorizontalOrVertical.vertical);
myTable.cells.item(0).split(HorizontalOrVertical.vertical);
myTable.rows.item(-1).split(HorizontalOrVertical.horizontal);
myTable.cells.item(-1).split(HorizontalOrVertical.vertical);
for(myRowCounter = 0; myRowCounter < myTable.rows.length; myRowCounter ++){
myRow = myTable.rows.item(myRowCounter);
for(myCellCounter = 0; myCellCounter < myRow.cells.length; myCellCounter ++){
myString = "Row: " + myRowCounter + " Cell: " + myCellCounter;
myRow.cells.item(myCellCounter).contents = myString;
}
}
Text and Type
Tables
57
The following script fragment shows how to create header and footer rows in a table (for the complete
script, see HeaderAndFooterRows):
var myTable = app.documents.item(0).stories.item(0).tables.item(0);
//Convert the first row to a header row.
myTable.rows.item(0).rowType = RowTypes.headerRow;
//Convert the last row to a footer row.
myTable.rows.item(-1).rowType = RowTypes.footerRow;
The following script fragment shows how to apply formatting to a table (for the complete script, see
TableFormatting):
var myTable = myDocument.stories.item(0).tables.item(0);
//Convert the first row to a header row.
myTable.rows.item(0).rowType = RowTypes.headerRow;
//Use a reference to a swatch, rather than to a color.
myTable.rows.item(0).fillColor = myDocument.swatches.item("DGC1_446b");
myTable.rows.item(0).fillTint = 40;
myTable.rows.item(1).fillColor = myDocument.swatches.item("DGC1_446a");
myTable.rows.item(1).fillTint = 40;
myTable.rows.item(2).fillColor = myDocument.swatches.item("DGC1_446a");
myTable.rows.item(2).fillTint = 20;
myTable.rows.item(3).fillColor = myDocument.swatches.item("DGC1_446a");
myTable.rows.item(3).fillTint = 40;
//Use everyItem to set the formatting of multiple cells at once.
myTable.cells.everyItem().topEdgeStrokeColor = myDocument.swatches.item("DGC1_446b");
myTable.cells.everyItem().topEdgeStrokeWeight = 1;
myTable.cells.everyItem().bottomEdgeStrokeColor =
myDocument.swatches.item("DGC1_446b");
myTable.cells.everyItem().bottomEdgeStrokeWeight = 1;
//When you set a cell stroke to a swatch, make certain you also set the
//stroke weight.
myTable.cells.everyItem().leftEdgeStrokeColor = myDocument.swatches.item("None");
myTable.cells.everyItem().leftEdgeStrokeWeight = 0;
myTable.cells.everyItem().rightEdgeStrokeColor = myDocument.swatches.item("None");
myTable.cells.everyItem().rightEdgeStrokeWeight = 0;
The following script fragment shows how to add alternating row formatting to a table (for the complete
script, see AlternatingRows):
//Given a table "myTable" containing at least four rows and a document
//"myDocument" containing the colors "DGC1_446a" and "DGC1_446b"...
//Convert the first row to a header row.
myTable.rows.item(0).rowType = RowTypes.headerRow;
//Applly alternating fills to the table.
myTable.alternatingFills = AlternatingFillsTypes.alternatingRows;
myTable.startRowFillColor = myDocument.swatches.item("DGC1_446a");
myTable.startRowFillTint = 60;
myTable.endRowFillColor = myDocument.swatches.item("DGC1_446b");
myTable.endRowFillTint = 50;
The following script fragment shows how to process the selection when text or table cells are selected. In
this example, the script displays an alert for each selection condition, but a real production script would
then do something with the selected item(s). (For the complete script, see TableSelection.)
Text and Type
Autocorrect
if(app.documents.length != 0){
if(app.selection.length != 0){
switch(app.selection[0].constructor.name){
//When a row, a column, or a range of cells is selected,
//the type returned is "Cell"
case "Cell":
alert("A cell is selected.");
break;
case "Table":
alert("A table is selected.");
break;
case "InsertionPoint":
case "Character":
case "Word":
case "TextStyleRange":
case "Line":
case "Paragraph":
case "TextColumn":
case "Text":
if(app.selection[0].parent.constructor.name == "Cell"){
alert("The selection is inside a table cell.");
}
else{
alert("The selection is not inside a table.");
}
break;
default:
alert("The selection is not inside a table.");
break;
}
}
}
Autocorrect
The autocorrect feature can correct text as you type. The following script shows how to use it (for the
complete script, see Autocorrect):
//The autocorrect preferences object turns the
//autocorrect feature on or off.
app.autoCorrectPreferences.autoCorrect = true;
app.autoCorrectPreferences.autoCorrectCapitalizationErrors = true;
//Add a word pair to the autocorrect list. Each AutoCorrectTable is linked
//to a specific language.
var myAutoCorrectTable = app.autoCorrectTables.item("English: USA");
//To safely add a word pair to the auto correct table, get the current
//word pair list, then add the new word pair to that array, and then
//set the autocorrect word pair list to the array.
var myWordPairList = myAutoCorrectTable.autoCorrectWordPairList;
//Add a new word pair to the array.
myWordPairList.push(["paragarph", "paragraph"]);
//Update the word pair list.
myAutoCorrectTable.autoCorrectWordPairList = myWordPairList;
//To clear all autocorrect word pairs in the current dictionary:
//myAutoCorrectTable.autoCorrectWordPairList = [[]];
58
Text and Type
Footnotes
Footnotes
The following script fragment shows how to add footnotes to a story (for the complete script, see
Footnotes):
var myWord, myFootnote;
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Add four footnotes at random locations in the story.
for(myCounter = 0; myCounter < 4; myCounter ++){
myWord = myStory.words.item(myGetRandom(0, myStory.words.length));
var myFootnote = myWord.insertionPoints.item(-1).footnotes.add();
//Note: when you create a footnote, it contains text--the footnote
//marker and the separator text (if any). If you try to set the text of
//the footnote by setting the footnote contents, you will delete the
//marker. Instead, append the footnote text, as shown below.
myFootnote.insertionPoints.item(-1).contents = "This is a footnote.";
//This function gets a random number in the range myStart to myEnd.
function myGetRandom(myStart, myEnd){
var myRange = myEnd - myStart;
return myStart + Math.floor(Math.random()*myRange);
}
59
5
User Interfaces
Chapter Update Status
CS6
Unchanged
JavaScript can create dialog boxes for simple yes/no questions and text entry, but you probably will need
to create more complex dialog boxes for your scripts. InCopy scripting can add dialog boxes and can
populate them with common user-interface controls, like pop-up lists, text-entry fields, and numeric-entry
fields. If you want your script to collect and act on information entered by you or any other user of your
script, use the dialog object.
This chapter shows how to work with InCopy dialog scripting. The sample scripts in this chapter are
presented in order of complexity, starting with very simple scripts and building toward more complex
operations.
NOTE: InCopy scripts written in JavaScript also can include user interfaces created using the Adobe ScriptUI
component. This chapter includes some ScriptUI scripting tutorials; for more information, see Adobe
Creative Suite® 3 JavaScript Tools Guide.
We assume that you have already read Chapter 2, “Getting Started” and know how to create, install, and
run a script.
Dialog-box overview
An InCopy dialog box is an object like any other InCopy scripting object. The dialog box can contain
several different types of elements (known collectively as “widgets”), as shown in the following figure:
dialog
dialog column
static text
border panel
checkbox control
radiobutton group
radiobutton control
measurement editbox
dropdown
60
User Interfaces
Your first InCopy dialog box
61
The items in the figure are defined in the following table:
Dialog-box element
InCopy name
Text-edit fields
Text editbox control
Numeric-entry fields
Real editbox, integer editbox, measurement
editbox, percent editbox, angle editbox
Pop-up menus
Drop-down control
Control that combines a text-edit field with a
pop-up menu
Combo-box control
Check box
Check-box control
Radio buttons
Radio-button control
The dialog object itself does not directly contain the controls; that is the purpose of the dialogColumn
object. dialogColumns give you a way to control the positioning of controls within a dialog box. Inside
dialogColumns, you can further subdivide the dialog box into other dialogColumns or borderPanels
(both of which can, if necessary, contain more dialogColumns and borderPanels).
Like any other InCopy scripting object, each part of a dialog box has its own properties. For example, a
checkboxControl has a property for its text (staticLabel) and another property for its state
(checkedState). The dropdown control has a property (stringList) for setting the list of options that
appears on the control’s menu.
To use a dialog box in your script, create the dialog object, populate it with various controls, display the
dialog box, and then gather values from the dialog-box controls to use in your script. Dialog boxes remain
in InCopy’s memory until they are destroyed. This means you can keep a dialog box in memory and have
data stored in its properties used by multiple scripts, but it also means the dialog boxes take up memory
and should be disposed of when they are not in use. In general, you should destroy a dialog-box object
before your script finishes executing.
Your first InCopy dialog box
The process of creating an InCopy dialog box is very simple: add a dialog box, add a dialog column to the
dialog box, and add controls to the dialog column. The following script demonstrates the process (for the
complete script, see SimpleDialog).
User Interfaces
Adding a user interface to “Hello World”
var myDialog = app.dialogs.add({name:"Simple Dialog"});
//Add a dialog column.
with(myDialog.dialogColumns.add()){
staticTexts.add({staticLabel:"This is a very simple dialog box."});
}
//Show the dialog box.
var myResult = myDialog.show();
//Display a message.
if(myResult == true){
alert("You clicked the OK button.");
}
else{
alert("You clicked the Cancel button.");
}
//Remove the dialog box from memory.
myDialog.destroy();
Adding a user interface to “Hello World”
In this example, we add a simple user interface to the Hello World tutorial script presented in Chapter 2,
“Getting Started.” The options in the dialog box provide a way for you to specify the sample text and
change the point size of the text. For the complete script, see HelloWorldUI.
var myDialog = app.dialogs.add({name:"Simple User Interface Example
Script",canCancel:true});
with(myDialog){
//Add a dialog column.
with(dialogColumns.add()){
//Create a text edit field.
var myTextEditField = textEditboxes.add({editContents:"Hello World!",
minWidth:180});
//Create a number (real) entry field.
var myPointSizeField = realEditboxes.add({editValue:72});
}
}
//Display the dialog box.
var myResult = myDialog.show();
if(myResult == true){
//Get the values from the dialog box controls.
var myString = myTextEditField.editContents;
var myPointSize = myPointSizeField.editValue;
//Remove the dialog box from memory.
myDialog.destroy();
//Create a new document.
var myDocument = app.documents.add()
with(myDocument){
var myStory = myDocument.stories.item(0);
//Enter the text from the dialog box.
myStory.contents=myString;
//Set the size of the text to the size you entered in the dialog box.
myStory.texts.item(0).pointSize = myPointSize;
}
}
else{
//User clicked Cancel, so remove the dialog box from memory.
myDialog.destroy();
}
62
User Interfaces
Creating a more complex user interface
Creating a more complex user interface
In the next example, we add more controls and different types of controls to the sample dialog box. The
example creates a dialog box that resembles the following:
For the complete script, see ComplexUI.
var myDialog = app.dialogs.add({name:"ComplexUI", canCancel:true});
with(myDialog){
var mySwatchNames = app.swatches.everyItem().name;
//Add a dialog column.
with(dialogColumns.add()){
//Create a border panel.
with(borderPanels.add()){
with(dialogColumns.add()){
with(dialogRows.add()){
//The following line shows how to set a property
//as you create an object.
staticTexts.add({staticLabel:"Message:"});
//The following line shows how to set multiple
//properties as you create an object.
var myTextEditField = textEditboxes.add(
{editContents:"Hello World!", minWidth:180});
}
}
}
//Create another border panel.
with(borderPanels.add()){
with(dialogColumns.add()){
with(dialogRows.add()){
staticTexts.add({staticLabel:"Point Size:"});
//Create a number entry field. Note that this field uses
//editValue rather than editText (as a textEditBox would).
var myPointSizeField = measurementEditboxes.add({editValue:72,
editUnits:MeasurementUnits.points});
}
}
}
//Create another border panel.
with(borderPanels.add()){
with(dialogColumns.add()){
with(dialogRows.add()){
staticTexts.add({staticLabel:"Paragraph Alignment:"});
var myRadioButtonGroup = radiobuttonGroups.add();
with(myRadioButtonGroup){
radiobuttonControls.add({staticLabel:"Left",
checkedState:true});
63
User Interfaces
Creating a more complex user interface
radiobuttonControls.add({staticLabel:"Center"});
radiobuttonControls.add({staticLabel:"Right"});
}
}
}
}
//Create another border panel.
with(borderPanels.add()){
with(dialogColumns.add()){
with(dialogRows.add()){
staticTexts.add({staticLabel:"Text Color:"});
}
var mySwatchDropdown = dropdowns.add({stringList:mySwatchNames,
selectedIndex:4});
}
}
}
}
//Display the dialog box.
if(myDialog.show() == true){
var myParagraphAlignment, myString, myPointSize, myVerticalJustification;
//If the user didn't click the Cancel button,
//then get the values back from the dialog box.
//Get the example text from the text edit field.
var myString = myTextEditField.editContents
//Get the point size from the point size field.
var myPointSize = myPointSizeField.editValue;
//Get the paragraph alignment setting from the radiobutton group.
if(myRadioButtonGroup.selectedButton == 0){
myParagraphAlignment = Justification.leftAlign;
}
else if(myRadioButtonGroup.selectedButton == 1){
myParagraphAlignment = Justification.centerAlign;
}
else{
myParagraphAlignment = Justification.rightAlign;
}
var mySwatchName = mySwatchNames[mySwatchDropdown.selectedIndex];
//Remove the dialog box from memory.
myDialog.destroy();
//Now create the document and apply the properties to the text.
var myDocument = app.documents.add();
with(myDocument.stories.item(0)){
//Set the contents of the story to the string you entered
//in the dialog box.
contents = myString;
//Set the alignment of the paragraph.
texts.item(0).justification = myParagraphAlignment;
//Set the point size of the text.
texts.item(0).pointSize = myPointSize;
//Set the fill color of the text.
texts.item(0).fillColor = myDocument.swatches.item(mySwatchName);
}
}
else{
myDialog.destroy()
}
64
User Interfaces
Working with ScriptUI
65
Working with ScriptUI
JavaScripts can make, create, and define user-interface elements using an Adobe scripting component
named ScriptUI. ScriptUI gives script writers a way to create floating palettes, progress bars, and interactive
dialog boxes that are far more complex than InCopy’s built-in dialog object.
This does not mean, however, that user-interface elements written using Script UI are not accessible to
users. InCopy scripts can execute scripts written in other scripting languages using the method.
Creating a progress bar with ScriptUI
The following sample script shows how to create a progress bar using JavaScript and ScriptUI, then how to
use the progress bar from an (for the complete script, see ProgressBar):
#targetengine "session"
var myProgressPanel;
var myMaximumValue = 300;
var myProgressBarWidth = 300;
var myIncrement = myMaximumValue/myProgressBarWidth;
myCreateProgressPanel(myMaximumValue, myProgressBarWidth);
function myCreateProgressPanel(myMaximumValue, myProgressBarWidth){
myProgressPanel = new Window('window', 'Progress');
with(myProgressPanel){
myProgressPanel.myProgressBar = add('progressbar', [12, 12, myProgressBarWidth,
24], 0, myMaximumValue);
}
}
The following script fragment shows how to call the progress bar created in the preceding script using a
separate JavaScript (for the complete script, see CallProgressBar):
#targetengine "session"
myCreateProgressPanel(20, 400);
myProgressPanel.show();
var myStory = app.documents.item(0).stories.item(0);
for(var myCounter = 0; myCounter < 20; myCounter ++){
//Scale the value change to the maximum value of the progress bar.
myProgressPanel.myProgressBar.value = myCounter/myIncrement;
var myInsertionPoint = myStory.insertionPoints.item(-1);
myInsertionPoint.contents = "This is a paragraph\r.";
}
myProgressPanel.myProgressBar.value = 0;
myProgressPanel.hide();
Creating a button-bar panel with ScriptUI
If you want to run your scripts by clicking buttons in a floating palette, you can create one using JavaScript
and ScriptUI. It does not matter which scripting language the scripts themselves use.
The following tutorial script shows how to create a simple floating panel. The panel can contain a series of
buttons, with each button being associated with a script stored on disk. Click the button, and the panel
runs the script (the script, in turn, can display dialog boxes or other user-interface elements). The button in
the panel can contain text or graphics. (For the complete script, see ButtonBar.)
The tutorial script reads an XML file in the following form:
User Interfaces
Working with ScriptUI
...
For example:
The following functions read the XML file and set up the button bar:
#targetengine "session"
var myButtonBar;
main();
function main(){
myButtonBar = myCreateButtonBar();
myButtonBar.show();
}
function myCreateButtonBar(){
var myButtonName, myButtonFileName, myButtonType, myButtonIconFile, myButton;
var myButtons = myReadXMLPreferences();
if(myButtons != ""){
myButtonBar = new Window('window', 'Script Buttons', undefined,
{maximizeButton:false, minimizeButton:false});
with(myButtonBar){
spacing = 0;
margins = [0,0,0,0];
with(add('group')){
spacing = 2;
orientation = 'row';
for(var myCounter = 0; myCounter < myButtons.length(); myCounter++){
myButtonName = myButtons[myCounter].xpath("buttonName");
myButtonType = myButtons[myCounter].xpath("buttonType");
myButtonFileName = myButtons[myCounter].xpath("buttonFileName");
myButtonIconFile = myButtons[myCounter].xpath("buttonIconFile");
if(myButtonType == "text"){
myButton = add('button', undefined, myButtonName);
}
else{
myButton = add('iconbutton', undefined,
File(myButtonIconFile));
}
myButton.scriptFile = myButtonFileName;
66
User Interfaces
Working with ScriptUI
myButton.onClick = function(){
myButtonFile = File(this.scriptFile)
app.doScript(myButtonFile);
}
}
}
}
}
return myButtonBar;
}
function myReadXMLPreferences(){
myXMLFile = File.openDialog("Choose the file containing your
button bar defaults");
var myResult = myXMLFile.open("r", undefined, undefined);
var myButtons = "";
if(myResult == true){
var myXMLDefaults = myXMLFile.read();
myXMLFile.close();
var myXMLDefaults = new XML(myXMLDefaults);
var myButtons = myXMLDefaults.xpath("/buttons/button");
}
return myButtons;
}
67
6
Menus
Chapter Update Status
CS6
Unchanged
InCopy scripting can add menu items, remove menu items, perform any menu command, and attach
scripts to menu items.
This chapter shows how to work with InCopy menu scripting. The sample scripts in this chapter are
presented in order of complexity, starting with very simple scripts and building toward more complex
operations.
We assume that you have read Chapter 2, “Getting Started” and know how to create, install, and run a
script.
Understanding the menu model
The InCopy menu-scripting model is made up of a series of objects that correspond to the menus you see
in the application’s user interface, including menus associated with panels as well as those displayed on
the main menu bar. A menu object contains the following objects:
menuItems — The menu options shown on a menu. This does not include submenus.
menuSeparators — Lines used to separate menu options on a menu.
submenus — Menu options that contain further menu choices.
menuElements — All menuItems, menuSeparators and submenus shown on a menu.
eventListeners — These respond to user (or script) actions related to a menu.
events — The events triggered by a menu.
Every menuItem is connected to a menuAction through the associatedMenuAction property. The
properties of the menuAction define what happens when the menu item is chosen. In addition to the
menuActions defined by the user interface, InCopy scripters can create their own, scriptMenuActions,
which associate a script with a menu selection.
A menuAction or scriptMenuAction can be connected to zero, one, or more menuItems.
The following diagram shows how the different menu objects relate to each other:
68
Menus
Understanding the menu model
69
application
menuActions
menuAction
area
checked
enabled
eventListeners
eventListener
id
eventListener
index
...
label
name
events
event
parent
event
title
...
scriptMenuActions
scriptMenuAction
same as menuAction
To create a list (as a text file) of all visible menu actions, run the following script fragment (from the
GetMenuActions tutorial script):
var myMenuActionNames = app.menuActions.everyItem().name;
//Open a new text file.
var myTextFile = File.saveDialog("Save Menu Action Names As", undefined);
//If the user clicked the Cancel button, the result is null.
if(myTextFile != null){
//Open the file with write access.
myTextFile.open("w");
for(var myCounter = 0; myCounter < myMenuActionNames.length; myCounter++){
myTextFile.writeln(myMenuActionNames[myCounter]);
}
myTextFile.close();
}
To create a list (as a text file) of all available menus, run the following script fragment (for the complete
script listing, refer to the GetMenuNames tutorial script). Note that these scripts can be very slow, as there
are a large number of menu names in InCopy.
Menus
Understanding the menu model
70
var myMenu;
//Open a new text file.
var myTextFile = File.saveDialog("Save Menu Action Names As", undefined);
//If the user clicked the Cancel button, the result is null.
if(myTextFile != null){
//Open the file with write access.
myTextFile.open("w");
for(var myMenuCounter = 0;myMenuCounter< app.menus.length; myMenuCounter++){
myMenu = app.menus.item(myMenuCounter);
myTextFile.writeln(myMenu.name);
myProcessMenu(myMenu, myTextFile);
}
myTextFile.close();
alert("done!");
}
function myProcessMenu(myMenu, myTextFile){
var myMenuElement;
var myIndent = myGetIndent(myMenu);
for(var myCounter = 0; myCounter < myMenu.menuElements.length; myCounter++){
myMenuElement = myMenu.menuElements.item(myCounter);
if(myMenuElement.getElements()[0].constructor.name != "MenuSeparator"){
myTextFile.writeln(myIndent + myMenuElement.name);
if(myMenuElement.getElements()[0].constructor.name == "Submenu"){
if(myMenuElement.menuElements.length > 0){
myProcessMenu(myMenuElement, myTextFile);
}
}
}
}
}
function myGetIndent(myObject){
var myString = "\t";
var myDone = false;
do{
if((myObject.parent.constructor.name == "Menu")||
(myObject.parent.constructor.name == "Application")){
myDone = true;
}
else{
myString = myString + "\t";
myObject = myObject.parent;
}
}while(myDone == false)
return myString;
}
Localization and menu names
in InCopy scripting, menuItems, menus, menuActions,and submenus are all referred to by name. Because of
this, scripts need a method of locating these objects that is independent of the installed locale of the
application. To do this, you can use an internal database of strings that refer to a specific item, regardless of
the locale. For example, to get the locale-independent name of a menu action, you can use the following
script fragment (for the complete script, see GetKeyStrings):
Menus
Running a menu action from a script
71
var myString = "";
var myMenuAction = app.menuActions.item("$ID/Convert to Note");
var myKeyStrings = app.findKeyStrings(myMenuAction.name);
if(myKeyStrings.constructor.name == "Array"){
for(var myCounter = 0; myCounter < myKeyStrings.length; myCounter ++){
myString += myKeyStrings[myCounter] + "\r";
}
}
else{
myString = myKeyStrings;
}
alert(myString);
NOTE: It is much better to get the locale-independent name of a menuAction than of a menu, menuItem, or
submenu, because the title of a menuAction is more likely to be a single string. Many of the other menu
objects return multiple strings when you use the getKeyStrings method.
Once you have the locale-independent string you want to use, you can include it in your scripts. Scripts
that use these strings will function properly in locales other than that of your version of InCopy.
To translate a locale-independent string into the current locale, use the following script fragment (from the
TranslateKeyString tutorial script):
var myString = app.translateKeyString("$ID/Convert to Note");
alert(myString);
Running a menu action from a script
Any of InCopy’s built-in menuActions can be run from a script. The menuAction does not need to be
attached to a menuItem; however, in every other way, running a menuItem from a script is exactly the same
as choosing a menu option in the user interface. If selecting the menu option displays a dialog box,
running the corresponding menuAction from a script also displays a dialog box.
The following script shows how to run a menuAction from a script (for the complete script, see
InvokeMenuAction):
//Get a reference to a menu action.
var myMenuAction = app.menuActions.item("$ID/Convert to Note");
//Run the menu action. This example action will fail if you do not
//have text selected.
myMenuAction.invoke();
NOTE: In general, you should not try to automate InCopy processes by scripting menu actions and
user-interface selections; InCopy’s scripting object model provides a much more robust and powerful way
to work. Menu actions depend on a variety of user-interface conditions, like the selection and the state of
the window. Scripts using the object model work with the objects in an InCopy document directly, which
means they do not depend on the user interface; this, in turn, makes them faster and more consistent.
Adding menus and menu items
Scripts also can create new menus and menu items or remove menus and menu items, just as you can in
the InCopy user interface. The following sample script shows how to duplicate the contents of a submenu
to a new menu in another menu location (for the complete script, see CustomizeMenu):
Menus
Menus and events
72
var myMainMenu = app.menus.item("Main");
var myTypeMenu = myMainMenu.menuElements.item("Type");
var myFontMenu = myTypeMenu.menuElements.item("Font");
var myKozukaMenu = myFontMenu.submenus.item("Kozuka Mincho Pro ");
var mySpecialFontMenu = myMainMenu.submenus.add("Kozuka Mincho Pro");
for(myCounter = 0;myCounter < myKozukaMenu.menuItems.length; myCounter++){
var myAssociatedMenuAction =
myKozukaMenu.menuItems.item(myCounter).associatedMenuAction;
mySpecialFontMenu.menuItems.add(myAssociatedMenuAction);
}
To remove the custom menu added by the preceding script, run the RemoveSpecialFontMenu script.
var myMainMenu = app.menus.item("Main");
var mySpecialFontMenu = myMainMenu.submenus.item("Kozuka Mincho Pro");
mySpecialFontMenu.remove();
Menus and events
Menus and submenus generate events as they are chosen in the user interface, and menuActions and
scriptMenuActions generate events as they are used. Scripts can install eventListeners to respond to
these events. The following table shows the events for the different menu scripting components:
Object
Event
Description
menu
beforeDisplay
Runs the attached script before the contents of the menu is
shown.
menuAction
afterInvoke
Runs the attached script when the associated menuItem is
selected, but after the onInvoke event.
beforeInvoke
Runs the attached script when the associated menuItem is
selected, but before the onInvoke event.
afterInvoke
Runs the attached script when the associated menuItem is
selected, but after the onInvoke event.
beforeInvoke
Runs the attached script when the associated menuItem is
selected, but before the onInvoke event.
beforeDisplay
Runs the attached script before an internal request for the
enabled/checked status of the
scriptMenuActionscriptMenuAction.
onInvoke
Runs the attached script when the scriptMenuAction is
invoked.
beforeDisplay
Runs the attached script before the contents of the submenu
are shown.
scriptMenuAction
submenu
For more about events and eventListeners, see Chapter 7, “Events."
To change the items displayed in a menu, add an eventListener for the beforeDisplay event. When the
menu is selected, the eventListener can then run a script that enables or disables menu items, changes
the wording of menu item, or performs other tasks related to the menu. This mechanism is used internally
to change the menu listing of available fonts, recent documents, or open windows.
Menus
Working with script menu actions
73
Working with script menu actions
You can use scriptMenuAction to create a new menuAction whose behavior is implemented through the
script registered to run when the onInvoke event is triggered.
The following script shows how to create a scriptMenuAction and attach it to a menu item (for the
complete script, see MakeScriptMenuAction). This script simply displays an alert when the menu item is
selected.
var mySampleScriptAction = app.scriptMenuActions.add("Display Message");
var myEventListener = mySampleScriptAction.eventListeners.add("onInvoke",
function(){alert("This menu item was added by a script.");});
//If the submenu "Script Menu Action" does not already exist, create it.
try{
var mySampleScriptMenu = app.menus.item("$ID/Main").submenus.item(
"Script Menu Action");
mySampleScriptMenu.title;
}
catch (myError){
var mySampleScriptMenu = app.menus.item("$ID/Main").submenus.add
("Script Menu Action");
}
var mySampleScriptMenuItem = mySampleScriptMenu.menuItems.add(mySampleScriptAction);
To remove the menu, submenu, menuItem, and scriptMenuAction created by the preceding script, run the
following script fragment (from the RemoveScriptMenuAction tutorial script):
#targetengine "session"
var mySampleScriptAction = app.scriptMenuActions.item("Display Message");
mySampleScriptAction.remove();
var mySampleScriptMenu = app.menus.item("$ID/Main").submenus.item
("Script Menu Action");
mySampleScriptMenu.remove();
You also can remove all scriptMenuAction, as shown in the following script fragment (from the
RemoveAllScriptMenuActions tutorial script). This script also removes the menu listings of the
scriptMenuAction, but it does not delete any menus or submenus you might have created.
#targetengine "session"
app.scriptMenuActions.everyItem().remove();
You can create a list of all current scriptMenuActions, as shown in the following script fragment (from
the GetScriptMenuActions tutorial script):
var myScriptMenuActionNames = app.scriptMenuActions.everyItem().name;
//Open a new text file.
var myTextFile = File.saveDialog("Save Script Menu Action Names As", undefined);
//If the user clicked the Cancel button, the result is null.
if(myTextFile != null){
//Open the file with write access.
myTextFile.open("w");
for(var myCounter = 0; myCounter < myScriptMenuActionNames.length; myCounter++){
myTextFile.writeln(myScriptMenuActionNames[myCounter]);
}
myTextFile.close();
}
scriptMenuAction also can run scripts during their beforeDisplay event, in which case they are
executed before an internal request for the state of the scriptMenuAction (for example, when the menu
Menus
Working with script menu actions
74
item is about to be displayed). Among other things, the script can then change the menu names and/or
set the enabled/checked status.
In the following sample script, we add an eventListener to the beforeDisplay event that checks the
current selection. If there is no selection, the script in the eventListener disables the menu item. If an
item is selected, the menu item is enabled, and choosing the menu item displays the type of the first item
in the selection. (For the complete script, see BeforeDisplay.)
var mySampleScriptAction = app.scriptMenuActions.add("Display Message");
var myEventListener = mySampleScriptAction.eventListeners.add("onInvoke",
myOnInvokeHandler, false);
var mySampleScriptMenu = app.menus.item("$ID/Main").submenus.add("Script Menu
Action");
var mySampleScriptMenuItem = mySampleScriptMenu.menuItems.add(mySampleScriptAction);
mySampleScriptMenu.eventListeners.add("beforeDisplay", myBeforeDisplayHandler,
false);
//JavaScript function to run before the menu item is drawn.
function myBeforeDisplayHandler(myEvent){
var mySampleScriptAction = app.scriptMenuActions.item("Display Message");
if(app.documents.length > 0){
if(app.selection.length > 0){
mySampleScriptAction.enabled = true;
}
else{
mySampleScriptAction.enabled = false;
}
}
else{
mySampleScriptAction.enabled = false;
}
}
//JavaScript function to run when the menu item is selected.
function myOnInvokeHandler(myEvent){
myString = app.selection[0].constructor.name;
alert("The first item in the selection is a " + myString + ".");
}
7
Events
Chapter Update Status
CS6
Unchanged
InCopy scripting can respond to common application and document events, like opening a file, creating a
new file, printing, and importing text and graphic files from disk. In InCopy scripting, the event object
responds to an event that occurs in the application. Scripts can be attached to events using the
eventListener scripting object. Scripts that use events are the same as other scripts—the only difference
is that they run automatically, as the corresponding event occurs, rather than being run by the user (from
the Scripts palette).
This chapter shows how to work with InCopy event scripting. The sample scripts in this chapter are
presented in order of complexity, starting with very simple scripts and building toward more complex
operations.
We assume that you have already read Chapter 2, “Getting Started” and know how to create, install, and
run a script.
This chapter covers application and document events. For a discussion of events related to menus, see
Chapter 6, “Menus.”
The InCopy event scripting model is similar to the Worldwide Web Consortium (W3C) recommendation for
Document Object Model Events. For more information, see http://www.w3c.org.
Understanding the event scripting model
The InCopy event scripting model is made up of a series of objects that correspond to the events that
occur as you work with the application. The first object is the event, which corresponds to one of a limited
series of actions in the InCopy user interface (or corresponding actions triggered by scripts).
To respond to an event, you register an eventListener with an object capable of receiving the event.
When the specified event reaches the object, the eventListener executes the script function defined in
its handler function (which can be either a script function or a reference to a script file on disk).
The following table shows a list of events to which eventListeners can respond. These events can be
triggered by any available means, including menu selections, keyboard shortcuts, or script actions.
75
Events
Understanding the event scripting model
User-Interface
event
Event name
Description
Object type
Any menu
action
beforeDisplay
Appears before the menu or
submenu is displayed.
Event
beforeDisplay
Appears before the script menu
action is displayed or changed.
Event
beforeInvoke
Appears after the menu action is
chosen but before the content of the
menu action is executed.
Event
afterInvoke
Appears after the menu action is
executed.
Event
onInvoke
Executes the menu action or script
menu action.
Event
beforeClose
Appears after a close document
request is made but before the
document is closed.
DocumentEvent
afterClose
Appears after a document is closed.
DocumentEvent
beforeExport
Appears after an export request is
made but before the document or
page item is exported.
ImportExportEvent
afterExport
Appears after a document or page
item is exported.
ImportExportEvent
beforeImport
Appears before a file is imported but
before the incoming file is imported
into a document (before place).
ImportExportEvent
afterImport
Appears after a file is imported but
before the file is placed on a page.
ImportExportEvent
beforeNew
Appears after a new document
request but before the document is
created.
DocumentEvent
afterNew
Appears after a new document is
created.
DocumentEvent
beforeOpen
Appears after an open document
request but before the document is
opened.
DocumentEvent
afterOpen
Appears after a document is opened.
DocumentEvent
beforePrint
Appears after a print document
request is made but before the
document is printed.
DocumentEvent
afterPrint
Appears after a document is printed.
DocumentEvent
Close
Export
Import
New
Open
Print
76
Events
Understanding the event scripting model
User-Interface
event
Event name
Revert
Save
Save A Copy
Save As
Description
Object type
beforeRevert
Appears after a document revert
request is made but before the
document is reverted to an earlier
saved state.
DocumentEvent
afterRevert
Appears after a document is reverted
to an earlier saved state.
DocumentEvent
beforeSave
Appears after a save document
request is made but before the
document is saved.
DocumentEvent
afterSave
Appears after a document is saved.
DocumentEvent
beforeSaveACopy
Appears after a document
save-a-copy-as request is made but
before the document is saved.
DocumentEvent
afterSaveACopy
Appears after a document is saved.
DocumentEvent
beforeSaveAs
Appears after a document save-as
request is made but before the
document is saved.
DocumentEvent
afterSaveAs
Appears after a document is saved.
DocumentEvent
77
About event properties and event propagation
When an action—whether initiated by a user or by a script—triggers an event, the event can spread, or
propagate, through the scripting objects capable of responding to the event. When an event reaches an
object that has an eventListener registered for that event, the eventListener is triggered by the event.
An event can be handled by more than one object as it propagates.
There are three types of event propagation:
None — Only the eventListeners registered to the event target are triggered by the event. The
beforeDisplay event is an example of an event that does not propagate.
Capturing — The event starts at the top of the scripting object model—the application—then
propagates through the model to the target of the event. Any eventListeners capable of
responding to the event registered to objects above the target will process the event.
Bubbling — The event starts propagation at its target and triggers any qualifying eventListeners
registered to the target. The event then proceeds upward through the scripting object model,
triggering any qualifying eventListeners registered to objects above the target in the scripting
object model hierarchy.
The following table provides more detail on the properties of an event and the ways in which they relate
to event propagation through the scripting object model.
Events
Working with eventListeners
Property
Description
Bubbles
If true, the event propagates to scripting objects above the object initiating
the event.
Cancelable
If true, the default behavior of the event on its target can be canceled. To do
this, use the PreventDefault method.
Captures
If true, the event may be handled by eventListeners registered to scripting
objects above the target object of the event during the capturing phase of
event propagation. This means an eventListener on the application, for
example, can respond to a document event before an eventListener is
triggered.
CurrentTarget
The current scripting object processing the event. See target in this table.
DefaultPrevented
If true, the default behavior of the event on the current target (see target in
this table) was prevented, thereby cancelling the action.
EventPhase
The current stage of the event propagation process.
EventType
The type of the event, as a string (for example, "beforeNew").
PropagationStopped
If true, the event has stopped propagating beyond the current target (see
target in this table). To stop event propagation, use the stopPropagation
78
method.
Target
The object from which the event originates. For example, the target of a
beforeImport event is a document; of a beforeNew event, the application.
TimeStamp
The time and date the event occurred.
Working with eventListeners
When you create an eventListener, you specify the event type (as a string) the event handler (as a
JavaScript function or file reference), and whether the eventListener can be triggered in the capturing
phase of the event. The following script fragment shows how to add an eventListener for a specific
event (for the complete script, see AddEventListener).
#targetengine "session"
main();
function main(){
var myEventListener = app.addEventListener("afterNew", myDisplayEventType,
false);
}
function myDisplayEventType(myEvent){
alert("This event is the " + myEvent.eventType + " event.");
}
To remove the eventListener created by the above script, run the following script (from the
RemoveEventListener tutorial script):
app.removeEventListener("afterNew", myDisplayEventType, false);
When an eventListener responds an event, the event may still be processed by other eventListeners
that might be monitoring the event (depending on the propagation of the event). For example, the
Events
Working with eventListeners
79
afterOpen event can be observed by eventListeners associated with both the application and the
document.
eventListeners do not persist beyond the current InCopy session. To make an eventListener available
in every InCopy session, add the script to the startup scripts folder (for more on installing scripts, see
Chapter 2, “Getting Started.”). When you add an eventListener script to a document, it is not saved with
the document or exported to INX.
NOTE: If you are having trouble with a script that defines an eventListener, you can either run a script
that removes the eventListener or quit and restart InCopy.
eventListeners that use handler functions defined inside the script (rather than in an external file) must
use #targetengine "session". If the script is run using #targetengine "main" (the default), the
function is not available when the event occurs, and the script generates an error.
An event can trigger multiple eventListeners as it propagates through the scripting object model. The
following sample script demonstrates an event triggering eventListeners registered to different objects
(for the full script, see MultipleEventListeners):
#targetengine "session"
main();
function main(){
var myApplicationEventListener = app.eventListeners.add("beforeImport",
myEventInfo, false);
var myDocumentEventListener = app.documents.item(0).eventListeners.add
("beforeImport", myEventInfo, false);
}
function myEventInfo(myEvent){
var myString = "Current Target: " + myEvent.currentTarget.name;
alert(myString);
}
When you run the preceding script and place a file, InCopy displays alerts showing, in sequence, the name
of the document, then the name of the application.
The following sample script creates an eventListener for each supported event and displays information
about the event in a simple dialog box. For the complete script, see EventListenersOn.
main()
function main(){
app.scriptPreferences.version = 5.0;
var myEventNames = [
"beforeQuit", "afterQuit",
"beforeNew", "afterNew",
"beforeOpen", "afterOpen",
"beforeClose", "afterClose",
"beforeSave", "afterSave",
"beforeSaveAs", "afterSaveAs",
"beforeSaveACopy", "afterSaveACopy",
"beforeRevert", "afterRevert",
"beforePrint", "afterPrint",
"beforeExport", "afterExport",
"beforeImport", "afterImport"
] ;
for (var myCounter = 0; myCounter < myEventNames.length; myCounter ++){
app.addEventListener(myEventNames[myCounter], myEventInfo, false);
}
}
function myEventInfo(myEvent){
Events
A sample “afterNew” eventListener
80
var myString = "Handling Event: " +myEvent.eventType;
myString += "\r\rTarget: " + myEvent.target + " " +myEvent.target.name;
myString += "\rCurrent: " +myEvent.currentTarget + " "
myStirng += myEvent.currentTarget.name;
myString += "\r\rPhase: " + myGetPhaseName(myEvent.eventPhase );
myString += "\rCaptures: " +myEvent.captures;
myString += "\rBubbles: " + myEvent.bubbles;
myString += "\r\rCancelable: " +myEvent.cancelable;
myString += "\rStopped: " +myEvent.propagationStopped;
myString += "\rCanceled: " +myEvent.defaultPrevented;
myString += "\r\rTime: " +myEvent.timeStamp;
alert(myString);
function myGetPhaseName(myPhase){
switch(myPhase){
case EventPhases.atTarget:
myPhaseName = "At Target";
break;
case EventPhases.bubblingPhase:
myPhaseName = "Bubbling";
break;
case EventPhases.capturingPhase:
myPhaseName = "Capturing";
break;
case EventPhases.done:
myPhaseName = "Done";
break;
case EventPhases.notDispatching:
myPhaseName = "Not Dispatching";
break;
}
return myPhaseName;
}
}
The following sample script shows how to turn off all eventListeners for the application object. For the
complete script, see EventListenersOff.
//EventListenersOff.jsx
//An InCopy CS6 JavaScript
#targetengine "session"
app.eventListeners.everyItem().remove();
A sample “afterNew” eventListener
The afterNew event provides a convenient place to add information to the document, like user name,
document creation date, copyright information, and other job-tracking information. The following sample
script shows how to add this sort of information to document metadata (also known as file info or XMP
information). For the complete script listing, refer to the AfterNew tutorial script.
Events
A sample “afterNew” eventListener
#targetengine "session"
//Creates an event listener that will run after a new document is created.
main();
function main(){
var myEventListener = app.eventListeners.add("afterNew",
myAfterNewHandler, false);
}
function myAfterNewHandler(myEvent){
var myDocument = myEvent.parent;
main(myDocument);
function main(myDocument){
app.userName = "Adobe";
myAddXMPData(myDocument);
}
function myAddXMPData(myDocument){
with(myDocument.metadataPreferences){
author = "Adobe Systems";
description = "This is a sample document with XMP metadata. Created:"
+ myEvent.timeStamp + "\rby: " + app.userName;
}
}
}
81
8
Notes
Chapter Update Status
CS6
Unchanged
With the InDesign and InCopy inline editorial-notes features, you can add comments and annotations as
notes directly to text without affecting the flow of a story. Notes features are designed to be used in a
workgroup environment. Notes can be color coded or turned on or off based on certain criteria.
Notes can be created using the Note tool in the toolbox, the Notes > New Note command, or the New
Note icon on the Notes palette.
We assume that you have already read Chapter 2, “Getting Started” and know how to create, install, and
run a script. We also assume you have some knowledge of working with notes in InCopy.
Entering and importing a note
This section covers the process of getting a note into your InCopy document. Just as you can create a note
and replace the text of the note using the InCopy user interface, you can create notes and insert text into a
note using scripting.
Adding a note to a story
To add note to a story, use the add method. The following sample adds a note at the last insertion point.
For the complete script, see InsertNote.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Add note to a default story. We'll use the last insertion point in the story.
var myNote = myStory.insertionPoints.item(-1).notes.add();
//Add text to the note
myNote.texts.item(0).contents = "This is a note."
Replacing text of a note
To replace the text of a note, use the contents property, as shown in the following sample. For the
complete script, see Replace.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
var myNote = myStory.notes.item(0);
//Replace text of note with "This is a replaced note."
myNote.texts.item(0).contents = "This is a replaced note."
82
Notes
Converting between notes and text
Converting between notes and text
Converting a note to text
To convert a note to text, use the convertToText method, as shown in the following sample. For the
complete script, see ConvertToText.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Convert the note to text
myStory.notes.item(0).convertToText();
Converting text to a note
To convert text to a note, use the convertToNote method, as shown in the following sample. For the
complete script, see ConvertToNote.
var myDocument = app.documents.item(0);
myStory = myDocument.stories.item(0);
//Convert text to note
myStory.words.item(0).convertToNote();
Expanding and collapsing notes
Collapsing a note
The following script fragment shows how to collapse a note. For the complete script, see CollapseNote.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
var myNote = myStory.notes.item(0);
//Collapse a note
myNote.collapsed = true;
Expanding a note
The following script fragment shows how to expand a note. For the complete script, see ExpandNote.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
var myNote = myStory.notes.item(0);
//Expand a note
myNote.collapsed = false;
83
Notes
Removing a note
84
Removing a note
To remove a note, use the remove method, as shown in the following sample. For the complete script, see
RemoveNote.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Remove the note
myStory.notes.item(0).remove(myStory.notes.item(0));
Navigating among notes
Going to the first note in a story
The following script fragment shows how to go to the first note in a story. For the complete script, see
FirstNote.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Get next note
var myNote = myStory.notes.firstItem();
//Add text to the note
myNote.texts.item(0).contents = "This is the first note."
Going to the next note in a story
The following script fragment shows how to go to the next note in a story. For the complete script, see
NextNote.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Get next note
var myNote = myStory.notes.nextItem(myStory.notes.item(0));
text to the note
myNote.texts.item(0).contents = "This is the next note."
Going to the previous note in a story
The following script fragment shows how to go to the previous note in a story. For the complete script, see
PreviousNote.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Get previous note
var myNote = myStory.notes.previousItem(myStory.notes.item(1));
//Add text to the note
myNote.texts.item(0).contents = "This is the prev note."
Notes
Navigating among notes
Going to the last note in a story
The following script fragment shows how to go to the last note in a story. For the complete script, see
LastNote.
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Get next note
var myNote = myStory.notes.lastItem();
//Add text to the note
myNote.texts.item(0).contents = "This is the last note."
85
9
Tracking Changes
Chapter Update Status
CS6
Unchanged
Writers can track, show, hide, accept, and reject changes as a document moves through the writing and
editing process. All changes are recorded and visualized to make it easier to review a document.
This chapter shows how to script the most common operations involving tracking changes.
We assume that you have already read Chapter 2, “Getting Started” and know how to create, install, and
run a script. We also assume that you have some knowledge of working with text in InCopy and
understand basic typesetting terms.
Tracking Changes
This section shows how to navigate tracked changes, accept changes, and reject changes using scripting.
Whenever anyone adds, deletes, or moves text within an existing story, the change is marked in galley and
story views.
Navigating tracked changes
If the story contains a record of tracked changes, the user can navigate sequentially through tracked
changes. The following scripts show how to navigate the tracked changes.
The followinng script uses the nextItem method to navigate to the change following the insertion point:
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Story.trackChanges
If true, track changes is turned on.
if(myStory.trackChanges==true )
{
var myChangeCount =myStory.changes.length;
var myChange = myStory.changes.item(0);
if(myChangeCount>1)
{
var myChange0 = myStory.changes.nextItem(myChange);
}
}
In the following script, we use the previousItem method to navigate to the change following the
insertion point:
86
Tracking Changes
Tracking Changes
87
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
//Story.trackChanges
If true, track changes is turned on.
if(myStory.trackChanges==true )
{
var myChangeCount =myStory.changes.length;
var myChange = myStory.changes.lastItem();
if(myChangeCount>1)
{
var myChange0 = myStory.changes.previousItem(myChange);
}
}
Accepting and reject tracked changes
When changes are made to a story, by you or others, the change-tracking feature enables you to review all
changes and decide whether to incorporate them into the story. You can accept and reject
changes—added, deleted, or moved text—made by any user.
In the following script, the change is accepted:
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
var myChange = myStory.changes.item(0);
myChange.accept () ;
In the following script, the change is rejected:
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
var myChange = myStory.changes.item(0);
myChange.reject() ;
Information about tracked changes
Change information includes include date and time. The following script shows the information of a
tracked change:
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
var myChange = myStory.changes.item(0);
//ChangeTypes.DELETED_TEXT (Read Only) Deleted text.
//ChangeTypes.DELETED_TEXT (Read Only) Deleted text.
//ChangeTypes.MOVED_TEXT (Read Only) Moved text.
var myChangeTypes = myChange.changeType;
//Characters A collection of characters.
var myCharacters = myChange.characters;
//Character = myCharacters.item(0);
var myDate = myChange.date;
//InsertionPoints A collection of insertion points.
// insertpoint = myInsertionPoints.item(0);
var myInsertionPoints = myChange.insertionPoints;
//Change.lines (Read Only) A collection of lines.
var myLines = myChange.lines;
Tracking Changes
Preferences for tracking changes
//Change.paragraphs (Read Only) A collection of paragraphs.
var myParagraphs =myChange.paragraphs;
//InsertionPoints A collection of insertion points.
// insertpoint = myInsertionPoints.item(0);
var myStoryOffset = myChange.storyOffset;
//Change.textColumns (Read Only) A collection of text columns.
var myTextColumns = myChange.textColumns;
//Change.textStyleRanges (Read Only) A collection of text style ranges.
var myTextStyleRanges = myChange.textStyleRanges;
//Change.textVariableInstances (Read Only) A collection of text variable instances.
var myTextVariableInstances = myChange.textVariableInstances;
//Change.texts (Read Only) A collection of text objects.
var myTexts = myChange.texts;
var myUserName = myChange.userName;
var myWords = myChange.words;
Preferences for tracking changes
Track-changes preferences are user settings for tracking changes. For example, you can define which
changes are tracked (adding, deleting, or moving text). You can specify the appearance of each type of
tracked change, and you can have changes identified with colored change bars in the margins. The
following script shows how to set and get these preferences:
var myTrackChangesPreference = app.trackChangesPreferences ;
with(myTrackChangesPreference)
{addedBackgroundColorChoice =
ChangeBackgroundColorChoices.CHANGE_BACKGROUND_USES_CHANGE_PREF_COLOR;
addedTextColorChoice = ChangeTextColorChoices.CHANGE_USES_CHANGE_PREF_COLOR ;
backgroundColorForAddedText = UIColors.gray;
var myColor = backgroundColorForDeletedText;
backgroundColorForDeletedText = UIColors.red;
backgroundColorForMovedText = UIColors.pink;
changeBarColor = UIColors.charcoal;
deletedBackgroundColorChoice
=ChangeBackgroundColorChoices.CHANGE_BACKGROUND_USES_CHANGE_PREF_COLOR;
deletedTextColorChoice =ChangeTextColorChoices.CHANGE_USES_CHANGE_PREF_COLOR ;
//ChangebarLocations.LEFT_ALIGN (Read Only) Change bars are in the left margin.
//ChangebarLocations.RIGHT_ALIGN (Read Only) Change bars are in the right margin
locationForChangeBar = ChangebarLocations.LEFT_ALIGN;
//ChangeMarkings.OUTLINE (Read Only)
Outlines changed text.
//ChangeMarkings.NONE (Read Only) Does not mark changed text.
//ChangeMarkings.STRIKETHROUGH (Read Only) Uses a strikethrough to mark changed
text.
//ChangeMarkings.UNDERLINE_SINGLE (Read Only) Underlines changed text.
88
Tracking Changes
Preferences for tracking changes
markingForAddedText =ChangeMarkings.OUTLINE;
markingForDeletedText = ChangeMarkings.STRIKETHROUGH;
markingForMovedText = ChangeMarkings.UNDERLINE_SINGLE;
movedBackgroundColorChoice
=ChangeBackgroundColorChoices.CHANGE_BACKGROUND_USES_CHANGE_PREF_COLOR;
movedTextColorChoice = ChangeTextColorChoices.CHANGE_USES_CHANGE_PREF_COLOR ;
showAddedText = true;
shhowDeletedText =true;
showMovedText = true;
spellCheckDeletedtext = true;
showChangeBar = true;
textColorForAddedText=UIColors.blue;
textColorForDeletedText=UIColors.yellow;
textColorForMovedText=UIColors.green;
}
89
10
Assignments
Chapter Update Status
CS6
Unchanged
An assignment is a container for text and graphics in an InDesign file that can be viewed and edited in
InCopy. Typically, an assignment contains related text and graphics, such as body text, captions, and
illustrations that make up a magazine article. Only InDesign can create assignments and assignment files.
This tutorial shows how to script the most common operations involving assignments.
We assume that you have already read Chapter 2, “Getting Started” and know how to create, install, and
run a script.
Assignment object
The section shows how to work with assignments and assignment files. Using scripting, you can open the
assignment file and get assignment properties.
Opening assignment files
The following script shows how to open an existing assignment file:
//Open an exist assignment file
var myDocument = app.open(File("/c/a.icma"));
var myAssignement = myDocument.assignments.item(0);
Iterating through assignment properties
The following script fragment shows how to get assignment properties, such as the assignment name,
user name, location of the assignment file, and export options for the assignment.
var myName = myAssignement.name;
var myUserName = myAssignement.userName;
var myDocument = app.documents.item(0);
var myAssignement = myDocument.assignments.item(0);
var myFilePath = myAssignement.filePath;
var myFramecolor = myAssignement.frameColor;
// exportOptions property can be:
// AssignmentExportOptions.ASSIGNED_SPREADS
// AssignmentExportOptions.EMPTY_FRAMES
// AssignmentExportOptions.EVERYTHING
var myExportOptions = myAssignement.exportOptions;
90
Assignments
An assignment story
91
Assignment packages
Assignment packages (.incp files created by InCopy) are compressed folders that contain assignment files.
An assignment can be packaged using the createPackage method. The following sample script uses this
technique to create a package file:
var myDocument = app.documents.item(0);
var myAssignement = myDocument.assignments.item(0);
if(myAssignement.packaged==false)
{
var myFile= new File("/c/b.icap");
// PackageType.FORWARD_PACKAGE Creates an assignment package for export.
// PackageType.RETURN_PACKAGE Create a package to place in the main document.
myAssignement.createPackage(myFile,PackageType.FORWARD_PACKAGE);
}
An assignment story
The following diagram shows InCopy’s assignment object model. An assignment document contains one
or more assignments; an assignment contains zero, one, or more assigned stories. Each assigned story
references a text story or image story.
document
1
1…*
assignment
1
0…*
assigned story
1
1
text/image story
This section covers the process of getting assigned stories and assignment story properties.
Assigned-story object
The following script shows how to get an assigned story from an assignment object:
var myDocument = app.documents.item(0);
var myAssignement = myDocument.assignments.item(0);
var myAssignmentStory = myAssignement.assignedStories.item(0);
Iterating through the assigned-story properties
In InCopy, assigned-story objects have properties. The following script shows how to get all properties of
an assigned-story object:
Assignments
An assignment story
var myDocument = app.documents.item(0);
var myAssignement = myDocument.assignments.item(0);
var myAssignmentStory = myAssignement.assignedStories.item(0);
if(myAssignmentStory != null)
{
var myName = myAssignmentStory.name;
var myIsvalid = myAssignmentStory.isValid;
var myFilePath = myAssignmentStory.filePath;
var myStoryReference = myAssignmentStory.storyReference;
}
92
11
XML
Chapter Update Status
CS6
Unchanged
Extensible Markup Language, or XML, is a text-based mark-up system created and managed by the World
Wide Web Consortium (www.w3.org). Like Hypertext Markup Language (HTML), XML uses angle brackets
to indicate markup tags (for example, or ). While HTML has a predefined set of tags,
XML allows you to describe content more precisely by creating custom tags.
Because of its flexibility, XML increasingly is used as a format for storing data. InCopy includes a complete
set of features for importing XML data into page layouts, and these features can be controlled using
scripting.
We assume that you have already read Chapter 2, “Getting Started” and know how to create, install, and
run a script. We also assume that you have some knowledge of XML, DTDs, and XSLT.
Overview
Because XML is entirely concerned with content and explicitly not concerned with formatting, making
XML work in a page-layout context is challenging. InCopy’s approach to XML is quite complete and
flexible, but it has a few limitations:
Once XML elements are imported into an InCopy document, they become InCopy elements that
correspond to the XML structure. The InCopy representations of the XML elements are not the same thing
as the XML elements themselves.
Each XML element can appear only once in a layout. If you want to duplicate the information of the
XML element in the layout, you must duplicate the XML element itself.
The order in which XML elements appear in a layout depends largely on the order in which they
appear in the XML structure.
Any text that appears in a story associated with an XML element becomes part of that element’s data.
The best approach to scripting XML in InCopy
You might want to do most of the work on an XML file outside InCopy, before importing the file into an
InCopy layout. Working with XML outside InCopy, you can use a wide variety of excellent tools, like XML
editors and parsers.
When you need to rearrange or duplicate elements in a large XML data structure, the best approach is to
transform the XML using XSLT. You can do this as you import the XML file.
93
XML
Scripting XML Elements
94
Scripting XML Elements
This section shows how to set XML preferences and XML import preferences, import XML, create XML
elements, and add XML attributes. The scripts in this section demonstrate techniques for working with the
XML content itself; for scripts that apply formatting to XML elements, see “Adding XML elements to a
story” on page 99.
Setting XML preferences
You can control the appearance of the InCopy structure panel using the XML view-preferences object, as
shown in the following script fragment (from the XMLViewPreferences tutorial script):
var myDocument = app.documents.add();
var myXMLViewPreferences = myDocument.xmlViewPreferences;
myXMLViewPreferences.showAttributes = true;
myXMLViewPreferences.showStructure = true;
myXMLViewPreferences.showTaggedFrames = true;
myXMLViewPreferences.showTagMarkers = true;
myXMLViewPreferences.showTextSnippets = true;
You also can specify XML tagging-preset preferences (the default tag names and user-interface colors for
tables and stories) using the XML-preferences object, as shown in the following script fragment (from the
XMLPreferences tutorial script):
var myDocument = app.documents.add();
var myXMLPreferences = myDocument.xmlPreferences;
myXMLPreferences.defaultCellTagColor = UIColors.blue;
myXMLPreferences.defaultCellTagName = "cell";
myXMLPreferences.defaultImageTagColor = UIColors.brickRed;
myXMLPreferences.defaultImageTagName = "image";
myXMLPreferences.defaultStoryTagColor = UIColors.charcoal;
myXMLPreferences.defaultStoryTagName = "text";
myXMLPreferences.defaultTableTagColor = UIColors.cuteTeal;
myXMLPreferences.defaultTableTagName = "table";
Setting XML import preferences
Before importing an XML file, you can set XML-import preferences that can apply an XSLT transform,
govern the way white space in the XML file is handled, or create repeating text elements. You do this using
the XML import-preferences object, as shown in the following script fragment (from the
XMLImportPreferences tutorial script):
XML
Scripting XML Elements
95
var myDocument = app.documents.add();
var myXMLImportPreferences = myDocument.xmlImportPreferences;
myXMLImportPreferences.allowTransform = false;
myXMLImportPreferences.createLinkToXML = false;
myXMLImportPreferences.ignoreUnmatchedIncoming = true;
myXMLImportPreferences.ignoreWhitespace = true;
myXMLImportPreferences.importCALSTables = true;
myXMLImportPreferences.importStyle = XMLImportStyles.mergeImport;
myXMLImportPreferences.importTextIntoTables = false;
myXMLImportPreferences.importToSelected = false;
myXMLImportPreferences.removeUnmatchedExisting = false;
myXMLImportPreferences.repeatTextElements = true;
//The following properties are only used when the
//AllowTransform property is set to True.
//myXMLImportPreferences.transformFilename = "c:\myTransform.xsl"
//If you have defined parameters in your XSL file, then you can pass
//parameters to the file during the XML import process. For each parameter,
//enter an array containing two strings. The first string is the name of the
//parameter, the second is the value of the parameter.
//myXMLImportPreferences.transformParameters = [["format", "1"]];
Importing XML
Once you set the XML-import preferences the way you want them, you can import an XML file, as shown in
the following script fragment (from the ImportXML tutorial script):
myDocument.importXML(File("/c/completeDocument.xml"));
When you need to import the contents of an XML file into a specific XML element, use the importXML
method of the XML element, rather than the corresponding method of the document. See the following
script fragment (from the ImportXMLIntoElement tutorial script):
var myXMLTag = myDocument.xmlTags.add("xml_element");
var myXMLElement = myDocument.xmlElements.item(0).xmlElements.add(myXMLTag);
//Import into the new XML element.
myXMLElement.importXML(File("/c/completeDocument.xml"));
You also can set the importToSelected property of the xmlImportPreferences object to true, then
select the XML element, and then import the XML file, as shown in the following script fragment (from the
ImportXMLIntoSelectedXMLElement tutorial script):
var myXMLTag = myDocument.xmlTags.add("xml_element");
var myXMLElement = myDocument.xmlElements.item(0).xmlElements.add(myXMLTag);
myDocument.select(myXMLElement);
myDocument.xmlImportPreferences.importToSelected = true;
//Import into the selected XML element.
myDocument.importXML(File("/c/test.xml"));
Creating an XML tag
XML tags are the names of XML elements that you want to create in a document. When you import XML,
the element names in the XML file are added to the list of XML tags in the document. You also can create
XML tags directly, as shown in the following script fragment (from the MakeXMLTags tutorial script):
XML
Scripting XML Elements
96
//You can create an XML tag without specifying a color for the tag.
var myXMLTagA = myDocument.xmlTags.add("XML_tag_A");
//You can define the highlight color of the XML tag using the UIColors enumeration...
var myXMLTagB = myDocument.xmlTags.add("XML_tag_B", UIColors.gray);
//...or you can provide an RGB array to set the color of the tag.
var myXMLTagC = myDocument.xmlTags.add("XML_tag_C", [0, 92, 128]);
Loading XML tags
You can import XML tags from an XML file without importing the XML contents of the file. You might want
to do this to work out a tag-to-style or style-to-tag mapping before importing the XML data, as shown in
the following script fragment (from the LoadXMLTags tutorial script):
myDocument.loadXMLTags(File("/c/test.xml"));
Saving XML tags
Just as you can load XML tags from a file, you can save XML tags to a file, as shown in the following script.
When you do this, only the tags themselves are saved in the XML file; document data is not included. As
you would expect, this process is much faster than exporting XML, and the resulting file is much smaller.
The following sample script shows how to save XML tags (for the complete script, see SaveXMLTags):
myDocument.saveXMLTags(File("/c/xml_tags.xml"), "Tag set created October 5, 2006");
Creating an XML element
Ordinarily, you create XML elements by importing an XML file, but you also can create an XML element
using InCopy scripting, as shown in the following script fragment (from the CreateXMLElement tutorial
script):
var myXMLTag = myDocument.xmlTags.add("myXMLTag");
var myRootElement = myDocument.xmlElements.item(0);
var myXMLElment = myRootElement.xmlElements.add(myXMLTag);
myXMLElement.contnets = "This is an XML element containing text."
Moving an XML element
You can move XML elements within the XML structure using the move method, as shown in the following
script fragment (from the MoveXMLElement tutorial script):
XML
Scripting XML Elements
97
var myDocument = app.documents.add();
var myRootXMLElement = myDocument.xmlElements.item(0);
var myXMLTag = myDocument.xmlTags.add("xml_element");
var myXMLElementA = myRootXMLElement.xmlElements.add(myXMLTag);
myXMLElementA.contents = "A";
var myXMLElementB = myRootXMLElement.xmlElements.add(myXMLTag);
myXMLElementB.contents = "B";
var myXMLElementC = myRootXMLElement.xmlElements.add(myXMLTag);
myXMLElementC.contents = "C";
var myXMLElementD = myRootXMLElement.xmlElements.add(myXMLTag);
myXMLElementD.contents = "D";
//Move the XML element containing "A" to after
//the XML element containing "C"
myXMLElementA.move(LocationOptions.after, myRootXMLElement.xmlElements.item(2));
//Move the XML element containing "D" to the beginning of its parent.
myRootXMLElement.xmlElements.item(-1).move(LocationOptions.atBeginning);
//Place the XML structure so that you can see the result.
myDocument.stories.item(0).placeXML(myRootXMLElement);
Deleting an XML element
Deleting an XML element removes it from both the layout and the XML structure, as shown in the
following script fragment (from the DeleteXMLElement tutorial script):
myRootXMLElement.xmlElements.item(0).remove();
Duplicating an XML element
When you duplicate an XML element, the new XML element appears immediately after the original XML
element in the XML structure, as shown in the following script fragment (from the DuplicateXMLElement
tutorial script):
var myDocument = app.documents.item(0);
var myRootXMLElement = myDocument.xmlElements.item(0);
//Duplicate the XML element containing "A"
var myNewXMLElement = myRootXMLElement.xmlElements.item(0).duplicate();
//Change the content of the duplicated XML element.
myNewXMLElement.contents = myNewXMLElement.contents + " duplicate";
Removing items from the XML structure
To break the association between a text object and an XML element, use the untag method, as shown in
the following script. The objects are not deleted, but they are no longer tied to an XML element (which is
deleted). Any content of the deleted XML element becomes associated with the parent XML element. If
the XML element is the root XML element, any layout objects (text or page items) associated with the XML
element remain in the document. (For the complete script, see UntagElement.)
var myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(-2);
myXMLElement.untag();
Creating an XML comment
XML comments are used to make notes in XML data structures. You can add an XML comment using
something like the following script fragment (from the MakeXMLComment tutorial script):
XML
Scripting XML Elements
98
var myRootXMLElement = myDocument.xmlElements.item(0);
var myXMLElement = myRootXMLElement.xmlElements.item(1);
myXMLElement.xmlComments.add("This is an XML comment.");
Creating an XML processing instruction
A processing instruction (PI) is an XML element that contains directions for the application reading the
XML document. XML processing instructions are ignored by InCopy but can be inserted in an InCopy XML
structure for export to other applications. An XML document can contain multiple processing instructions.
An XML processing instruction has two parts, target and value. The following is an example of an XML
processing instruction:
The following script fragment shows how to add an XML processing instruction (for the complete script,
see MakeProcessingInstruction):
var myRootXMLElement = myDocument.xmlElements.item(0);
var myXMLProcessingInstruction = myRootXMLElement.xmlInstructions.add("xml-stylesheet
type=\"text/css\" ", "href=\"generic.css\"");
Working with XML attributes
XML attributes are “metadata” that can be associated with an XML element. To add an attribute to an
element, use something like the following script fragment. An XML element can have any number of XML
attributes, but each attribute name must be unique within the element (that is, you cannot have two
attributes named “id”).
The following script fragment shows how to add an XML attribute to an XML element (for the complete
script, see MakeXMLAttribute):
var myDocument = app.documents.item(0);
var myRootXMLElement = myDocument.xmlElements.item(0);
var myXMLElementB = myRootXMLElement.xmlElements.item(1);
myXMLElementB.xmlAttributes.add("example_attribute", "This is an XML attribute. It
will not appear in the layout!");
In addition to creating attributes directly using scripting, you can convert XML elements to attributes.
When you do this, the text contents of the XML element become the value of an XML attribute added to
the parent of the XML element. Because the name of the XML element becomes the name of the attribute,
this method can fail when an attribute with that name already exists in the parent of the XML element. If
the XML element contains page items, those page items are deleted from the layout.
When you convert an XML attribute to an XML element, you can specify the location where the new XML
element is added. The new XML element can be added to the beginning or end of the parent of the XML
attribute. By default, the new element is added at the beginning of the parent element.
You also can specify an XML mark-up tag for the new XML element. If you omit this parameter, the new
XML element is created with the same XML tag as the XML element containing the XML attribute.
The following script shows how to convert an XML element to an XML attribute (for the complete script,
see the ConvertElementToAttribute tutorial script):
XML
Adding XML elements to a story
99
var myDocument = app.documents.add();
var myRootXMLElement = myDocument.xmlElements.item(0);
var myXMLTag = myDocument.xmlTags.add("myXMLElement");
var myXMLElement = myRootXMLElement.xmlElements.add(myXMLTag);
myXMLElement.contents = "This is content in an XML element.";
myXMLElement.convertToAttribute();
//Place the XML content so that you can see the result of the change.
var myStory = myDocument.stories.item(0);
myStory.placeXML(myRootXMLElement);
You also can convert an XML attribute to an XML element, as shown in the following script fragment (from
the ConvertAttributeToElement tutorial script):
var myRootXMLElement = myDocument.xmlElements.item(0);
var myXMLElementB = myRootXMLElement.xmlElements.item(1);
//The "at" parameter can be either LocationOptions.atEnd or
LocationOptions.atBeginning, but cannot
//be LocationOptions.after or LocationOptions.before.
myXMLElementB.xmlAttributes.item(0).convertToElement(XMLElementLocation.elementEnd,
myDocument.xmlTags.item("myXMLElement"));
Working with XML stories
When you import XML elements that were not associated with a layout element (a story or page item),
they are stored in an XML story. You can work with text in unplaced XML elements just as you would work
with the text in a text frame. The following script fragment shows how this works (for the complete script,
see XMLStory):
var myXMLStory = myDocument.xmlStories.item(0);
//Though the text has not yet been placed in the layout, all text
//properties are available.
myXMLStory.texts.item(0).pointSize = 72;
//Place the XML element in the layout to see the result.
myDocument.xmlElements.item(0).xmlElements.item(0).placeXML(myDocument.pages.item(0).
textFrames.item(0));
Exporting XML
To export XML from an InCopy document, export either the entire XML structure in the document or one
XML element (including any child XML elements it contains). The following script fragment shows how to
do this (for the complete script, see ExportXML):
myDocument.exportFile("XML", File("/c/test.xml")
Adding XML elements to a story
Previously, we covered the process of getting XML data into InCopy documents and working with the XML
structure in a document. In this section, we discuss techniques for getting XML information into a story
and applying formatting to it.
XML
Adding XML elements to a story
100
Associating XML elements with text
To associate text with an existing XML element, use the placeXML method. This replaces the content of the
page item with the content of the XML element, as shown in the following script fragment (from the
PlaceXML tutorial script):
myDocument.stories.item(0).placeXML(xmlElements.item(0);
To associate an existing text object with an existing XML element, use the markup method. This merges
the content of the text object with the content of the XML element (if any). The following script fragment
shows how to use the markup method (for the complete script, see Markup):
var myDocument = app.documents.add();
var myRootXMLElement = myDocument.xmlElements.item(0);
var myStory = myDocument.stories.item(0);
myStory.placeXML(myRootXMLElement);
myString = "This is the first paragraph in the story.\r";
myString += "This is the second paragraph in the story.\r";
myString += "This is the third paragraph in the story.\r";
myString += "This is the fourth paragraph in the story.\r";
myStory.contents = myString;
var myXMLTag = myDocument.xmlTags.add("myXMLlement");
var myXMLElement = myRootXMLElement.xmlElements.add(myXMLTag);
myStory.paragraphs.item(2).markup(myXMLElement);
Inserting text in and around XML text elements
When you place XML data into an InCopy story, you often need to add white space (for example, return
and tab characters) and static text (labels like “name” or “address”) to the text of your XML elements. The
following sample script shows how to add text in and around XML elements (for the complete script, see
InsertTextAsContent):
var myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(0);
//By inserting the return character after the XML element, the character
//becomes part of the content of the parent XML element, not of the element itself.
myXMLElement.insertTextAsContent("\r", XMLElementPosition.afterElement);
myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(1);
myXMLElement.insertTextAsContent("Static text: ", XMLElementPosition.beforeElement);
myXMLElement.insertTextAsContent("\r", XMLElementPosition.afterElement);
//To add text inside the element, set the location option to beginning or end.
myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(2);
myXMLElement.insertTextAsContent("Text at the start of the element: ",
XMLElementPosition.elementStart);
myXMLElement.insertTextAsContent(" Text at the end of the element.",
XMLElementPosition.elementEnd);
myXMLElement.insertTextAsContent("\r", XMLElementPosition.afterElement);
//Add static text outside the element.
myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(3);
myXMLElement.insertTextAsContent("Text before the element: ",
XMLElementPosition.beforeElement);
myXMLElement.insertTextAsContent(" Text after the element.",
XMLElementPosition.afterElement);
//To insert text inside the text of an element, work with the text
//objects contained by the element.
myXMLElement.words.item(2).insertionPoints.item(0).contents = "(the third word of) ";
XML
Adding XML elements to a story
101
Mapping tags to styles
One of the quickest ways to apply formatting to XML text elements is to use xmlImportMaps, also known
as tag-to-style-mappings. When you do this, you can associate a specific XML tag with a paragraph or
character style. When you use themapTagsToStyles method of the document, InCopy applies the style to
the text, as shown in the following script fragment (from the MapTagsToStyles tutorial script):
var myDocument = app.documents.item(0);
//Create a tag to style mapping.
myDocument.xmlImportMaps.add(myDocument.xmlTags.item("heading_1"),
myDocument.paragraphStyles.item("heading 1"));
myDocument.xmlImportMaps.add(myDocument.xmlTags.item("heading_2"),
myDocument.paragraphStyles.item("heading 2"));
myDocument.xmlImportMaps.add(myDocument.xmlTags.item("para_1"),
myDocument.paragraphStyles.item("para 1"));
myDocument.xmlImportMaps.add(myDocument.xmlTags.item("body_text"),
myDocument.paragraphStyles.item("body text"));
//Apply the tag to style mapping.
myDocument.mapXMLTagsToStyles();
//Place the XML element in the layout to see the result.
myDocument.stories.item(0).placeXML(myDocument.xmlElements.item(0));
Mapping styles to tags
When you have formatted text that is not associated with any XML elements, and you want to move that
text into an XML structure, use style-to-tag mapping, which associates paragraph and character styles with
XML tags. To do this, use xmlExportMaps objects to create the links between XML tags and styles, then use
the mapStylesToTags method to create the corresponding XML elements, as shown in the following
script fragment (from the MapStylesToTags tutorial script):
var myDocument = app.documents.item(0);
//Create a style to tag mapping.
myDocument.xmlExportMaps.add(myDocument.paragraphStyles.item("heading 1"),
myDocument.xmlTags.item("heading_1"));
myDocument.xmlExportMaps.add(myDocument.paragraphStyles.item("heading 2"),
myDocument.xmlTags.item("heading_2"));
myDocument.xmlExportMaps.add(myDocument.paragraphStyles.item("para 1"),
myDocument.xmlTags.item("para_1"));
myDocument.xmlExportMaps.add(myDocument.paragraphStyles.item("body text"),
myDocument.xmlTags.item("body_text"));
//Apply the style to tag mapping.
myDocument.mapStylesToXMLTags();
Another approach is simply to have your script create a new XML tag for each paragraph or character style
in the document, and then apply the style to tag mapping, as shown in the following script fragment (from
the MapAllStylesToTags tutorial script):
XML
Adding XML elements to a story
102
var myDocument = app.documents.item(0);
//Create tags that match the style names in the document,
//creating an XMLExportMap for each tag/style pair.
for(var myCounter = 0; myCounterSource Exif Data:
File Type : PDF
File Type Extension : pdf
MIME Type : application/pdf
PDF Version : 1.6
Linearized : No
Encryption : Standard V1.3 (40-bit)
User Access : Print, Annotate, Fill forms, Extract, Assemble, Print high-res
Tagged PDF : Yes
XMP Toolkit : Adobe XMP Core 5.2-c001 63.139439, 2010/09/27-13:37:26
Copyright : AdobeSystems Incorporated, 2012
Producer : Acrobat Distiller 10.0.0 (Windows)
Format : application/pdf
Title : Adobe InCopy CS6 JavaScript Scripting Guide
Creator : Adobe Systems Incorporated
Create Date : 2012:02:17 00:28:50Z
Creator Tool : FrameMaker 8.0
Modify Date : 2012:02:17 00:44:29-08:00
Metadata Date : 2012:02:17 00:44:29-08:00
Document ID : uuid:1796c2af-adae-4b4d-858c-ad044045eec1
Instance ID : uuid:9b17973b-273e-4858-ab55-2b9470f61b7c
Page Mode : UseOutlines
Page Count : 105
Author : Adobe Systems Incorporated