2

I would like to highlight the search results similarly to what word's native search is doing. In other words, I don't want the search action to have side effects in the document, e.g. by changing the color of the font in the returned text ranges.

var searchResults = paragraph.search(searchValue);
context.load(searchResults, { select: 'text, font, style' });

desired functionality in word

Kim Major
  • 3,681
  • 1
  • 22
  • 20

1 Answers1

1

right now the only way you can achieve your scenario is by traversing the search results collection and change the highlight color for each range like I am showing on the snippet below. To undo this operation you need to do the search again and restore the highlights to white.

Word.run(function (context) {

            // Queue a command to search the document
            var searchResults = context.document.body.search('string you want to search for');
            context.load(searchResults, 'font');
            return context.sync().then(function () {
                console.log('Found count: ' + searchResults.items.length);

                // Queue a set of commands to change the font for each found item.
                for (var i = 0; i < searchResults.items.length; i++) {
                   
                    searchResults.items[i].font.highlightColor = '#FFFF00'; //Yellow
                   
                }

                return context.sync();
            });
        })
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});
Juan Balmori
  • 4,898
  • 1
  • 8
  • 17
  • The issue is that the highlight color is not necessarily white so I guess I have to track the original highlight. – Kim Major Oct 13 '16 at 21:14
  • do you know whether highlighting of search results is on the roadmap? It is a little disturbing that highlighting the search results affects the undo-stack. – Kim Major Oct 16 '16 at 09:31
  • you are right, we are actually adding support for this soon. you are going to be able to set highlight color to "null" in order to clear the highlight. but that's going to be public in a few months. regarding your request to highlight search results this is a great idea, it would be great if you can share it un our user voice channel https://officespdev.uservoice.com/forums/224641-general/category/163566-add-in-word – Juan Balmori Oct 18 '16 at 19:47