By Greg Mattes


2009-11-30 16:38:36 8 Comments

I've got some Java code with SQL statements written as Java strings (please no OR/M flamewars, the embedded SQL is what it is - not my decision).

I've broken the SQL statements semantically into several concatenated strings over several lines of code for ease of maintenance. So instead of something like:

String query = "SELECT FOO, BAR, BAZ FROM ABC WHERE BAR > 4";

I have something like:

String query =
    "SELECT FOO, BAR, BAZ" +
    "  FROM ABC          " +
    " WHERE BAR > 4      ";

This style makes the SQL much easier to read and maintain (IMHO), especially for larger queries. For example, I can put my editor into "overwrite" mode and modify the text in-place fairly easily.

Note that this issue generalizes beyond the particular example of SQL. Any code that is written with any vertical formatting, particularly tabular constructs, is susceptible to destruction by a pretty printer.

Now, some project members use the Eclipse editor and the semantic formatting is often destroyed when they format an entire source file.

Is there a way to instruct Eclipse to ignore certain lines of source with respect to formatting?

I'm looking for something like a special comment that toggles the Eclipse formatter. Ideally, such a comment could be configurable to be whatever we choose, and other formatters could be programmed to respect it as well:

// STOP-ECLIPSE-FORMATTING
String query =
    "SELECT FOO, BAR, BAZ" +
    "  FROM ABC          " +
    " WHERE BAR > 4      ";
// START-ECLIPSE-FORMATTING

Obviously, one "solution" is to have our team members standardize on some external formatter like Jalopy or JIndent, but that's not what this question is about (also, not my decision on this project): I'm specifically looking for a way to avoid the Eclipse formatter on an ad-hoc basis.

Ideally, a solution will allow me to insert instructions for the Eclipse formatter without requiring team members using Eclipse to do any IDE reconfiguration (other than possibly choosing a formatter agnostic command comment: STOP-ECLIPSE-FORMATTINGSTOP-FORMATTING).

12 comments

@Tomas Bjerre 2017-06-01 19:45:37

