Add brackets to paragraphs and tables in selected text
- August 3, 2023
- 1 reply
- 2059 views
Hi
What I’m trying to achieve is to select some text and for the script to put square brackets at either end of the paragraph which can be picked up by a GREP style in the paragraph style that will highlight the text. If I select text that contains a table I would like it to highlight the text in the table. If the paragraph is empty I would like it to do nothing. For the most part it works fine, but when I select text where the last paragraph of the selection is either empty or contains a table it throws an error saying the object is invalid, I presume because it can’t find a table. But why then would it work if it’s not the final paragraph? Please can anyone help? I have cut my script to the basics and I’ve included a screenshot of what I’m trying to achieve.
var sel = app.selection[0];
var rgEmpty = /^\s*$/
if (sel.constructor.name == "Text") {
if (sel.paragraphs.length > 1) {
for (var p = 0; p < sel.paragraphs.length; p++) {
if (sel.paragraphs[p].tables.length > 0) {
for (var q = 0; q < sel.paragraphs[p].tables.length; q++) {
var cellParas = sel.paragraphs[p].tables[q].cells
for (var r = 0; r < cellParas.length; r++) {
for (var s = 0; s < cellParas[r].paragraphs.length; s++) {
sqTextInParas(cellParas[r].paragraphs[s], s, cellParas[r].paragraphs.length - 1)
}
}
}
} else {
var endOfStory = sel.paragraphs[p].parentStory.paragraphs[-1]
var selectedPara = sel.paragraphs[p]
sqTextInParas(sel.paragraphs[p], selectedPara, endOfStory)
}
}
}
}
function sqTextInParas(selection, thisPara, endOfStory,) {
if (!rgEmpty.test(selection.contents)) {
if (thisPara == endOfStory) {
selection.insertionPoints[-1].contents = ']';
} else {
selection.insertionPoints[-2].contents = ']';
}
selection.insertionPoints[0].contents = '[';
}
}


