2013-04-15 21 views
6

Generuję klasy z JDT. Następnie chciałbym sformatować całą ICompilationUnit, tak jakbym naciskał Ctrl + Shift + F (Źródło> Format) w otwartym Edytorze bez zaznaczenia.Formatowanie kodu źródłowego programowo za pomocą JDT

Wszelkie wskaźniki API w JDT w celu programowego formatowania kodu źródłowego są wysoko cenione.

Dodawanie: Próbowałem to tak, ale kod nie został zmieniony. Co ja robię?

private void formatUnitSourceCode(ICompilationUnit targetUnit, IProgressMonitor monitor) throws JavaModelException { 
    CodeFormatter formatter = ToolFactory.createCodeFormatter(null); 
    TextEdit formatEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, targetUnit.getSource(), 0, targetUnit.getSource().length(), 0, null); 
    targetUnit.applyTextEdit(formatEdit, monitor); 
} 

Odpowiedz

5

To może być błąd, ale używając JDK w Elcipse 4.2.2, konieczne jest utworzenie roboczej kopii ICompilationUnit w celu zastosowania TextEdit do pliku.

targetUnit.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); 
    ... do work on the source file ... 
    formatUnitSourceCode(targetUnit, new SubProgressMonitor(monitor, 1)); 
    targetUnit.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1)); 

Samo formatowanie odbywa się to tak:

public static void formatUnitSourceCode(ICompilationUnit unit, IProgressMonitor monitor) throws JavaModelException { 
    CodeFormatter formatter = ToolFactory.createCodeFormatter(null); 
    ISourceRange range = unit.getSourceRange(); 
    TextEdit formatEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, unit.getSource(), range.getOffset(), range.getLength(), 0, null); 
    if (formatEdit != null && formatEdit.hasChildren()) { 
     unit.applyTextEdit(formatEdit, monitor); 
    } else { 
     monitor.done(); 
    } 
} 
2

Kiedy generating some classes by using JDT, można umieścić "\ t" S w kodzie źródłowym. Lub podoba Ci się to, co zrobiłeś, używając programu do formatowania kodu. Ja testowałem następujący kod:

public static void main(String[] args) 
{ 
    String code = "public class TestFormatter{public static void main(String[] args){System.out.println(\"Hello World\");}}"; 
    CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null); 

    TextEdit textEdit = codeFormatter.format(CodeFormatter.K_UNKNOWN, code, 0,code.length(),0,null); 
    IDocument doc = new Document(code); 
    try { 
     textEdit.apply(doc); 
     System.out.println(doc.get()); 
    } catch (MalformedTreeException e) { 
     e.printStackTrace(); 
    } catch (BadLocationException e) { 
     e.printStackTrace(); 
    } 
} 

Sposób apply() załatwia sprawę tutaj.

+0

To pomaga, ale doens't elegancko rozwiązać wszystkich pożądanego formatowania. I. e. trzeba ręcznie łamać długie deklaracje metod z dużą ilością parametrów. –

+0

Bardzo interesujący problem. Widzę, co robisz, i właśnie zredagowałem swoją odpowiedź. Dzięki. – Ryan

+0

Cześć Ryan, zmieniłem powyższy kod, aby użyć 'CodeFormatter.K_UNKNOWN', ale to też nie działało. Później sprawdziłem 'targetUnit.getSource()' po wywołaniu 'targetUnit.applyTextEdit' (które wykonuje' apply() 'na wewnętrznym' IDocument' z 'ICompilationUnit'), i dziwne, że zmiany wydają się być zastosowane. Ale nie są one stosowane do pliku. Czy to błąd, czy coś mi brakuje? –

0

używam następujący sposób sformatować plik źródłowy Java

public static void formatSource(ICompilationUnit cu, IProgressMonitor progressMonitor) throws JavaModelException{ 
    String source = cu.getSource(); 
    IJavaProject javaProject = cu.getJavaProject(); 

    Map options = javaProject.getOptions(true); 


      // Instantiate the default code formatter with the given options 
      final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options); 


      final TextEdit edit = codeFormatter.format(
       CodeFormatter.K_COMPILATION_UNIT, // format a compilation unit 
       source, // source to format 
       0, // starting position 
       source.length(), // length 
       0, // initial indentation 
       System.getProperty("line.separator") // line separator 
      );   

      cu.becomeWorkingCopy(progressMonitor); 
      try { 
       cu.applyTextEdit(edit, progressMonitor); 
       //cu.reconcile(); 
       cu.commitWorkingCopy(true, progressMonitor); 
       //cu.save(progressMonitor, false); 

       JavaUI.openInEditor(cu); 


      } catch (MalformedTreeException e) { 
       e.printStackTrace(); 
      } catch (PartInitException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

} 
Powiązane problemy