简体   繁体   English

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

[英]How to programmatically use Intellij IDEA code formatter?

I use Eclipse jdt to format my generated java files as below : 我使用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();
}

But the question is how can I use the Intellij Idea code formatter API programmatically as above? 但是问题是,如何如上所述以编程方式使用Intellij Idea代码格式化程序API? Has Jetbrains introduced any API? Jetbrains是否引入了任何API?

Yes, you can programmatically format code in IntelliJ. 是的,您可以在IntelliJ中以编程方式设置代码格式。

The key to doing this is: 这样做的关键是:

CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
PsiElement psiFile = event.getData(LangDataKeys.PSI_FILE);
styleManager.reformat(psiFile);

I have an example plugin that does just this. 我有一个示例插件可以做到这一点。 Check it out here . 在这里查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM