tags:

views:

150

answers:

2

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 !

+3  A: 

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!

VonC
I need to include it in my code. Is that possible?
Geo
"as a standalone class", but in a java program! Right, I understand now ;) Looking into it right now..
VonC
english is not my primary language. I find that some ideas are complicated for me to express :). Sorry.
Geo
Well... count me in too (in the "english is not my primary language") ;) I did find the right class, but I am still unsure how to use that CodeFormatter for *java* format. Let me know if it helps.
VonC
I'll give it a try and post the results. Thanks!
Geo
I've managed to get it to work. I'm writing a blog post about it. I'll post the link here when I'm done.
Geo
Excellent! I look forward reading about it. Thank you for the feedback :)
VonC
I've added the link to the question's body. Thanks!
Geo
+1  A: 

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);
Nels Beckman