2015-02-03 4 views
5

나는 이클립스 JDT는 다음과 같이 내 생성 된 자바 파일의 형식을 사용프로그래밍 방식으로 Intellij IDEA 코드 포맷터를 사용하는 방법?

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

하지만 문제는 내가 위와 같이 프로그래밍 인 IntelliJ 아이디어 코드 포맷터 API를 사용할 수있는 방법인가? Jetbrains는 API를 소개 했습니까?

답변

1

예, 프로그래밍 방식으로 IntelliJ에서 코드의 서식을 지정할 수 있습니다.

이 일의 핵심은 다음과 같습니다

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

난 그냥이 작업을 수행하는 예 플러그인을 가지고있다. 그것을 확인해보십시오 here.