Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -98,7 +99,42 @@
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() {

Check warning on line 137 in open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingServiceTest.java

View workflow job for this annotation

GitHub Actions / build

[ProtectedMembersInFinalClass] Make members of final classes package-private: getProject, getProjectDescriptor
return fixture.getProject();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -340,7 +342,8 @@ public String formatSource(String input, Collection<Range<Integer>> 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
Expand All @@ -350,21 +353,66 @@ public String formatSource(String input, Collection<Range<Integer>> characterRan
public List<Replacement> getFormatReplacements(String input, Collection<Range<Integer>> 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<Integer> 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<Integer> keptRanges(String input) throws FormatterException {
if (!FormatterOffRegions.mayHoldMarkers(input)) {
return ImmutableRangeSet.of();
}
var javaInput = new JavaInput(input);
var codeToKeep = FormatterOffRegions.find(javaInput);
RangeSet<Integer> 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<Integer> keptToks(JavaInput javaInput, JavaOutput javaOutput, RangeSet<Integer> 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<Integer> tokenRangeSet = javaInput.characterRangesToTokenRanges(characterRanges);
return javaOutput.getFormatReplacements(tokenRangeSet);
}

private static Collection<Range<Integer>> without(
Collection<Range<Integer>> characterRanges, RangeSet<Integer> codeToKeep) {
var rest = TreeRangeSet.create(characterRanges);
rest.removeAll(codeToKeep);
return rest.asRanges();
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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<Integer> 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<Integer> 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));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,21 @@ public List<Replacement> getFormatReplacements(RangeSet<Integer> 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<Integer> expandToBreakableRegions(RangeSet<Integer> iRangeSet) {
RangeSet<Integer> 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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Integer, String> replacements = input.reflowReplacements(columnLimit, continuationIndent);
TreeRangeMap<Integer, String> 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;
Expand All @@ -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)) {
Expand All @@ -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);
}

Expand Down Expand Up @@ -183,17 +184,21 @@ private static Source wrapOnce(final int columnLimit, Source input, Formatter fo
*/
private record Source(String text, @Nullable RangeSet<Integer> ranges) {

/** The replacements of {@link #getReflowReplacements}, less those for literals outside the ranges. */
TreeRangeMap<Integer, String> 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<Integer, String> reflowReplacements(int columnLimit, int continuationIndent, Formatter formatter)
throws FormatterException {
TreeRangeMap<Integer, String> replacements = getReflowReplacements(columnLimit, continuationIndent, text);
RangeSet<Integer> within = ranges;
if (within == null) {
var kept = formatter.keptRanges(text);
if (within == null && kept.isEmpty()) {
return replacements;
}
TreeRangeMap<Integer, String> 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);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
}
Expand Down
Loading
Loading