使用JDT以编程方式格式化源代码

chr*_*mel 7 java eclipse eclipse-jdt

我正在用JDT生成一些类.之后我想格式化整个ICompilationUnit,就像我在没有选择的情况下在打开的编辑器中按下Ctrl + Shift + F(源>格式)一样.

JDT中用于以编程方式格式化源代码的API的任何指针都非常受欢迎.

另外:我试过这样,但代码没有改变.我在忙什么?

private void formatUnitSourceCode(ICompilationUnit targetUnit, IProgressMonitor monitor) throws JavaModelException {
    CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
    TextEdit formatEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, targetUnit.getSource(), 0, targetUnit.getSource().length(), 0, null);
    targetUnit.applyTextEdit(formatEdit, monitor);
}
Run Code Online (Sandbox Code Playgroud)

chr*_*mel 6

这可能是一个错误,但是在Elcipse 4.2.2中使用JDK,有必要创建ICompilationUnit的工作副本,以便将TextEdit应用于该文件.

    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));
Run Code Online (Sandbox Code Playgroud)

格式化本身就像这样:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)