Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
7

Need script to search and apply style to rows with specific text

Community Beginner ,
May 02, 2024 May 02, 2024

Hello,

 

i am looking for help on creating a working script that will search a table containing a specific text string, then selecting the rows it resides on and applying either a character style, cell style, or paeticular font to each of those rows. 

TOPICS
Scripting
793
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Community Beginner , May 03, 2024 May 03, 2024

I actually just got the first script to work.  

thank you very much to all!

 

 

Translate
Community Expert ,
May 02, 2024 May 02, 2024

A rudimentary example. This will apply to every table in the doc; getting a single table requires some finesse. You should just be using Cell Styles with the correct applied Paragraph Style in the Cell Style definition; changing character styles or, worse, font seems innappropriate, but this could be adjusted to do such a thing. 

"xyz" is your test string. It's converted into a regular expression here, which would allow for more robust searches. "Cell Style 1" should be changed to whatever the name of your Cell Style is.  

 

var rows = app.activeDocument.stories.everyItem().tables.everyItem().rows.everyItem().getElements();
var i = rows.length;
var rx = /xyz/gi;
var ec;
while(i--) {
    ec = rows[i].cells.everyItem();
    if (rx.test(ec.contents.join("|"))) {
        ec.appliedCellStyle = "Cell Style 1";
    }
}

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
May 02, 2024 May 02, 2024

Hi @Jeff37144906ge0e I'll add my version as well as @brian_p_dts's excellent script, just because it is more learning for you, and also it is a more general script: for example you can configure it to accept any sort of object, eg. document, selection, or anything.

 

You can try the script with the attached demo.indd but, to use it yourself, you need to edit the `customizeMe` function. This is where you configure the code to do what you want. There is no error checking here currently so if, for example, a cell style is missing it will throw an error.

 

In my example cusomizeMe function we search for 'foo' and 'bar' and set the cell styles accordingly, and also search for 'foobar' and set the whole row's cell styles. I'm using strings here for searching, but as @brian_p_dts mentioned, using RegExp can do more complex matching and you can just swap them eg. to find 'foo' at the start of the cell, then instead of 'foo' you can use /^foo/.

 

Let me know if you want any further explanation or if you try the script and something doesn't work right.

- Mark

demo.gif

/**
 * @file Set Cell Styles.js
 * Searches for text in table cells
 * and sets cell styles accordingly.
 * @author m1b
 * @discussion https://community.adobe.com/t5/indesign-discussions/need-script-to-search-and-apply-style-to-rows-with-specific-text/m-p/14595514
 */
function main() {

    if (0 === app.documents.length)
        return alert('Please open a document and try again.');

    var doc = app.activeDocument,
        counter = 0;

    // apply to whole document
    var target = doc;

    // or, apply to selection only
    // var target = doc.selection;

    // execute customize me for each cell in target
    doSomethingToThings(getCells(target), customizeMe);

    /**
     * Set cell style based on text found in cell contents.
     * Configure this to suit your needs
     * @param {Cell} cell - an Indesign Table Cell.
     */
    function customizeMe(cell) {

        // counter is just for reporting at end
        counter++;

        if (-1 !== cell.contents.search('foobar')) {
            // example to set the whole row style
            cell.parentRow.cells.everyItem().appliedCellStyle = 'My Row Style'
        }

        else if (-1 !== cell.contents.search('foo'))
            cell.appliedCellStyle = 'My Cell Style 1'

        else if (-1 !== cell.contents.search('bar'))
            cell.appliedCellStyle = 'My Cell Style 2'

        else
            counter--;

    };

    // show results
    alert('Set ' + counter + ' cell styles.');

};
app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, 'Set Cell Styles');


/**
 * Performs function `doThisTo` on each element of `things`.
 * @param {Array<*>} things - array of things.
 * @param {Function} doThisTo - the function to execute, given a thing.
 */
function doSomethingToThings(things, doThisTo) {

    for (var i = things.length - 1; i >= 0; i--)
        doThisTo(things[i]);

};

