0

In order to get around the 255 character search limitation in the desktop Word api I'm breaking long strings into searchable chunks of 254 characters and pushing them into an object "oSearchTerms". Then I'm attempting to iterate over oSearchTerms, search for the text, highlight it, then search for the next chunk and do the same until all items in oSearchTerms have been highlighted. The problem is it's not looping. It goes through the first iteration successfully but stops.

I've tried copious context.sync() calls, return true, return context.sync(), etc, which you'll see commented out below, to no avail.

I should also point out that it's not showing any errors. The loop just isn't looping.

Do I have to convert this over to an async function? I'd like to stick with ES5 and not use fat arrow functions.

What am I missing?

var fullSearchTerm = "As discussed earlier, one of the primary objectives of these DYH rules is to ensure that operators have at least one source of XYZ-approved data and documents that they can use to comply with operational requirements The objective would be defeated if the required data and documents were not, in fact, approved and Only by retaining authority to approve these materials can we ensure that they comply with applicable requirements and can be relied upon by operators to comply with operational rules which We believe there are differences between EXSS ICA and other ICA that necessitate approval of EVIS ICA."

function findTextMatch() {
    Word.run(function(context) {
    OfficeExtension.config.extendedErrorLogging = true;
    var oSearchTerms = [];      
    var maxChars = 254;
    var lenFullSearchTerm = fullSearchTerm.length;
    var nSearchCycles = Math.ceil(Number((lenFullSearchTerm / maxChars)));
    console.log("lenFullSearchTerm: " + lenFullSearchTerm + " nSearchCycles: " + nSearchCycles);

    // create oSearchTerms object containing search terms
    // leaves short strings alone but breaks long strings into 
    // searchable 254 character chunks
    for (var i = 0; i < nSearchCycles; i++) {
        var posStart = i * maxChars;
        var mySrch = fullSearchTerm.substr(posStart, maxChars);
        console.log( i +" mySrch: "+ mySrch);
        var oSrch = {"searchterm":mySrch};
        oSearchTerms.push(oSrch);
    }

    console.log("oSearchTerms.length: " + oSearchTerms.length +" oSearchTerm: "+ JSON.stringify(oSearchTerms));

    // Begin search loop
    // iterate over oSearchTerms, find and highlight each searchterm
    for (var i = 0; i < oSearchTerms.length; i++) {
        console.log("oSearchTerms["+i+"].searchterm: " + JSON.stringify(oSearchTerms[i].searchterm));
        var searchResults = context.document.body.search(oSearchTerms[i].searchterm, { matchCase: true });      
        console.log("do context.sync() ");      
        context.load(searchResults);        
        return context.sync()
            .then(function(){
                console.log("done context.sync() ");                
                console.log("searchResults:  "+ JSON.stringify(searchResults));             
                if(typeof searchResults.items !== undefined){                   
                    console.log("i: "+i+ " searchResults: "+searchResults.items.length);
                    // highlight each result
                    for (var j = 0; j < searchResults.items.length; j++) {                          
                        console.log("highlight searchResults.items["+j +"]");       
                        searchResults.items[j].font.highlightColor = "red";
                    }                   
                }
                else{
                    console.log("typeof searchResults.items == undefined");                     
                }                   
                // return true;
                // return context.sync();
            });
            //.then(context.sync);      
            //return true;
    } // end search loop
})
.catch( function (error) {
        console.log('findTextMatch Error: ' + JSON.stringify(error));
        if (error instanceof OfficeExtension.Error) {
            console.log('findTextMatch Debug info: ' + JSON.stringify(error));
        }
    }); 
}
2
  • I answered this once before. See stackoverflow.com/a/51159442/3077495 Commented Sep 29, 2019 at 17:57
  • Thanks, Cindy. I tried working with that solution but couldn't get it to work correctly if search results returned more than a single instance of the full search term. In lieu of extending a range I thought I'd just sequentially highlight the chunks for all returned search results. Commented Sep 29, 2019 at 18:31

1 Answer 1

0

I recommend that you not have a context.sync inside a loop. That can be a performance hit and it makes the code hard to reason about. Please see my answer to: Document not in sync after replace text and this sample: Word Add-in Stylechecker for a design pattern that avoids this. The pattern can be used with ES5 syntax if you want.

If you implement this pattern, you may find that the problem has gone away, or at least you will be able to see clearer where the cause might be.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.