Eclipse JDT: Call 'correct indentation' programmatically?
Asked Answered
K

2

6

I am working on an Eclipse plugin that modifies Java code in a user's project.

Basically the result of this plugin is that Java annotations are added to some methods, so

void foo() { ... }

becomes

@MyAnnotation
void foo() { ... }

Except that it doesn't quite look like that; the indentation on the newly inserted annotation is wack (specifically, the new annotation is all the way to the left-hand side of the line). I'd like to make all my changes to the file, and then programmatically call "Correct Indentation."

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

Thanks!

Kingsbury answered 20/5, 2010 at 12:34 Comment(1)
Looks like a good starting point may be: org.eclipse.jdt.core.formatter.CodeFormatterApplicationKingsbury
K
6

Well I think I may have figured out the solution I want. Guess I should have spend more time searching before asking... but for future reference, here's what I did! The good stuff was in the 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 reformats the entire file. There are other options if you need to reformat less...

Kingsbury answered 20/5, 2010 at 13:10 Comment(1)
i guess this will use the default formatter. have you figured out how to specify another formatter?Escapee
A
-1

It's probably easier to add the indentation as you process the Java code.

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

Application answered 20/5, 2010 at 12:42 Comment(2)
Thanks Gilbert, but actually I didn't read the line... I get the method location from MethodDeclaration.getStartPosition() where MethodDeclaration is in the package org.eclipse.jdt.core.dom. Now I could go back and copy what's before the method declaration from the start of the line, but I don't want to copy a bunch of junk if the programmer's using some alternative formatting...Kingsbury
Ok, I've not seen these org.eclipse.jdt packages before. How are you adding your annotation to the Java source code?Application

© 2022 - 2024 — McMap. All rights reserved.