// Current position in the message string.
int position = 0;
for (int idx = 0; idx < rangesList.size(); idx++) {
final HighlightRange range = rangesList.get(idx);
// Part before the next highlighted range of the message. (avoid empty chunks)
if (position != range.getStart()) {
list.add(new FieldChunk(message.substring(position, range.getStart()), true));
}
// The highlighted range of the message. Only allow the highlighting tags to be unescaped. The highlighted
// part can contain HTML elements so that should be escaped.
list.add(new FieldChunk("<span class=\"result-highlight\">",false));
list.add(new FieldChunk(message.substring(range.getStart(), range.getStart() + range.getLength()), true));
list.add(new FieldChunk("</span>", false));
if ((idx + 1) < rangesList.size() && rangesList.get(idx + 1) != null) {
// If there is another highlight range, add the part between the end of the current range and the start
// of the next range.
final HighlightRange nextRange = rangesList.get(idx + 1);
list.add(new FieldChunk(message.substring(range.getStart() + range.getLength(), nextRange.getStart()), true));
position = nextRange.getStart();
} else {
// If this range is the last, just add the rest of the message.
list.add(new FieldChunk(message.substring(range.getStart() + range.getLength()), true));
position = range.getStart() + range.getLength();