Formatting Source Code programmatically with JDT

前端 未结 3 1425
-上瘾入骨i
-上瘾入骨i 2021-01-05 09:09

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

3条回答
  •  臣服心动
    2021-01-05 09:53

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

提交回复
热议问题