/**
 * Returns a thing with matching property.
 * @param {Array|collection} things - the things to look through, eg. PageItems.
 * @param {String} key - the property name, eg. 'name'.
 * @param {*} value - the value to match.
 * @returns {*} - the thing.
 */
function getThing(things, key, value) {

    for (var i = 0; i < things.length; i++)
        if (things[i][key] == value)
            return things[i];

};

/**
 * Returns array of cells, given an object.
 * @author m1b
 * @version 2024-05-03
 * @param {*} obj - an object, can be an array, eg. a document selection.
 * @returns {Array<Cell>}
 */
function getCells(obj) {

    var cells = [];

    if (obj == undefined)
        return [];

    else if ('Array' === obj.constructor.name)
        for (var i = 0; i < obj.length; i++)
            cells = cells.concat(getCells(obj[i]));

    else if ('Document' === obj.constructor.name)
        cells = getCells(getThingsFromDocument(obj, 'stories'));

    else if (
        obj.hasOwnProperty('cells')
        && obj.cells.length > 0
    )
        cells = obj.cells.everyItem().getElements();

    else if (
        obj.hasOwnProperty('tables')
        && obj.tables.length > 0
    )
        cells = getCells(obj.tables.everyItem().cells.everyItem().getElements())

    else if ('Cell' === obj.constructor.name)
        cells = [obj];

    else if (
        obj.hasOwnProperty('parent')
        && 'Cell' === obj.parent.constructor.name
    )
        cells = getCells(obj.parent.parent);

    else if ('Table' === obj.constructor.name)
        cells = obj.cells.everyItem().getElements();

    return cells;

};

/**
 * Returns array of things found in `doc`.
 * `thingPlural` is a Document property name,
 * for example 'formFields' or 'swatches'.
 * @author m1b
 * @version 2024-05-03
 * @param {Document} doc - an Indesign Document.
 * @param {String} thingPlural - collective property of Document eg. 'checkBoxes'.
 * @returns {?Array<*>} - the things.
 */
function getThingsFromDocument(doc, thingPlural) {

    if (
        !doc.hasOwnProperty(thingPlural)
        || 'function' !== typeof doc[thingPlural].everyItem
    )
        return;

    var things = doc[thingPlural].everyItem().getElements();

    if (
        doc.hasOwnProperty('groups')
        && doc.groups.length > 0
        && doc.groups[0].hasOwnProperty(thingPlural)
    )
        // also collect things in groups
        things = things.concat(doc.groups.everyItem()[thingPlural].everyItem().getElements());

    if (
        doc.hasOwnProperty('stories')
        && doc.stories.length > 0
        && doc.stories[0].hasOwnProperty(thingPlural)
    ) {

        // also collect any anchored things
        things = things.concat(doc.stories.everyItem()[thingPlural].everyItem().getElements());

        if (doc.stories.everyItem().tables.length > 0)
            // also collect any thing in tables
            things = things.concat(doc.stories.everyItem().tables.everyItem().cells.everyItem()[thingPlural].everyItem().getElements());
    }

    return things;

};

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
May 03, 2024 May 03, 2024

Thank you to both of you for your input.  

I am very new to scripting so trying to make sense of it all.  I have tried both scripts and both end up giving me errors. 

to simplify perhaps you could further help. I am looking to to bold text in the rows containing the text string "Month-year". This is what I am searching for and I'd like to have those rows with bolded fonts.  Ideally it would be done by selected table or even by selected sections of a table.  But if  it is easier by document search then it is what it is. 

thank again for the help. 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
May 03, 2024 May 03, 2024
 

@Jeff37144906ge0e 

 

Please always post screenshots of BEFORE and AFTER of what you would like to achieve.

 

quote

[...]

I am very new to scripting so trying to make sense of it all.  I have tried both scripts and both end up giving me errors.

[...]


By @Jeff37144906ge0e

 

Without the screenshot of the error - we can't help you much.

 

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
May 03, 2024 May 03, 2024
LATEST

I actually just got the first script to work.  

thank you very much to all!

 

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines