2015-02-03 17 views
5

Io uso Eclipse JDT per formattare i miei file Java generato come di seguito:Come utilizzare a livello di codice il formattatore del codice IDEA Intellij?

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(); 
} 

Ma la domanda è: come posso utilizzare il codice Idea formattatore API Intellij di programmazione di cui sopra? Jetbrains ha introdotto qualche API?

risposta

1

Sì, è possibile formattare il codice a livello di programmazione in IntelliJ.

La chiave per fare questo è:

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

Ho un plugin di esempio che fa proprio questo. Dai un'occhiata allo here.

Problemi correlati