Eclipse JDT: Programmatically "Correct Indentation"?

I am working on an Eclipse plugin that modifies Java code in a custom project.

The main result of this plugin is that Java annotations are added to some methods, therefore

void foo() { ... } 

becomes

 @MyAnnotation void foo() { ... } 

Except that this is not entirely true; the indentation in the recently inserted annotation is inactive (in particular, the new annotation fully fits the left side of the line). I would like to make all my changes to the file, and then programmatically call "Fix Indentation."

Does anyone know how to do this? I can't find the answer here or in the JDT forums, and all classes that look relevant (IndentAction, JavaIndenter) are in internal packages that I shouldn't use ...

Thanks!

+6
java eclipse eclipse-jdt
source share
2 answers

Ok, I think I might have figured out what solution I want. I think I should have looked longer before asking ... but for future reference, here's what I did! Good stuff was in ToolFactory ...

 import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.text.edits.TextEdit; import org.eclipse.jdt.core.ICompilationUnit; ... ICompilationUnit cu = ... ... CodeFormatter formatter = ToolFactory.createCodeFormatter(null); ISourceRange range = cu.getSourceRange(); TextEdit indent_edit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, cu.getSource(), range.getOffset(), range.getLength(), 0, null); cu.applyTextEdit(indent_edit, null); cu.reconcile(); 

This will reformat the entire file. There are other options if you need to reformat less ...

+6
source share

It may be easier to add indentation while processing Java code.

The Eclipse plugin had to read the void foo() { ... } to know to add @MyAnnotation , right? Just get the indentation from the Java string and add the annotation to the indentation.

-one
source share

All Articles