使用JDT以编程方式格式化源代码 [英] Formatting Source Code programmatically with JDT
问题描述
我正在使用JDT生成一些类。之后我想格式化整个ICompilationUnit,就好像我在一个没有选择的开放式编辑器中按Ctrl + Shift + F(Source> Format)。
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 without a selection.
任何指针JDT中的API以编程方式格式化源代码非常感谢。
Any pointers for the API in JDT to format the source code programmatically is highly appreciated.
添加:我试过这样,但代码没有改变。我在做什么?
Addition: I tried it like this, but the code isn't changed. What am I mssing?
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);
}
推荐答案
这可能是一个bug,但是在Elcipse 4.2.2中使用JDK,有必要创建ICompilationUnit的工作副本,以便将TextEdit应用于该文件。
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));
格式化本身就像这样:
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();
}
}
这篇关于使用JDT以编程方式格式化源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!