eclipseformattingideeclipse-formatter

Eclipse formatter: How to move comment between method name and open brace to always have open brace on same line as method declaration


I have code that looks like this, that I'm trying to format

Original code:

public int doThing(int a) // -incredibly useful comment here
{
    int ab = a+1;

    return ab;
}

I want it to look like this

public int doThing(int a) { // -incredibly useful comment here
    int ab = a+1;

    return ab;
}

If I try to turn on the Brace position -> Method Declaration -> Same line option and run the formatter, any code with a comment in the position "breaks" the formatter, and I get an output for my example that looks the same as the original code, but methods without a comment have the correct formatting (meaning the results are inconsistent).

Is it possible with the eclipse formatter to get the style I want? I'm trying to run it against a large amount of code, and would prefer not to have to fix these all manually to get a consistent brace position.


Solution

  • The problem here is that is not formatting but rewriting. Using File Search + regular expression + Replace could do that in bulk.

    Try this regex

    ^(\s*(?:public|private|protected)\s+[^(]+\([^)]*\))(\s*\/\/[^/]+)\R\s*\{
    

    On File Search ( Ctrl + H)

    File search box

    Hit Replace and use $1 { $2\n as replacement

    Replace box

    Code should compile after the refactoring.

    UPDATE: Fixed regex part that represents function arguments

    \([^)]*\)

    Full Regex matches these cases

    public int doSmthg() // coment here
    {
        return 1;
    }
    
    private String doSmthgElse(String arg) // coment here
        {
        return arg;
    }