Skip to main content
Inspiring
June 10, 2024
Answered

Script to insert styled paragraph and text

  • June 10, 2024
  • 2 replies
  • 516 views

What I am trying to do:

I want a script to find every instance of a paragraph styled as Chapter Title, then insert a paragraph styled "Inline graphic" and in that new paragraph insert the text "InsertGraphic"

 

Current Script (cobbled together from two different scripts):

var myDocument = app.activeDocument;
var myParas = myDocument.stories.everyItem().paragraphs.everyItem().getElements();
var myPage = myDocument.pages;
textStyle = app.activeDocument.paragraphStyles.item("Inline graphic");
 
 
for (i=0; i<myParas.length; i++)
{
if(myParas[i].appliedParagraphStyle.name == "Chapter Title")
{
myParas[i].insertionPoints[-1].contents = myParas[i].insertionPoints[0].contents + "\r"; // Use a newline to split the paragraph
        myParas[i].insertionPoints[-1].appliedParagraphStyle = textStyle;
  myParas[i].insertionPoints[-1].contents+='INSERTgraphic';
i = i + 1;
}
}
alert("Done");

 

Issue:

I'm close. This works perfect for the first instance of Chapter Title but throws the text in the middle of the second instance and goes downhill from there. So being a total noob, I added the i+1 thing thinking that would move it to the next paragraph and somehow magically that would help. It didn't. And yes, feel free to call me blond. It's okay. I really do have blond hair.

 

Any help is greatly appreciated

This topic has been closed for replies.
Correct answer Peter Kahrel

By inserting a paragraph you disturb the items you found. To avoid this, process your found paragraphs back to front:

 

for (i=myParas.length-1; i>=0; i--)

2 replies

Peter Kahrel
Community Expert
Peter KahrelCommunity ExpertCorrect answer
Community Expert
June 11, 2024

By inserting a paragraph you disturb the items you found. To avoid this, process your found paragraphs back to front:

 

for (i=myParas.length-1; i>=0; i--)
Inspiring
June 11, 2024

Oh my goodness! I knew it would be a simple solution. I have been up all nigh wrestling with this. Thank you, thank you, thank you. It works perfectly (without the i=i+1 thing)

I so appreciate your help!

Inspiring
June 10, 2024

Additional note to others who might be doing the same thing. Once this script is working, I can then use Find/Change to find the text Insertgraphic and change it to a formatted graphic copied to the clipboard. In the change field, click the @ and go down to other, and near the bottom is the option to insert the contents of the clipboard, formatted. This is a huge time saver in setting up books with a chapter glyph or a second script to handle section markers.