我正在开发一个 Eclipse 插件,它可以修改用户项目中的 Java 代码。
基本上这个插件的结果就是在一些方法上加了Java注解,所以
void foo() { ... }
成为
@MyAnnotation
void foo() { ... }
除了它看起来不太像;新插入的注释的缩进很奇怪(具体来说,新注释一直到该行的左侧)。我想对文件进行所有更改,然后以编程方式调用“正确缩进”。
有人知道怎么做吗?我在这里或 JDT 论坛上找不到答案,所有看起来相关的类(IndentAction、JavaIndenter)都在我不应该使用的内部包中...
谢谢!
最佳答案
好吧,我想我可能已经找到了我想要的解决方案。我想我应该在询问之前花更多时间进行搜索......但是为了将来引用,这就是我所做的!好东西在 ToolFactory 中......
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.jdt.core.ICompilationUnit;
...
ICompilationUnit cu = ...
...
CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
ISourceRange range = cu.getSourceRange();
TextEdit indent_edit =
formatter.format(CodeFormatter.K_COMPILATION_UNIT,
cu.getSource(), range.getOffset(), range.getLength(), 0, null);
cu.applyTextEdit(indent_edit, null);
cu.reconcile();
这将重新格式化整个文件。如果您需要重新格式化 less,还有其他选择...
关于java - eclipse JDT : Call 'correct indentation' programmatically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2873678/