From 5eae2120ad7f1e73073ec57090438812aecfa05c Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Tue, 24 Nov 2026 14:24:00 +0300 Subject: [PATCH] Keep the code between @formatter:off and @formatter:on as written IntelliJ IDEA and Eclipse leave alone the code between these marker comments, such as a builder chain laid out by hand, and the IntelliJ plugin formatted it anyway. Honouring them in the plugin only would have the IDE keep what the command line, Gradle and Spotless then reformat, so the formatter honours them itself, in every tool alike. The markers are fixed and always on; the IDE's own setting for them does not apply. A region runs from the line of an off marker to the line of the next on marker, or to the end of the file. A marker is a line or block comment that starts with the marker text: the same text in a string, a Javadoc, a Markdown doc comment or later in a comment is none. Partial formatting widens a range to the statements or members around it, so getFormatReplacements leaves out every one that holds code of a region, and markers inside a statement keep all of it. StringWrapper does not reflow, join or indent the literals in those statements, and ModifierOrderer does not reorder the modifiers in a region. Imports are fixed as before. Files without an off marker format as before: of 9,532 files, the old and the new formatter differ only on the 344 with markers, and each of their 707 regions is kept verbatim. Closes #215. --- README.md | 5 + ...lantirJavaFormatFormattingServiceTest.java | 36 ++++++ .../palantir/javaformat/java/Formatter.java | 62 ++++++++-- .../javaformat/java/FormatterOffRegions.java | 108 ++++++++++++++++++ .../palantir/javaformat/java/JavaOutput.java | 15 +++ .../javaformat/java/StringWrapper.java | 19 +-- .../java/PartialFormattingTest.java | 38 ++++++ ...StatementBetweenMarkersStaysAsWritten.case | 28 +++++ ...mentWithMarkersInsideItStaysAsWritten.case | 30 +++++ .../formatterOff/blockCommentMarkers.case | 21 ++++ .../markerTextElsewhereIsNoMarker.case | 32 ++++++ .../membersBetweenMarkersStayAsWritten.case | 19 +++ ...dModifiersBetweenMarkersStayAsWritten.case | 22 ++++ ...ementWithMarkersInsideItStayAsWritten.case | 22 ++++ ...nMarkerTheRestOfTheFileStaysAsWritten.case | 18 +++ 15 files changed, 461 insertions(+), 14 deletions(-) create mode 100644 open-java-format/src/main/java/com/palantir/javaformat/java/FormatterOffRegions.java create mode 100644 open-java-format/src/test/resources/test-cases-java21/formatterOff/aStatementBetweenMarkersStaysAsWritten.case create mode 100644 open-java-format/src/test/resources/test-cases-java21/formatterOff/aStatementWithMarkersInsideItStaysAsWritten.case create mode 100644 open-java-format/src/test/resources/test-cases-java21/formatterOff/blockCommentMarkers.case create mode 100644 open-java-format/src/test/resources/test-cases-java21/formatterOff/markerTextElsewhereIsNoMarker.case create mode 100644 open-java-format/src/test/resources/test-cases-java21/formatterOff/membersBetweenMarkersStayAsWritten.case create mode 100644 open-java-format/src/test/resources/test-cases-java21/formatterOff/stringsAndModifiersBetweenMarkersStayAsWritten.case create mode 100644 open-java-format/src/test/resources/test-cases-java21/formatterOff/stringsInAStatementWithMarkersInsideItStayAsWritten.case create mode 100644 open-java-format/src/test/resources/test-cases-java21/formatterOff/withoutAnOnMarkerTheRestOfTheFileStaysAsWritten.case diff --git a/README.md b/README.md index 9ee8a279d..75fa2cac2 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,11 @@ private static void configureResolvedVersionsWithVersionMapping(Project project) } ``` +Code between a `// @formatter:off` and a `// @formatter:on` comment stays as written, in every tool +alike: the command line, Gradle, Spotless, IntelliJ IDEA and Eclipse. A statement with the markers +inside it stays as written whole. The markers cannot be changed or turned off, so the IDE's own +setting for them does not apply. + ## Coming from palantir-java-format - **Same output, except for bug fixes.** The formatter is the code of palantir-java-format 2.98.0, diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingServiceTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingServiceTest.java index 4c4ebf3d0..63f730edc 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingServiceTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingServiceTest.java @@ -16,6 +16,7 @@ package com.palantir.javaformat.intellij; +import com.intellij.application.options.CodeStyle; import com.intellij.codeInsight.actions.ReformatCodeProcessor; import com.intellij.formatting.service.AsyncFormattingRequest; import com.intellij.formatting.service.FormattingService; @@ -98,6 +99,41 @@ void defaultFormatSettings() throws Exception { assertThat(delegatingFormatter.wasInvoked()).isTrue(); } + @Test + void keepsCodeBetweenFormatterMarkersWhateverTheIdeSaysOfThem() throws Exception { + // The formatter honours the markers, as the build's does: the IDE's setting for them changes nothing. + var input = """ + package com.foo; + + class FormatTest { + void configure(Http http) { + // @formatter:off + http + .authorizeRequests() + .formLogin(); + // @formatter:on + } + } + """; + var file = createPsiFile("com/foo/FormatTest.java", input); + var codeStyle = CodeStyle.createTestSettings(CodeStyle.getSettings(getProject())); + codeStyle.FORMATTER_TAGS_ENABLED = false; + var processor = new ReformatCodeProcessor(file, false); + + CodeStyle.doWithTemporarySettings( + getProject(), + codeStyle, + () -> WriteCommandAction.runWriteCommandAction(getProject(), () -> { + ProjectRootManager.getInstance(getProject()) + .setProjectSdk(getProjectDescriptor().getSdk()); + processor.run(); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + })); + + assertThat(file.getText()).isEqualTo(input.replace("Http http", "Http http")); + assertThat(delegatingFormatter.wasInvoked()).isTrue(); + } + protected Project getProject() { return fixture.getProject(); } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java b/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java index 19388409e..2af622020 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java @@ -17,9 +17,11 @@ import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.ImmutableRangeSet; import com.google.common.collect.Iterables; import com.google.common.collect.Range; import com.google.common.collect.RangeSet; +import com.google.common.collect.TreeRangeSet; import com.google.common.io.CharSink; import com.google.common.io.CharSource; import com.google.errorprone.annotations.Immutable; @@ -340,7 +342,8 @@ public String formatSource(String input, Collection> characterRan } /** - * Emit a list of {@link Replacement}s to convert from input to output. + * Emit a list of {@link Replacement}s to convert from input to output. The code between {@code // @formatter:off} + * and {@code // @formatter:on} stays as written, and so does all of a statement or member that holds some of it. * * @param input the input compilation unit * @param characterRanges the character ranges to reformat @@ -350,21 +353,66 @@ public String formatSource(String input, Collection> characterRan public List getFormatReplacements(String input, Collection> characterRanges) throws FormatterException { JavaInput javaInput = new JavaInput(input); + var codeToKeep = FormatterOffRegions.find(javaInput); // TODO(cushon): this is only safe because the modifier ordering doesn't affect whitespace, // and doesn't change the replacements that are output. This is not true in general for // 'de-linting' changes (e.g. import ordering). - javaInput = ModifierOrderer.reorderModifiers(javaInput, characterRanges); + javaInput = ModifierOrderer.reorderModifiers( + javaInput, codeToKeep.isEmpty() ? characterRanges : without(characterRanges, codeToKeep)); - JavaCommentsHelper commentsHelper = new JavaCommentsHelper(javaInput, options); - JavaOutput javaOutput; + var javaOutput = layOut(javaInput); + RangeSet tokenRangeSet = javaInput.characterRangesToTokenRanges(characterRanges); + if (!codeToKeep.isEmpty()) { + tokenRangeSet.removeAll(keptToks(javaInput, javaOutput, codeToKeep)); + } + return javaOutput.getFormatReplacements(tokenRangeSet); + } + + /** + * The character ranges of {@code input} that formatting keeps as written: the statements and members that hold + * code between {@code // @formatter:off} and {@code // @formatter:on}. {@link StringWrapper} leaves the literals + * in them as they are. + */ + RangeSet keptRanges(String input) throws FormatterException { + if (!FormatterOffRegions.mayHoldMarkers(input)) { + return ImmutableRangeSet.of(); + } + var javaInput = new JavaInput(input); + var codeToKeep = FormatterOffRegions.find(javaInput); + RangeSet kept = TreeRangeSet.create(); + if (codeToKeep.isEmpty()) { + return kept; + } + var keptToks = keptToks(javaInput, layOut(javaInput), codeToKeep); + for (var toks : keptToks.asRanges()) { + var first = JavaOutput.startTok(javaInput.getToken(toks.lowerEndpoint())); + var last = JavaOutput.endTok(javaInput.getToken(toks.upperEndpoint() - 1)); + kept.add(Range.closedOpen(first.getPosition(), last.getPosition() + last.length())); + } + return kept; + } + + // A range is widened to the statements or members around it, so one next to code to keep would rewrite that code + // too: none of the statements and members that hold some of it is formatted. + private static RangeSet keptToks(JavaInput javaInput, JavaOutput javaOutput, RangeSet codeToKeep) + throws FormatterException { + return javaOutput.expandToBreakableRegions(javaInput.characterRangesToTokenRanges(codeToKeep.asRanges())); + } + + private JavaOutput layOut(JavaInput javaInput) throws FormatterException { try { - javaOutput = format(javaInput, options, commentsHelper, debugMode); + return format(javaInput, options, new JavaCommentsHelper(javaInput, options), debugMode); } catch (FormattingError e) { throw new FormatterException(e.diagnostics()); } - RangeSet tokenRangeSet = javaInput.characterRangesToTokenRanges(characterRanges); - return javaOutput.getFormatReplacements(tokenRangeSet); + } + + private static Collection> without( + Collection> characterRanges, RangeSet codeToKeep) { + var rest = TreeRangeSet.create(characterRanges); + rest.removeAll(codeToKeep); + return rest.asRanges(); } /** diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/FormatterOffRegions.java b/open-java-format/src/main/java/com/palantir/javaformat/java/FormatterOffRegions.java new file mode 100644 index 000000000..b967818ed --- /dev/null +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/FormatterOffRegions.java @@ -0,0 +1,108 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.java; + +import com.google.common.base.CharMatcher; +import com.google.common.collect.ImmutableRangeSet; +import com.google.common.collect.Range; +import com.google.common.collect.RangeSet; +import com.google.common.collect.TreeRangeSet; +import com.palantir.javaformat.Input; +import java.util.regex.Pattern; + +/** + * The code that {@code // @formatter:off} and {@code // @formatter:on} keep as written. It runs from the start of the + * line with an off marker to the start of the line with the next on marker, or to the end of the file, so the on + * marker itself is formatted; the whitespace at its edges is not part of it. + * + *

