Archive for the 'code formatting' Category

I was wondering if I could use the Eclipse Code Formatter from inside my code … so, the logical thing to do was to ask on stackoverflow, and see if anyone knew how to do that. Thanks to VonC‘s answer, I found out about the CodeFormatter class … and 10 jars and 2 hours later, I’ve got it working.

Here’s how I did it.

CodeFormatter is an abstract class, which means you can’t instantiate it directly. So, I started to search about classes derived from it, and so I found out about DefaultCodeFormatter, which I presumed was what I was looking for. I was right.

I used the CodeFormatter.K_UNKNOWN constant for the formatting, because I was thinking that the CodeFormatter will “deduce” the type of code I’ve passed it. I’m not really sure what K_UNKNOWN does, but it seems to work well with the code I’ve tried.

So … the DefaultCodeFormatter returned a TextEdit object as the result of the code formatting.
I was kind of hoping that it’s toString method would give me the code. Instead, I found out it had several ReplaceEdit children nodes. I tried to iterate over each of the children and print their text using their getText, but they wouldn’t “show me the code” 🙂 . I thought “TextEdit’s apply method sounds interesting. Let’s see what it does”. Checking it’s method signature :

apply(IDocument document)

revealed a IDocument parameter. I was hoping it would be easy to create a Document object, and that I wouldn’t need any other “eclipse objects”. Turns out it was easy. There is a Document implementation, that has a String constructor :

Document(String initialContent)

I applied the TextEdit to the document, and hoped for the best. The eclipse console printed out nicely formatted code. WIN !