int start= range.start;
int length= range.length;
int end= start + length;
if (fRanges.size() == 0) {
StyleRange defaultRange= getDefaultStyleRange();
if (defaultRange == null)
defaultRange= range;
defaultRange.start= start;
defaultRange.length= length;
applyStyle(range, defaultRange, merge);
fRanges.add(defaultRange);
} else {
IRegion rangeRegion= new Region(start, length);
int first= getFirstIndexInWindow(rangeRegion);
if (first == fRanges.size()) {
StyleRange defaultRange= getDefaultStyleRange();
if (defaultRange == null)
defaultRange= range;
defaultRange.start= start;
defaultRange.length= length;
applyStyle(range, defaultRange, merge);
fRanges.add(defaultRange);
return;
}
int last= getFirstIndexAfterWindow(rangeRegion);
for (int i= first; i < last && length > 0; i++) {
StyleRange current= (StyleRange)fRanges.get(i);
int currentStart= current.start;
int currentEnd= currentStart + current.length;
if (end <= currentStart) {
fRanges.add(i, range);
return;
}
if (start >= currentEnd)
continue;
StyleRange currentCopy= null;
if (end < currentEnd)
currentCopy= (StyleRange)current.clone();
if (start < currentStart) {
// Apply style to new default range and add it
StyleRange defaultRange= getDefaultStyleRange();
if (defaultRange == null)
defaultRange= new StyleRange();
defaultRange.start= start;
defaultRange.length= currentStart - start;
applyStyle(range, defaultRange, merge);
fRanges.add(i, defaultRange);
i++; last++;
// Apply style to first part of current range
current.length= Math.min(end, currentEnd) - currentStart;
applyStyle(range, current, merge);
}
if (start >= currentStart) {
// Shorten the current range
current.length= start - currentStart;
// Apply the style to the rest of the current range and add it
if (current.length > 0) {
current= (StyleRange)current.clone();
i++; last++;
fRanges.add(i, current);
}
applyStyle(range, current, merge);
current.start= start;
current.length= Math.min(end, currentEnd) - start;
}
if (end < currentEnd) {
// Add rest of current range
currentCopy.start= end;
currentCopy.length= currentEnd - end;
i++; last++;
fRanges.add(i, currentCopy);
}
// Update range
range.start= currentEnd;
range.length= Math.max(end - currentEnd, 0);
start= range.start;
length= range.length;
}
if (length > 0) {
// Apply style to new default range and add it
StyleRange defaultRange= getDefaultStyleRange();
if (defaultRange == null)
defaultRange= range;
defaultRange.start= start;
defaultRange.length= end - start;
applyStyle(range, defaultRange, merge);