org.eclipse.jdt.core.formatter.CodeFormatter 用来格式化代码的类
摘录自开源软件源码
private static CodeFormatter getCodeFormatter() {
Map options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, DefaultCodeFormatterConstants.createAlignmentValue(true, DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE,
DefaultCodeFormatterConstants.INDENT_ON_COLUMN));
options.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, "160"); //$NON-NLS-1$
CodeFormatter codeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);
return codeFormatter;
}
public static String formatCode(String source) {
TextEdit edit = getCodeFormatter().format(CodeFormatter.K_UNKNOWN, source, 0, source.length(), 0, System.getProperty("line.separator")); //$NON-NLS-1$
if (edit != null) {
IDocument document = new Document(source);
try {
edit.apply(document);
return document.get();
} catch (Exception e) {
VisualSwingPlugin.getLogger().error(e);
}
}
return source;
}