CHAPTER 6: Text and Type Finding and Changing Text 103
<heading1>This is a heading.
<body_text>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 mark-up tags, as shown in the following script fragment (from the
ReadPMTags tutorial script):
var myDocument = app.documents.item;
var myStory = myDocument.stories.item(0);
myReadPMTags(myStory);
Here is the myReadPMTags function referred to in the above 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,
//the 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<myFoundItems.length; myCounter++){
myFoundTags.push(myFoundItems[myCounter].contents);
}
myFoundTags = myRemoveDuplicates(myFoundTags);
//At this point, we have a list of tags to search for.
for(myCounter = 0; myCounter < myFoundTags.length; myCounter++){
myString = myFoundTags[myCounter];
//Find the tag using findWhat.
app.findTextPreferences.findWhat = myString;
//Extract the style name from the tag.
myStyleName = myString.substring(1, myString.length-1);
//Create the style if it does not already exist.
try{
myStyle = myDocument.paragraphStyles.item(myStyleName);
myName = myStyle.name;
}
catch (myError){
myStyle = myDocument.paragraphStyles.add({name:myStyleName});
}
//Apply the style to each instance of the tag.
app.changeTextPreferences.appliedParagraphStyle = myStyle;
myStory.changeText();
//Reset the changeTextPreferences.
app.changeTextPreferences = NothingEnum.nothing;
//Set the changeTo to an empty string.
app.changeTextPreferences.changeTo = "";
//Search to remove the tags.
myStory.changeText();
//Reset the find/change preferences again.
app.changeTextPreferences = NothingEnum.nothing;
}
}
//Reset the findGrepPreferences.
app.findGrepPreferences = NothingEnum.nothing;