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

时间:2013-04-15 12:32:01

标签: 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);
}

3 个答案:

答案 0 :(得分:5)

这可能是一个错误,但是在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));

格式化本身就像这样:

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();
    }
}

答案 1 :(得分:2)

generating some classes by using JDT时,您可以在源代码中添加“\ t”。或者像你做的那样,使用代码格式化程序。我测试了以下代码:

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();
    }   
}

apply()方法可以解决这个问题。

答案 2 :(得分:0)

我使用以下方法格式化Java源文件

    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();
            }   

}