8

I use Eclipse jdt to format my generated java files as below :

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? Has Jetbrains introduced any API?

Pooya
  • 4,385
  • 6
  • 45
  • 73

1 Answers1

5

Yes, you can programmatically format code in 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.

pillravi
  • 4,035
  • 5
  • 19
  • 33
  • I am trying to format my generated Kotlin files but without any editor. I have tried that but it is not working. Any other way around? – Abdul Feb 03 '22 at 05:41