if (doc.getLength() == 0) return;
StringBuffer text = new StringBuffer(doc.get());
String anchor = getAnchorString(text);
ISourceViewer viewer = getEditor().getViewer();
int anchorOffset = getAnchorOffset(viewer, doc);
// insert an anchor comment at the end of the line with carret
// we'll find it back to reposition the caret after reformatting
text.insert(anchorOffset, anchor);
String formattedText = runFormatter(text);
if (formattedText == null ||
formattedText.equals(text.toString()) ||
formattedText.equals(anchor))
{
return;
}
StringBuffer newText = new StringBuffer(formattedText);
anchorOffset = newText.indexOf(anchor);
if (anchorOffset > 0)
{
// remove the anchor comment and the preceeding whitespace
// which might have been inserted by perltidy
int len = anchor.length() + 1;
anchorOffset--;
while (anchorOffset >= 0 &&
Character.isWhitespace(newText.charAt(anchorOffset)))
{
anchorOffset--;
len++;
}
newText.delete(anchorOffset+1, anchorOffset+len);
}
else
anchorOffset = 0;
doc.set(newText.toString());
viewer.setSelectedRange(anchorOffset, 0);
viewer.revealRange(anchorOffset, 0);
}