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 wi
I use the following method to format a Java Source file
public static void formatSource(ICompilationUnit cu, IProgressMonitor progressMonitor) throws JavaModelException{
String source = cu.getSource();
IJavaProject javaProject = cu.getJavaProject();
Map options = javaProject.getOptions(true);
// Instantiate the default code formatter with the given options
final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);
final TextEdit edit = codeFormatter.format(
CodeFormatter.K_COMPILATION_UNIT, // format a compilation unit
source, // source to format
0, // starting position
source.length(), // length
0, // initial indentation
System.getProperty("line.separator") // line separator
);
cu.becomeWorkingCopy(progressMonitor);
try {
cu.applyTextEdit(edit, progressMonitor);
//cu.reconcile();
cu.commitWorkingCopy(true, progressMonitor);
//cu.save(progressMonitor, false);
JavaUI.openInEditor(cu);
} catch (MalformedTreeException e) {
e.printStackTrace();
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}