google-java-format icon indicating copy to clipboard operation
google-java-format copied to clipboard

avoid adding space on // comments?

Open maxandersen opened this issue 11 months ago • 3 comments

its a special case but in jbang I use //JAVA , //DEPS etc as special markers.

I tried using @formatter:off but seem to have no effect.

///usr/bin/env jbang "$0" "$@" ; exit $?
// @formatter:off
//JAVA 21+
//PREVIEW
//DEPS org.imgscalr:imgscalr-lib:4.2

class test {

}

gets turned into:

/// usr/bin/env jbang "$0" "$@" ; exit $?
// @formatter:off
// JAVA 21+
// PREVIEW
// DEPS org.imgscalr:imgscalr-lib:4.2

the first line is a case of #1218 but the others below - how does one tell google-java-format not to mess with those?

maxandersen avatar Jan 07 '25 09:01 maxandersen

Fwiw: https://github.com/google/google-java-format/wiki/FAQ#principles-and-goals

tbroyer avatar Jan 07 '25 10:01 tbroyer

@maxandersen FYI the first problem (///usr/bin/env jbang ...) is what I previously raised #1215 about, perhaps you would like to Subscribe (Watch) that issue, engage on it if you have anything to add (there's an "interesting" question re. JEP 467 Markdown JavaDoc...), or perhaps even consider contributing?

The other part, re. //JAVA 21+ to // JAVA 21+ etc. is interesting, and perhaps what this issue should be about. How (what "algorithm") would a formatter "know" that it should not touch such lines - but that it does need to insert a space in something like //this function...\nvoid foo(); - what "rule" identifies this case? It "feels" like a very specific convention - but perhaps you know how other code formatting tools (Checkstyle?) handle this?

vorburger avatar Jan 10 '25 15:01 vorburger

how does one tell google-java-format not to mess with those?

@maxandersen , an additional option in the project build file must be enabled. In Gradle this is done through the toggleOffOn() option.

Gradle

    java {
        googleJavaFormat("1.28.0").aosp()
        toggleOffOn()
    }

Maven

        <configuration>
          <java>
            <googleJavaFormat>
              <style>AOSP</style>
            </googleJavaFormat>
            <toggleOffOn />
          </java>
        </configuration>

JBang Java example file:

///usr/bin/env jbang "$0" "$@" ; exit $?

// spotless:off
//DEPS com.google.code.gson:gson:2.13.1
//DEPS ...
//JAVA 21
// spotless:on

// more java code

All that remains to be solved is for GJF to ignore the first line of a Java file if it starts with /// then we have a home run.

wfouche avatar Sep 12 '25 09:09 wfouche