onOwnLine = true;
// Compress any whitespace before the line delimiter
if (start != end) {
int replaceLength = end - start;
textEdit.addChild(new ReplaceEdit(start + startOffset, replaceLength, EMPTY));
start = end = i;
}
}
}
else {
// Transitioned to a new word
if (start != end) {
int replaceLength = end - start;
if (onOwnLine) {
// If content is on its own line, replace leading whitespace with proper indent
textEdit.addChild(new ReplaceEdit(start + startOffset, replaceLength, indent));
resultLength -= (replaceLength - indent.length());
onOwnLine = false;
}
else if (!(replaceLength == 1 && text.charAt(start) == ' ')) {
textEdit.addChild(new ReplaceEdit(start + startOffset, replaceLength, SPACE));
resultLength -= (replaceLength - 1);
}
start = end = i;
// Make sure the word starts on a new line
if (resultLength > lineWidth) {
lineWidth = fPreferences.getMaxLineWidth();
resultLength = 0;
textEdit.addChild(new InsertEdit(start + startOffset, getLineDelimiter(region) + indent));
}
}
// Word is immediately after line delimiters, indent appropriately
if (onOwnLine) {
textEdit.addChild(new InsertEdit(i + startOffset, indent));
onOwnLine = false;
}
resultLength++;
}
}
// Clean up any dangling whitespace
int replaceLength = end - start;
indent = getIndentString(indentLevel);
if (replaceLength == 0) { // No trailing whitespace
textEdit.addChild(new InsertEdit(length + startOffset, (onOwnLine) ? indent : SPACE));
}
else {
String whitespace = text.substring(start);
String replacement = (onOwnLine) ? indent : SPACE;
if (!whitespace.equals(replacement)) {
textEdit.addChild(new ReplaceEdit(start + startOffset, replaceLength, replacement));
}
}
}