Updated script to deal with empty lines in the text file.
(function () {
var condition;
var riskWords;
// Remove and recreate the condition if it exists
// so that words removed from the list are
// 'unrisked' in the text
function getCondition () {
var c = app.documents[0].conditions.item('Risk word');
if (c.isValid) {
var p = c.properties;
// This is quicker than removing the highlights in the text
c.remove();
c = app.documents[0].conditions.add(p);
} else {
app.documents[0].conditionalTextPreferences.showConditionIndicators =
ConditionIndicatorMode.SHOW_INDICATORS;
c = app.documents[0].conditions.add ({
name: 'Risk word',
indicatorColor: UIColors.YELLOW,
indicatorMethod: ConditionIndicatorMethod.useHighlight,
});
}
return c;
}
function highlight (word) {
app.findTextPreferences.findWhat = word;
var w = app.documents[0].findText();
for (var i = w.length-1; i >= 0; i--) {
w[i].applyConditions (condition);
}
}
function getWords () {
var f = File (app.documents[0].filePath + '/risk-words.txt');
if (f.exists) {
f.encoding = ('utf-8');
f.open('r');
var w = f.read().replace(/+$/,'').split(/[\r]/);
f.close();
return w;
}
return null;
}
app.findTextPreferences = app.findChangeTextOptions = null;
app.findChangeTextOptions.properties = {
caseSensitive: false,
wholeWord: true,
includeLockedStoriesForFind: false,
}
condition = getCondition();
riskWords = getWords();
if (!riskWords) {
alert ('Risk words not found');
exit();
}
for (var i = riskWords.length-1; i >= 0; i--) {
highlight (riskWords[i]);
}
}());