I have created a taskpane addin for word that runs a search and displays information about the results as a list to the user. When the user clicks on an item in the list I want to select the range in word to show the user the location of the item. The addin will then allow the user to perform additional tasks on the range, for example change the font colour, similar to the use in this previous question: (How can a range be used across different Word.run contexts?).
However, although it works for basic searches using one search term (outlined below), it does not work for a context.document.body.match function (to perform regex searches) or where multiple searches are run.
Working example
let results = [];
async function testSearch() {
if (results.length > 0) {
await Word.run(results, async (context) => {
results.forEach((range) => range.untrack());
results = [];
await context.sync();
});
}
cleartable();
await Word.run(async (context) => {
var i = 0
results = context.document.body.search('<[A-Z][A-Za-z]*>[ ]{1,}<[A-Z][A-Za-z]*>[A-Za-z ]*>', {matchWildcards: true});
results.load('text');
await context.sync();
for (const result of results.items) {
i++;
createtable(i, result.text)
}
results.track();
});
}
However, the following function, for example, does not appear to track the specified ranges:
async function batchsearch() {
const words = Object.keys(americanbody).join("|");
// Clear previous search results
if (results.length > 0) {
await Word.run(results, async (context) => {
results.forEach((range) => range.untrack());
results = [];
await context.sync();
});
}
cleartable();
await Word.run(async (context) => {
var i = 0;
const body = context.document.body;
const paragraphs = body.paragraphs;
paragraphs.load("text");
await context.sync();
const regex = new RegExp(`\\b(${words})\\b`, "ig");
const batchSize = 100;
let start = 0;
while (start < paragraphs.items.length) {
const end = Math.min(start + batchSize, paragraphs.items.length);
const chunk = paragraphs.items.slice(start, end);
for (const para of chunk) {
const matches = para.text.matchAll(regex);
for (const match of matches) {
const typo = match[0];
const correction = americanbody[typo];
i++;
createtable(i, typo, correction);
}
}
start += batchSize;
}
});
}
My question is whether there is a way to: a) track ranges of search results when using the match function; and b) continue to track results with multiple searches.
There seems to be very little attention given to this in the documentation. I have reviewed the follow book, which provided guidance but did not fully get me to where I want to go: (https://leanpub.com/buildingofficeaddins/).
Any help would be greatly appreciated.