The phantom comments, adding // where you want new lines, are great!

  1. The @formatter: off adds a reference from the code to the editor. The code should, in my opinion, never have such references.

  2. The phantom comments (//) will work regardless of the formatting tool used. Regardless of Eclipse or InteliJ or whatever editor you use. This even works with the very nice Google Java Format

  3. The phantom comments (//) will work all over your application. If you also have Javascript and perhaps use something like JSBeautifier. You can have similar code style also in the Javascript.

  4. Actually, you probably DO want formatting right? You want to remove mixed tab/space and trailing spaces. You want to indent the lines according to the code standard. What you DONT want is a long line. That, and only that, is what the phantom comment gives you!

@CPerkins 2009-11-30 16:50:14

If you put the plus sign on the beginning of the line, it formats differently:

String query = 
    "SELECT FOO, BAR, BAZ" 
    +    "  FROM ABC"           
    +    " WHERE BAR > 4";

@Greg Mattes 2009-11-30 19:01:26

This might be an interesting compromise. In general, I'd like to refrain from changing the formatting of the code too much due to some undesirable behavior of one tool. In this case, the string concatenation operators are more of an accident rather than the essence of what's going on with the SQL. That's why I prefer to write them at the end of each line. I feel that the SQL should be emphasized as the beginning of the line. But this may be a good way to go in the absence of a solution that lets me preserve my desired formatting. Thanks!

@CPerkins 2009-12-01 11:46:12

You're welcome. Actually, I've been putting my + signs at the front of lines for decades, and not to fool the formatter. I prefer them at the front, because it makes what's happening clearer to me: what's at the end of a line sometimes gets lost. It was the project standard someplace way back when we used woodburning compilers, and it's stuck with me.

@Evvo 2016-07-23 02:12:17

End each of the lines with a double slash "//". That will keep eclipse from moving them all onto the same line.

@xpmatteo 2010-07-28 14:17:36

Eclipse 3.6 allows you to turn off formatting by placing a special comment, like

// @formatter:off
...
// @formatter:on

The on/off features have to be turned "on" in Eclipse preferences: Java > Code Style > Formatter. Click on Edit, Off/On Tags, enable Enable Off/On tags.

It's also possible to change the magic strings in the preferences — check out the Eclipse 3.6 docs here.

More Information

Java > Code Style > Formatter > Edit > Off/On Tags

This preference allows you to define one tag to disable and one tag to enable the formatter (see the Off/On Tags tab in your formatter profile):

enter image description here

You also need to enable the flags from Java Formatting

@xpmatteo 2012-01-12 12:59:45

The "Never join lines" option that is mentioned elsewhere in this page is also very useful.

@Domenic D. 2012-08-13 19:31:00

The on/off features have to be turned "on". In Eclipse preferences: Java > Code Style > Formatter. Click on "Edit" button, "Off/On Tags", check off "Enable Off/On tags".

@Redsandro 2013-02-22 15:08:37

This isn't available in JavaScript Code Style preferences, where I have the exact opposite problem with formatting. :(

@Joseph Lust 2013-03-18 21:56:34

Teams should export a copy of Eclipse prefs (file) to their wiki and require everyone to use the same one. Works well for us. ;)

@Roy Truelove 2014-01-29 15:11:33

FYI I had to remove the space between the // and the @ sign to get this to work.

@theGamblerRises 2016-10-06 02:06:13

Is there any hotkey for this?

@elonderin 2017-07-18 21:42:36

@theGamblerRises: u can define a template that explands to the respective strings. i have done this myself and use foff and fon for this.

@nuoritoveri 2018-01-04 17:57:51

Thank you very much! This also works when using maven-formatter-plugin (I changed setting org.eclipse.jdt.core.formatter.use_on_off_tags manually in the formatter xml file).

@Renaud 2014-04-11 15:01:48

See this answer on SO.

There is another solution that you can use to suppress the formatting of specific block comments. Use /*- (note the hyphen) at the beginning of the block comment, and the formatting won't be affected if you format the rest of the file.

/*-
 * Here is a block comment with some very special
 * formatting that I want indent(1) to ignore.
 *
 *    one
 *        two
 *            three
 */

Source: Documentation at Oracle.

@Azim 2018-09-26 19:36:37

This is the best answer since it does not depend on the configuration of the user's IDE. Thanks.

@ZilWerks 2011-08-17 18:06:38

You have to turn on the ability to add the formatter tags. In the menubar go to:

Windows Preferences Java Code Style Formatter

Press the Edit button. Choose the last tab. Notice the On/Off box and enable them with a checkbox.

@ilinca 2014-07-31 14:30:29

Instead of turning the formatting off, you can configure it not to join already wrapped lines. Similar to Jitter's response, here's for Eclipse STS:

Properties → Java Code Style → Formatter → Enable project specific settings OR Configure Workspace Settings → Edit → Line Wrapping (tab) → check "Never join already wrapped lines"

Save, apply.

enter image description here

@Greg Mattes 2014-07-31 15:29:27

I think this would help for things like the SQL example, but I'm not sure that it would be sufficient for the general case of completely disabling the IDE formatter.

@Jonas Kongslund 2014-11-15 11:13:43

This solution is excellent when using the builder pattern and its relevance is certainly increased with the introduction of lambdas in Java 8.

@Robin 2012-08-15 15:02:10

@xpmatteo has the answer to disabling portions of code, but in addition to this, the default eclipse settings should be set to only format edited lines of code instead of the whole file.

Preferences->Java->Editor->Save Actions->Format Source Code->Format Edited Lines

This would have prevented it from happening in the first place since your coworkers are reformatting code they didn't actually change. This is a good practice to prevent mishaps that render diff on your source control useless (when an entire file is reformatted because of minor format setting differences).

It would also prevent the reformatting if the on/off tags option was turned off.

@kmccoy 2011-04-16 17:10:48

Alternative method: In Eclipse 3.6, under "Line Wrapping" then "General Settings" there is an option to "Never join already wrapped lines." This means the formatter will wrap long lines but not undo any wrapping you already have.

@Guus 2010-07-16 11:17:51

I'm using fixed width string-parts (padded with whitespace) to avoid having the formatter mess up my SQL string indentation. This gives you mixed results, and won't work where whitespace is not ignored as it is in SQL, but can be helpful.

    final String sql = "SELECT v.value FROM properties p               "
            + "JOIN property_values v ON p.property_id = v.property_id "
            + "WHERE p.product_id = ?                                  "
            + "AND v.value        IS NOT NULL                          ";

@Thomas Jung 2009-11-30 16:47:45

This hack works:

String x = "s" + //Formatter Hack
    "a" + //
    "c" + //
    "d";

I would suggest not to use the formatter. Bad code should look bad not artificially good. Good code takes time. You cannot cheat on quality. Formatting is part of source code quality.

@Francis Upton IV 2009-11-30 18:48:55

Not using the formatter is just a bad idea; the formatter helps to catch errors and keeps the code in a consistent state.

@Chris 2009-11-30 20:19:15

An interesting suggestion, but I don't see how formatting tells us whether code is good or not.

@Greg Mattes 2009-11-30 20:33:18

I think what he's saying is that he feels that poorly written, poorly formatted code should be kept as-is rather than formatting it in the hope of "improving it." Poorly written, poorly formatted code should "stick out" somehow so that it can be easily identified. Not quite sure that I totally agree, but I think that's the idea.

@Thomas Jung 2009-12-01 06:06:57

@Francis - Bugs: How can auto-formatted code finding bugs? Consistency: Consistency is a nice argument but overall code quality is more important. You can define a nice consistent process for hamburger flipping but it will never work for haute cuisine. Cooking a can be a reasonably complicated activity or trivial if you ignore enough facts. If you think that software development is like hamburger flipping tools enforcing consistency are for you. This is not an argument against formatting guide lines but if the developers don't care about these guidelines the won't care about other essentials.

@Per Wiklander 2012-04-22 02:22:29

My argument here: I write good code and I stick to the formatting guide lines. But I am LAZY. Why should I have to insert the correct amount of spaces and line breaks when I can write my five lines of sloppy code, press the format-button and be happy? AFTER I have formatted the code, using my tool that makes sure the result is always perfect, I am as nazi as anyone about the formatting. There is NO argument against sticking to the guide lines (other that that they may be particularly bad) if the formatting is just a kestroke away. All project members share the same code formatting settings.

@djjeck 2013-07-18 21:05:42

LOL, I disagree but it's funny.

@stolsvik 2013-12-30 10:08:12

This is completely misunderstanding the "Bad code should look not look good"-argument: Quite the opposite, a cleanly and consistently formatted source will help you see "code smells" much faster, as your internal parser can kick in and see "but that thing looks way to complicated!", or simply "that looks strange?".

@Demonblack 2017-06-22 15:44:17

I completely agree with not using automatic formatting.It isn't hard to format code properly, and the autoformatter always ends up breaking things that a proper developer would have formatted in a certain way to improve readability. The sheer amount of "how to stop autoformat from doing x?" questions should be proof enough of this. No machine can be better than someone who cares about what they're doing, and if someone doesn't care enough to put in a stupid tab they're likely ignoring much more important underlying issues and I'd rather they weren't messing with my codebase at all.

@jitter 2009-11-30 16:48:29

AFAIK from Eclipse 3.5 M4 on the formatter has an option "Never Join Lines" which preserves user lines breaks. Maybe that does what you want.

Else there is this ugly hack

String query = //
    "SELECT FOO, BAR, BAZ" + //
    "  FROM ABC"           + //
    " WHERE BAR > 4";

@Greg Mattes 2009-11-30 18:32:27

So in addition to setting the "Never Join Lines" option I also have to write these "phantom" comments? Shouldn't the "Never Join Lines" part work by itself?

@Chris 2009-11-30 20:17:35

Yes, of course it should. The phantom comments are an alternative approach (in case it doesn't exist, or you're stuck with an earlier version, etc.).

@jnt30 2010-07-19 12:14:48

I've used this approach in tandem with a custom formatting template in TOAD to allow me to strip the old SQL from JAVA code, reformat it and get all the extraneous comments and then throw it back into JAVA. It's a pain, but it's allowed us to auto-format on save our Java code now. Thanks for the suggestion!

@Christoffer Soop 2014-12-10 17:24:24

Without checking the "Never join lines" the on/off macros do not work for me - thanks!

Related Questions

Sponsored Content

28 Answered Questions

[SOLVED] How do I declare and initialize an array in Java?

  • 2009-07-29 14:22:27
  • bestattendance
  • 4563083 View
  • 2089 Score
  • 28 Answer
  • Tags:   java arrays

44 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

34 Answered Questions

[SOLVED] How do you assert that a certain exception is thrown in JUnit 4 tests?

43 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

58 Answered Questions

[SOLVED] How to create a memory leak in Java?

66 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 4111973 View
  • 3550 Score
  • 66 Answer
  • Tags:   java random integer

44 Answered Questions

[SOLVED] Can't start Eclipse - Java was started but returned exit code=13

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

30 Answered Questions

[SOLVED] How to avoid Java code in JSP files?

  • 2010-07-05 07:24:06
  • chmoelders
  • 288089 View
  • 1686 Score
  • 30 Answer
  • Tags:   java jsp scriptlet

7 Answered Questions

Sponsored Content