pátek 20. ledna 2012

Eclipse: Manual and Automatic Code Formatting

I like automatic code formatting in the Eclipse IDE. For Java see the settings in Window -> Preferences -> Java -> Code Style -> Formatter. I Just hit CTRL+SHIFT+F time from time and let the IDE do the boring job for me.

Occasionally, I want the different result then the Eclipse Formatter produce. Especially when a method has many parameters. Sometimes I like to have all of them on one line, sometimes I like to break them into multiple times. Of course, the Eclipse automatic formatter cannot be configured to meet wishes.

The Eclipse formatter has a nice option On/Off Tags:
  • @formatter:off
  • @formatter:on
But it's tedious and ugly to write these tags into the code. (Even Code templates does not simply usage of On/Off Tags very much). Much more simpler solution is to append the Java comment // ant the and of line, which you want to break. For example, I have configured the Eclipse formatter to have all method parameters on a single line. But when I write
this.someMethod(param1, //
    param2, //
    param3, //
    param4, //
    param5);
Then the CTRL+SHIFT+F reformatting let this piece of the code as is.