A marker is a line or block comment that starts with the marker text, the way IntelliJ IDEA and Eclipse write + * them. The text elsewhere, in a string, a Javadoc or a Markdown doc comment, or later in a comment, is no marker, so + * that code and documentation that mention it are formatted as usual. The markers are not configurable. + */ +final class FormatterOffRegions { + private static final String OFF = "@formatter:off"; + + // After `//` or `/*`, so not a Javadoc (`/**`) or a Markdown doc comment (`///`). + private static final Pattern MARKER = Pattern.compile("/[/*][ \\t]*@formatter:(off|on)\\b"); + + private final String text; + private final RangeSet code = TreeRangeSet.create(); + private int regionStart = -1; + + private FormatterOffRegions(String text) { + this.text = text; + } + + /** Whether {@code text} holds the off marker anywhere: if not, it has no code to keep, and need not be tokenised. */ + static boolean mayHoldMarkers(String text) { + return text.contains(OFF); + } + + /** The code to keep as written in {@code input}. */ + static RangeSet find(JavaInput input) { + if (!mayHoldMarkers(input.getText())) { + return ImmutableRangeSet.of(); + } + var regions = new FormatterOffRegions(input.getText()); + for (var token : input.getTokens()) { + // Comments are among the toks before and after a token, in the order of the file. + token.getToksBefore().forEach(regions::visit); + token.getToksAfter().forEach(regions::visit); + } + if (regions.regionStart != -1) { + regions.addRegion(regions.regionStart, regions.text.length()); + } + return regions.code; + } + + private void visit(Input.Tok tok) { + if (!tok.isComment()) { + return; + } + var marker = MARKER.matcher(tok.getOriginalText()); + if (!marker.lookingAt()) { + return; + } + var off = marker.group(1).equals("off"); + if (off && regionStart == -1) { + regionStart = lineStart(tok.getPosition()); + } else if (!off && regionStart != -1) { + addRegion(regionStart, lineStart(tok.getPosition())); + regionStart = -1; + } + } + + private int lineStart(int position) { + var start = position; + while (start > 0 && text.charAt(start - 1) != '\n' && text.charAt(start - 1) != '\r') { + start--; + } + return start; + } + + // Without the whitespace at its edges, which JavaOutput widens a replacement next to the region over. + private void addRegion(int start, int end) { + var whitespace = CharMatcher.whitespace(); + var codeStart = start; + while (codeStart < end && whitespace.matches(text.charAt(codeStart))) { + codeStart++; + } + var codeEnd = end; + while (codeEnd > codeStart && whitespace.matches(text.charAt(codeEnd - 1))) { + codeEnd--; + } + code.add(Range.closedOpen(codeStart, codeEnd)); + } +} diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/JavaOutput.java b/open-java-format/src/main/java/com/palantir/javaformat/java/JavaOutput.java index 954d23fcc..00deba2b2 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/JavaOutput.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/JavaOutput.java @@ -350,6 +350,21 @@ public List getFormatReplacements(RangeSet iRangeSet0) { return List.copyOf(result); } + /** + * The token ranges that formatting the given ones rewrites: each widened, as {@link #getFormatReplacements} widens + * it, to the statements or members around it. + */ + public RangeSet expandToBreakableRegions(RangeSet iRangeSet) { + RangeSet expanded = TreeRangeSet.create(); + for (var iRange : iRangeSet.asRanges()) { + var range = expandToBreakableRegions(iRange.canonical(DiscreteDomain.integers())); + if (!range.equals(EMPTY_RANGE)) { + expanded.add(range); + } + } + return expanded; + } + /** * Expand a token range to start and end on acceptable boundaries for re-formatting. * diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java b/open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java index 17f4b6817..782853649 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java @@ -123,7 +123,8 @@ private static Source wrapOnce(final int columnLimit, Source input, Formatter fo // The pieces continue the way the formatter continues a chain of +: four columns times the multiplier of its // style, eight in OJF. var continuationIndent = 4 * formatter.options().indentationMultiplier(); - TreeRangeMap replacements = input.reflowReplacements(columnLimit, continuationIndent); + TreeRangeMap replacements = + input.reflowReplacements(columnLimit, continuationIndent, formatter); if (replacements.asMapOfRanges().isEmpty()) { // needWrapping is an over-approximation, so there may be nothing to do after all. return input; @@ -140,7 +141,7 @@ private static Source wrapOnce(final int columnLimit, Source input, Formatter fo // If formatting the replacement ranges resulted in a change, recalculate the replacements on // the updated input. input = firstPass; - replacements = input.reflowReplacements(columnLimit, continuationIndent); + replacements = input.reflowReplacements(columnLimit, continuationIndent, formatter); } } if (rangesFormatted && input.unchangedBy(replacements)) { @@ -155,7 +156,7 @@ private static Source wrapOnce(final int columnLimit, Source input, Formatter fo Source secondPass = result.format(formatter, rangesAfterAppliedReplacements(replacements)); if (!secondPass.text().equals(result.text())) { - replacements = secondPass.reflowReplacements(columnLimit, continuationIndent); + replacements = secondPass.reflowReplacements(columnLimit, continuationIndent, formatter); result = secondPass.apply(replacements); } @@ -183,17 +184,21 @@ private static Source wrapOnce(final int columnLimit, Source input, Formatter fo */ private record Source(String text, @Nullable RangeSet ranges) { - /** The replacements of {@link #getReflowReplacements}, less those for literals outside the ranges. */ - TreeRangeMap reflowReplacements(int columnLimit, int continuationIndent) + /** + * The replacements of {@link #getReflowReplacements}, less those for literals outside the ranges and for + * literals in what formatting keeps as written, a statement or member with {@code // @formatter:off} code. + */ + TreeRangeMap reflowReplacements(int columnLimit, int continuationIndent, Formatter formatter) throws FormatterException { TreeRangeMap replacements = getReflowReplacements(columnLimit, continuationIndent, text); RangeSet within = ranges; - if (within == null) { + var kept = formatter.keptRanges(text); + if (within == null && kept.isEmpty()) { return replacements; } TreeRangeMap inRanges = TreeRangeMap.create(); replacements.asMapOfRanges().forEach((literal, replacement) -> { - if (within.intersects(literal)) { + if ((within == null || within.intersects(literal)) && !kept.intersects(literal)) { inRanges.put(literal, replacement); } }); diff --git a/open-java-format/src/test/java/com/palantir/javaformat/java/PartialFormattingTest.java b/open-java-format/src/test/java/com/palantir/javaformat/java/PartialFormattingTest.java index d3bd9a7e5..13d961892 100644 --- a/open-java-format/src/test/java/com/palantir/javaformat/java/PartialFormattingTest.java +++ b/open-java-format/src/test/java/com/palantir/javaformat/java/PartialFormattingTest.java @@ -319,6 +319,44 @@ public void onlyPackage() throws Exception { assertThat(output).isEqualTo(expectedOutput); } + @TestTemplate + public void rangeBetweenFormatterMarkersChangesNothing() throws Exception { + var input = lines( + "class Foo {", // + " // @formatter:off", + " int kept = 1;", + " // @formatter:on", + "}", + ""); + var idx = input.indexOf("kept"); + var output = doGetFormatReplacements(input, idx, idx + 1); + assertThat(output).isEqualTo(input); + } + + @TestTemplate + public void rangeAcrossFormatterMarkersFormatsTheCodeAroundThem() throws Exception { + var input = lines( + "class Foo {", + " int before = 1;", + " // @formatter:off", + " int kept = 2;", + " // @formatter:on", + " int after = 3;", + "}", + ""); + var expectedOutput = lines( + "class Foo {", + " int before = 1;", + " // @formatter:off", + " int kept = 2;", + " // @formatter:on", + " int after = 3;", + "}", + ""); + var output = doGetFormatReplacements(input, input.indexOf("before"), input.indexOf("after")); + assertThat(output).isEqualTo(expectedOutput); + } + private static String doGetFormatReplacements(String input, int characterILo, int characterIHi) throws Exception { return Formatter.create().formatSource(input, List.of(Range.closedOpen(characterILo, characterIHi + 1))); } diff --git a/open-java-format/src/test/resources/test-cases-java21/formatterOff/aStatementBetweenMarkersStaysAsWritten.case b/open-java-format/src/test/resources/test-cases-java21/formatterOff/aStatementBetweenMarkersStaysAsWritten.case new file mode 100644 index 000000000..cf9fca365 --- /dev/null +++ b/open-java-format/src/test/resources/test-cases-java21/formatterOff/aStatementBetweenMarkersStaysAsWritten.case @@ -0,0 +1,28 @@ +# The lines from the one with // @formatter:off to the one with // @formatter:on stay as written, such as a builder +# chain laid out by hand, and the code around them is formatted (#215). +---------- +class T { + void configure(Http http) { + // @formatter:off + http + .authorizeRequests() + .anyRequest().authenticated() + .and() + .formLogin(); + // @formatter:on + int x = 1; + } +} +---------- +class T { + void configure(Http http) { + // @formatter:off + http + .authorizeRequests() + .anyRequest().authenticated() + .and() + .formLogin(); + // @formatter:on + int x = 1; + } +} diff --git a/open-java-format/src/test/resources/test-cases-java21/formatterOff/aStatementWithMarkersInsideItStaysAsWritten.case b/open-java-format/src/test/resources/test-cases-java21/formatterOff/aStatementWithMarkersInsideItStaysAsWritten.case new file mode 100644 index 000000000..e5845878e --- /dev/null +++ b/open-java-format/src/test/resources/test-cases-java21/formatterOff/aStatementWithMarkersInsideItStaysAsWritten.case @@ -0,0 +1,30 @@ +# Formatting lays out whole statements and members, so markers inside one, here in an argument list, keep all of it as +# written. The statements around it are formatted. +---------- +class T { + List identity() { + int before = 1; + return List.of( + // @formatter:off + 1, 0, + 0, 1 + // @formatter:on + ); + } + + int after = 2; +} +---------- +class T { + List identity() { + int before = 1; + return List.of( + // @formatter:off + 1, 0, + 0, 1 + // @formatter:on + ); + } + + int after = 2; +} diff --git a/open-java-format/src/test/resources/test-cases-java21/formatterOff/blockCommentMarkers.case b/open-java-format/src/test/resources/test-cases-java21/formatterOff/blockCommentMarkers.case new file mode 100644 index 000000000..cffd512f4 --- /dev/null +++ b/open-java-format/src/test/resources/test-cases-java21/formatterOff/blockCommentMarkers.case @@ -0,0 +1,21 @@ +# The markers can be block comments too. +---------- +class T { + /* @formatter:off */ + int[][] identity = { + {1,0}, + {0,1}, + }; + /* @formatter:on */ + int after = 2; +} +---------- +class T { + /* @formatter:off */ + int[][] identity = { + {1,0}, + {0,1}, + }; + /* @formatter:on */ + int after = 2; +} diff --git a/open-java-format/src/test/resources/test-cases-java21/formatterOff/markerTextElsewhereIsNoMarker.case b/open-java-format/src/test/resources/test-cases-java21/formatterOff/markerTextElsewhereIsNoMarker.case new file mode 100644 index 000000000..495558d95 --- /dev/null +++ b/open-java-format/src/test/resources/test-cases-java21/formatterOff/markerTextElsewhereIsNoMarker.case @@ -0,0 +1,32 @@ +# A marker is a line or block comment that starts with it. The same text in a string, a text block, a Javadoc, a +# Markdown doc comment, later in a comment or as part of a longer word turns nothing off. +---------- +class T { + String literal = "// @formatter:off"; + String block = """ + // @formatter:off + """; + /** Mentions @formatter:off in a Javadoc. */ + int a = 1; + /// @formatter:off in a Markdown doc comment + int b = 2; + // see @formatter:off + int c = 3; + // @formatter:offline + int d = 4; +} +---------- +class T { + String literal = "// @formatter:off"; + String block = """ + // @formatter:off + """; + /** Mentions @formatter:off in a Javadoc. */ + int a = 1; + /// @formatter:off in a Markdown doc comment + int b = 2; + // see @formatter:off + int c = 3; + // @formatter:offline + int d = 4; +} diff --git a/open-java-format/src/test/resources/test-cases-java21/formatterOff/membersBetweenMarkersStayAsWritten.case b/open-java-format/src/test/resources/test-cases-java21/formatterOff/membersBetweenMarkersStayAsWritten.case new file mode 100644 index 000000000..85baf6836 --- /dev/null +++ b/open-java-format/src/test/resources/test-cases-java21/formatterOff/membersBetweenMarkersStayAsWritten.case @@ -0,0 +1,19 @@ +# Members of a class between the markers, such as constants aligned by hand, stay as written. +---------- +class T { + // @formatter:off + static final int ONE = 1; + static final int TWO = 2; + static final int THREE = 3; + // @formatter:on + static final int FOUR = 4; +} +---------- +class T { + // @formatter:off + static final int ONE = 1; + static final int TWO = 2; + static final int THREE = 3; + // @formatter:on + static final int FOUR = 4; +} diff --git a/open-java-format/src/test/resources/test-cases-java21/formatterOff/stringsAndModifiersBetweenMarkersStayAsWritten.case b/open-java-format/src/test/resources/test-cases-java21/formatterOff/stringsAndModifiersBetweenMarkersStayAsWritten.case new file mode 100644 index 000000000..cef5fbeeb --- /dev/null +++ b/open-java-format/src/test/resources/test-cases-java21/formatterOff/stringsAndModifiersBetweenMarkersStayAsWritten.case @@ -0,0 +1,22 @@ +# Between the markers long strings are not reflowed, adjacent literals not joined, text blocks not indented and +# modifiers not reordered. +---------- +class T { + // @formatter:off + final static String MESSAGE = "a string literal that is far too long for one line, so that the formatter would have to reflow it into pieces of a hundred and twenty columns"; + String joined = "a " + "b"; + String block = """ + text + """; + // @formatter:on +} +---------- +class T { + // @formatter:off + final static String MESSAGE = "a string literal that is far too long for one line, so that the formatter would have to reflow it into pieces of a hundred and twenty columns"; + String joined = "a " + "b"; + String block = """ + text + """; + // @formatter:on +} diff --git a/open-java-format/src/test/resources/test-cases-java21/formatterOff/stringsInAStatementWithMarkersInsideItStayAsWritten.case b/open-java-format/src/test/resources/test-cases-java21/formatterOff/stringsInAStatementWithMarkersInsideItStayAsWritten.case new file mode 100644 index 000000000..05db23699 --- /dev/null +++ b/open-java-format/src/test/resources/test-cases-java21/formatterOff/stringsInAStatementWithMarkersInsideItStayAsWritten.case @@ -0,0 +1,22 @@ +# A long string outside the markers, in the statement that holds them, is not reflowed either: the statement stays as +# written whole. +---------- +class T { + List f() { + return List.of("a string literal that is far too long for one line, so that the formatter would have to reflow it", + // @formatter:off + "x", "y" + // @formatter:on + ); + } +} +---------- +class T { + List f() { + return List.of("a string literal that is far too long for one line, so that the formatter would have to reflow it", + // @formatter:off + "x", "y" + // @formatter:on + ); + } +} diff --git a/open-java-format/src/test/resources/test-cases-java21/formatterOff/withoutAnOnMarkerTheRestOfTheFileStaysAsWritten.case b/open-java-format/src/test/resources/test-cases-java21/formatterOff/withoutAnOnMarkerTheRestOfTheFileStaysAsWritten.case new file mode 100644 index 000000000..159c407d8 --- /dev/null +++ b/open-java-format/src/test/resources/test-cases-java21/formatterOff/withoutAnOnMarkerTheRestOfTheFileStaysAsWritten.case @@ -0,0 +1,18 @@ +---------- +class T { + int formatted = 1; + + // @formatter:off + int kept = 2; + + void keptToo( ) { } +} +---------- +class T { + int formatted = 1; + + // @formatter:off + int kept = 2; + + void keptToo( ) { } +}