Search code examples
javascriptadobe-indesign

How can I get the next paragraph after my selection in InDesign?


I'm using Adobe InDesign and ExtendScript to find a keyword using app.activeDocument.findGrep(), and I've got this part working well. I know findGrep() returns an array of Text objects. Let's say I want to work with the first result:

var result = app.activeDocument.findGrep()[0];

How can I get the next paragraph following result?


Solution

  • Use the InDesign DOM

    var nextParagraph = result.paragraphs[-1].insertionPoints[-1].paragraphs[-1];
    

    The Indesign DOM has different Text objects that you can use to address paragraphs, words, characters, or insertion points (the space between characters where your blinking cursor sits). A group of Text objects is called a collection. Collections in Indesign are similar to arrays, but one significant difference is that they can be addressed from the back by using a negative index (paragraphs[-1]).

    result refers to the findGrep() result. It can be any Text object, depending on your search terms.

    paragraphs[-1] means the last paragraph of your result (Paragraph A). If the search result is just one word, then this refers the word's enclosing paragraph, and this collection of paragraphs has just one element.

    insertionPoints[-1] refers to the last insertionPoint of Paragraph A. This comes after the paragraph mark and before the first character of the next paragraph (Paragraph B). This insertionPoint belongs to both this paragraph and the following paragraph.

    paragraphs[-1] returns the last paragraph of the insertionPoint, which is Paragraph B (the next paragraph).