Formatting Source Code programmatically with JDT [message #1042305] |
Tue, 16 April 2013 08:52 |
Christoph Keimel Messages: 482 Registered: December 2010 Location: Germany |
Senior Member |
|
|
Hello
I am generating some classes with JDT. Afterwards I would like to format the whole ICompilationUnit, just as if I pressed Ctrl+Shift+F (Source > Format) in an open Editor without a selection.
Currently I am using this code:
public static void formatUnitSourceCode(ICompilationUnit targetUnit, IProgressMonitor monitor) throws JavaModelException {
CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
String code = targetUnit.getSource();
TextEdit formatEdit = formatter.format(CodeFormatter.K_UNKNOWN, code, 0, code.length(), 0, null);
targetUnit.applyTextEdit(formatEdit, monitor);
}
Strangely, after the call to targetUnit.applyTextEdit, targetUnit.getSource() will show the changed source, but this change is not applied to the file. I verified, that targetUnit is not a workingCopy. Is this a bug or am I missing something?
Greetings
Christoph
|
|
|
Re: Formatting Source Code programmatically with JDT [message #1042329 is a reply to message #1042305] |
Tue, 16 April 2013 09:31 |
Christoph Keimel Messages: 482 Registered: December 2010 Location: Germany |
Senior Member |
|
|
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 {
monitor.beginTask(NLS.bind("Formatting Compilation Unit \"{0}\"", JavaElementLabels.getElementLabel(unit, JavaElementLabels.ALL_DEFAULT)), 2);
try {
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.hasChildren()) {
unit.applyTextEdit(formatEdit, new SubProgressMonitor(monitor, 1));
unit.reconcile(AST.JLS4, false, null, new SubProgressMonitor(monitor, 1));
}
} finally {
monitor.done();
}
}
|
|
|
Powered by
FUDForum. Page generated in 0.04180 seconds