How can I make eclipse's autoformatter ignore a section of code?

Viewed 15981

i remember there being a way of marking a section of code in eclipse (special comment or annotation?) which made the autoformatter ignore that section. Or I may have drempt this...

Used mainly when I have strings which wrap onto several lines and i don't want the autoformatter to rearrange this.

7 Answers

You can wrap the code you don't want auto-formatted between these special comments:

normal code

/* @formatter:off */
strangely laid out code
/* @formatter:on */

normal code

Here's a basic usage example that makes a json string (slightly) more readable:

public class SomeTest {

    @Test
    public void can_deserialize_json() {
        /* @formatter:off */
        String json = "" +
        "{" +
        "   \"id\" : 123," +
        "   \"address1\" : blah," +
        "   \"shippingInfo\" : {" +
        "      \"trackingUrl\" : null," +
        "      \"price\" : 350" +
        "   }," +
        "   \"errorMessage\" : null" +
        "}";
        /* @formatter:on */
        MyClass.deserializeJson(json);
    }
}

I only know the answer for comments:

Eclipse is smart enough to only re-format the comments where the generated JavaDoc wouldn't change (i.e. where whitespace doesn't matter):

/**
 * foo <i>
 * bar </i>
 * 
 * <pre>
 *   foo
 * bar
 * </pre>
 */

will be reformatted into

/**
 * foo <i> bar </i>
 * 
 * <pre>
 *   foo
 * bar
 * </pre>
 */

Note how the content of the <pre> tags is not reformatted.

For long String literals, I'd suggest that they might be an indication that you should be externalizing some of them.

I am not sure about the exact feature you're referring to, but you can change the line wrap policy of expressions, which may help you with your strings problem. See:

Window->Preferences->Java->Code Style->Formatter

Click "Edit..." Button

Click "Line Wrapping" Tab

In the tree, choose Expressions->Assignments, then change the indent policy at the bottom of the window.

Of course there are myriad other options inside the formatter, you may find many of those useful as well for other rules, such as where to put your braces, or how to indent control blocks.

I just found this question because I'm also annoyed by the lack of this feature.

A small search showed this question and the following answer: Stop eclipse from line wrapping?

Eclipse 3.5 supports this. (It hit release candidate a a few days ago, so could be worth checking out)

Good luck with this! :)

You can mark the code you want to format and selct format with right mouse click in this section. This is a "whitlist" solution, perhaps it helps...

Related