Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the eclipse indenter from my code?

Tags:

java

eclipse

I noticed the eclipse indenter has support for the latest version of java, and it would be nice if I could use that class to indent generated java source code. Is there a way of integrating it ?

EDIT: I need to be able to include the code formatter in my code. No external calls.

EDIT2: I've managed to get it working. You can read the story here. Thanks VonC !

like image 759
Geo Avatar asked Sep 09 '26 22:09

Geo


2 Answers

You can try running the formatter as a standalone application (also detailed here).

eclipse -vm <path to virtual machine> -application org.eclipse.jdt.core.JavaCodeFormatter [ OPTIONS ] <files>

Try first to define formatting settings with eclipse IDE in order to achieve the right result, then export those settings, and use that configuration file in the eclipse.exe parameters.
Or see also "Generating a Config File for the Formatter Application"

eclipse [...] -config <myExportedSettings> 

In a java program, you can try to directly format by:

  • Creating an instance of CodeFormatter
  • Using the method void format(aString) on this instance to format aString. It will return the formatted string.

Thanks to Geo himself and his report in his blog entry, I now know you need to use DefaultCodeFormatter

    String code = "public class geo{public static void main(String[] args){System.out.println(\"geo\");}}";
    CodeFormatter cf = new DefaultCodeFormatter();

    TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, code, 0,code.length(),0,null);
    IDocument dc = new Document(code);
    try {
        te.apply(dc);
        System.out.println(dc.get());
    } catch (MalformedTreeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Again, full details in the blog entry. Thank you Geo for that feedback!


Thorbjørn Ravn Andersen mentions in the comments:

Maven2 Java Formatter Plugin v0.4 describes a maven plugin that allows Maven to invoke the Eclipse formatter.
As of 0.4 it invokes Eclipse 3.5 which does not support Java 8.

like image 199
VonC Avatar answered Sep 11 '26 11:09

VonC


Actually, there is one problem with VonC's answer: DefaultCodeFormatter is in an 'internal' package, and therefore should not be be used by clients!

I recently asked the same question here on stackoverflow, and came up with the answer a little while later.

In short, you need to use ToolFactory, as in

ToolFactory.createCodeFormatter(null);
like image 34
Nels Beckman Avatar answered Sep 11 '26 10:09

Nels Beckman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!