如何以编程方式使用Intellij IDEA代码格式化程序?

Poo*_*oya 6 java formatting intellij-idea eclipse-jdt

我使用Eclipse jdt来格式化我生成的java文件,如下所示:

public String format(String code)
        throws MalformedTreeException, BadLocationException {
    Map options = new java.util.HashMap();
    options.put(JavaCore.COMPILER_SOURCE, "1.5");
    options.put(JavaCore.COMPILER_COMPLIANCE, "1.5");
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.5");

    DefaultCodeFormatterOptions cfOptions =
            DefaultCodeFormatterOptions.getDefaultSettings();
    cfOptions.insert_new_line_after_annotation = false;
    cfOptions.comment_insert_new_line_for_parameter = true;

    cfOptions.blank_lines_before_method = 1;
    cfOptions.number_of_empty_lines_to_preserve= 1;

    cfOptions.tab_char = DefaultCodeFormatterOptions.SPACE;

    CodeFormatter cf = new DefaultCodeFormatter(cfOptions, options);

    TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, code, 0,
            code.length(), 0, null);
    IDocument dc = new Document(code);

    te.apply(dc);
    return dc.get();
}
Run Code Online (Sandbox Code Playgroud)

但问题是我如何以编程方式使用Intellij Idea代码格式化程序API?Jetbrains是否推出了任何API?

pil*_*avi 6

是的,您可以在 IntelliJ 中以编程方式格式化代码。

做到这一点的关键是:

CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
PsiElement psiFile = event.getData(LangDataKeys.PSI_FILE);
styleManager.reformat(psiFile);
Run Code Online (Sandbox Code Playgroud)

我有一个示例插件就是这样做的。在这里查看一下。