John Steam February 2016

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?

Answers


John Steam February 2016

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).


milligramme February 2016

more simply code below

result.paragraphs.nextItem(result.paragraphs[0]);

thank you

mg.


Loic February 2016

Althouh nextItem seems totally appropriate and efficient, it may be a source of performance leaks especially if you call it several times in a huge loop. Keep in mind that nextItem() is a function creating an internal scope and stuff… An alternative is to navigate within the story and reach the next paragraph thanks to the insertionPoints indeces:

var main = function() {
	var doc, found, st, pCurr, pNext, ipNext, ps;
	if (!app.documents.length) return;
	doc = app.activeDocument;
	
	
	app.findGrepPreferences = app.changeGrepPreferences = null;
	
	app.findGrepPreferences.findWhat = "\\A.";
	
	found = doc.findGrep();
	
	if ( !found.length) return;
	
	found  = found[0];
	st = found.parentStory;
	
	pCurr = found.paragraphs[0];
	
	ipNext = st.insertionPoints [ pCurr.insertionPoints[-1].index ];
	var pNext = ipNext.paragraphs[0];
	
	alert( pNext.contents );
};

main();

Not claiming the absolute truth here. Just advising about possible issues with nextItem().

Post Status

Asked in February 2016
Viewed 3,663 times
Voted 12
Answered 3 times

Search




Leave an answer