Formatting Source Code programmatically with JDT
This could be a bug, but using the JDK in Elcipse 4.2.2, it is necessary to create a working copy of the ICompilationUnit in order to apply a TextEdit to the file.
targetUnit.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
... do work on the source file ...
formatUnitSourceCode(targetUnit, new SubProgressMonitor(monitor, 1));
targetUnit.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
The formatting itself is done like this:
public static void formatUnitSourceCode(ICompilationUnit unit, IProgressMonitor monitor) throws JavaModelException {
CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
ISourceRange range = unit.getSourceRange();
TextEdit formatEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, unit.getSource(), range.getOffset(), range.getLength(), 0, null);
if (formatEdit != null && formatEdit.hasChildren()) {
unit.applyTextEdit(formatEdit, monitor);
} else {
monitor.done();
}
}
When generating some classes by using JDT, you can put "\t"s in your source code. Or like what you did, using code formatter. I have tested the following code:
public static void main(String[] args)
{
String code = "public class TestFormatter{public static void main(String[] args){System.out.println(\"Hello World\");}}";
CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null);
TextEdit textEdit = codeFormatter.format(CodeFormatter.K_UNKNOWN, code, 0,code.length(),0,null);
IDocument doc = new Document(code);
try {
textEdit.apply(doc);
System.out.println(doc.get());
} catch (MalformedTreeException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
}
The apply()
method does the trick here.