Search code examples
javaeclipsecommentscode-formattingauto-indent

Stop Eclipse from indenting comments created with Ctrl-/


I often need to comment out a line temporarily (e.g., when debugging). This is easily done with Ctrl-/ and results in // at the beginning of the line:

public class Foo {
    int foo(int a, int b) {
        int sum = a + b;
//        System.out.println("debug: sum = " + sum);
        return sum;
    }
}

I like the placement of the // because it stands out, so it's easy to see which lines you might want to uncomment (as opposed to "English description" comments that shouldn't ever be uncommented).

The problem is, when I later indent my code with Ctrl-A (select all) followed by Ctrl-I (indent selection), the comment becomes super ugly:

public class Foo {
    int foo(int a, int b) {
        int sum = a + b;
        //        System.out.println("debug: sum = " + sum);
        return sum;
    }
}

If I instead format the code with Shift-Ctrl-F, the result looks better, but the // is no longer at the beginning of the line:

public class Foo {
    int foo(int a, int b) {
        int sum = a + b;
        // System.out.println("debug: sum = " + sum);
        return sum;
    }
}

Furthermore, in both scenarios, when I later uncomment the line with Ctrl-/, the line is no longer indented correctly.

My question: how can I get Eclipse's indenter and formatter to stop altering line comments that I've created with Ctrl-/?


Solution

    1. Go to Window -> Preferences -> Java -> Code Style -> Formatter.
    2. Select the profile you want to use/change and click the Edit button.
    3. Go to the Comments tab and look under General settings.
    4. For the indenter issue, check the option "Never indent line comments on first column".
    5. For the formatter issue, uncheck the option "Format line comments on first column".
    6. If you're modifying a built-in profile, enter a new Profile name.
    7. Apply the changes.

    Now, line comments created with ctrl-/ will not be modified by indenting (ctrl-A followed by ctrl-I) or formatting (shift-ctrl-F). This also applies to any other line comment where // is at the beginning of the line.

    Note: Using ctrl-I only on the commented line will keep the // at the beginning of the line and move the rest of the comment to be aligned with the line above.