eclipseeclipse-formatter

Eclipse Formatter isn't indenting correctly


We are using the Java Conventions [built-in] formatter for our Eclipse projects. The code looks as expected after formatting and indents correctly when viewing it in Eclipse.

What we've noticed is that if we open the file in Notepad++ (Or other apps) the indentation is actually incorrect. E.g. The method body has the same indentation as the method. Also if code is copied from Eclipse it isn't indented correctly.

Example 1

In Eclipse

class Example {

    public static void main(String args[]) {
        System.out.println("Hello World!");
    }
}

In Notepad++

class Example {

public static void main(String args[]) {
    System.out.println("Hello World!");
}
}

Example 2

In Eclipse

public static void main(String args[]) {
    System.out.println("Hello World!");
}

In Notepad++

public static void main(String args[]) {
System.out.println("Hello World!");
}

Is this behaviour expected?

Screenshot of spaces/tabs

enter image description here

All Characters

enter image description here


Solution

  • The default Eclipse formatter profile, Eclipse [Built-in], displays tabs with a width of 4 spaces.

    In contrast, the Java Conventions [Built-in], displays tabs with a width of 8 spaces.

    This is given by the Code Conventions for the Java Programming Language, 4 - Indentation as follows (highlighting by me):

    Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).

    These days, the original Java Code Conventions with its mixed tab policy and a tab width of 8 spaces is rarely used. You may consider switching to the Eclipse [Built-in] formatter profile.