Skip to content

Commit e01cd02

Browse files
cushongoogle-java-format Team
authored andcommitted
Only reflow long strings in the requested lines when partially formatting.
With `--lines`, `--offset`/`--length`, or the equivalent library APIs, `google-java-format` only reformats the requested ranges, but it still reflowed every long string literal in the file. `google-java-format-diff.py` users and editor integrations that format only changed lines got unrelated edits elsewhere in the file. The requested ranges are now mapped onto the formatted output and passed to `StringWrapper`, which only reflows string literals that intersect them. The offset mapping that `Cleanups` already used is extracted into a shared `Edit` class for this. `StringWrapper`'s preliminary pass over the strings it will reflow now uses whitespace-only `getFormatReplacements` instead of `formatSource`, so the ranges can be mapped through it too; the cleanup passes have already run by that point. Fixes #1114 PiperOrigin-RevId: 1010285643
1 parent 7e4696d commit e01cd02

7 files changed

Lines changed: 461 additions & 74 deletions

File tree

‎core/src/main/java/com/google/googlejavaformat/java/Cleanups.java‎

Lines changed: 3 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
package com.google.googlejavaformat.java;
1616

17-
import static com.google.common.base.Preconditions.checkArgument;
1817
import static java.lang.Math.max;
1918
import static java.lang.Math.min;
2019

@@ -50,57 +49,6 @@ record Result(
5049
Collection<Range<Integer>> characterRanges,
5150
@Nullable JCCompilationUnit unit) {}
5251

53-
/// One replacement: `[inStart, inEnd)` in the old contents became `[outStart, outEnd)`.
54-
private record Span(int inStart, int inEnd, int outStart, int outEnd) {}
55-
56-
/// The result of applying sorted, non-overlapping replacements to some text.
57-
private record Edit(String contents, ImmutableList<Span> spans) {
58-
59-
/// Applies sorted, non-overlapping replacements to `contents`.
60-
static Edit apply(String contents, List<Replacement> replacements) {
61-
StringBuilder sb = new StringBuilder(contents.length());
62-
ImmutableList.Builder<Span> spans =
63-
ImmutableList.builderWithExpectedSize(replacements.size());
64-
int cursor = 0;
65-
for (Replacement replacement : replacements) {
66-
Range<Integer> range = replacement.replaceRange();
67-
int inStart = range.lowerEndpoint();
68-
int inEnd = range.upperEndpoint();
69-
checkArgument(
70-
inStart >= cursor,
71-
"Replacements must be sorted and non-overlapping, but %s overlaps previous end %s",
72-
range,
73-
cursor);
74-
sb.append(contents, cursor, inStart);
75-
int outStart = sb.length();
76-
sb.append(replacement.replacementString());
77-
int outEnd = sb.length();
78-
spans.add(new Span(inStart, inEnd, outStart, outEnd));
79-
cursor = inEnd;
80-
}
81-
sb.append(contents, cursor, contents.length());
82-
return new Edit(sb.toString(), spans.build());
83-
}
84-
85-
/// Maps an offset in the old contents to the corresponding offset in the new contents.
86-
///
87-
/// Offsets before a span are unchanged relative to the previous span; offsets inside a span are
88-
/// clamped to its replacement text; offsets after all spans are shifted by the final span.
89-
int map(int offset) {
90-
Span prev = null;
91-
for (Span span : spans) {
92-
if (offset < span.inStart()) {
93-
return prev == null ? offset : prev.outEnd() + (offset - prev.inEnd());
94-
}
95-
if (offset <= span.inEnd()) {
96-
return span.outStart() + min(offset - span.inStart(), span.outEnd() - span.outStart());
97-
}
98-
prev = span;
99-
}
100-
return prev == null ? offset : prev.outEnd() + (offset - prev.inEnd());
101-
}
102-
}
103-
10452
private record Parsed(Context context, JCCompilationUnit unit) {}
10553

10654
/// Returns the enabled passes for formatting or fixing imports.
@@ -207,15 +155,8 @@ private void applyReplacements(List<Replacement> replacements) {
207155
return;
208156
}
209157
Edit edit = Edit.apply(contents, replacements);
210-
RangeSet<Integer> newRanges = TreeRangeSet.create();
211-
for (Range<Integer> range : ranges.asRanges()) {
212-
int mappedStart = edit.map(range.lowerEndpoint());
213-
int mappedEnd = edit.map(range.upperEndpoint());
214-
if (mappedStart < mappedEnd) {
215-
newRanges.add(Range.closedOpen(mappedStart, mappedEnd));
216-
}
217-
}
218-
for (Span span : edit.spans()) {
158+
RangeSet<Integer> newRanges = TreeRangeSet.create(edit.mapRanges(ranges.asRanges()));
159+
for (Edit.Span span : edit.spans()) {
219160
Range<Integer> r = reformatRange(span, edit.contents());
220161
if (!r.isEmpty()) {
221162
newRanges.add(r);
@@ -228,7 +169,7 @@ private void applyReplacements(List<Replacement> replacements) {
228169
}
229170

230171
/// Returns the range to reformat for the given span.
231-
private static Range<Integer> reformatRange(Span span, String contents) {
172+
private static Range<Integer> reformatRange(Edit.Span span, String contents) {
232173
if (span.outStart() == span.outEnd()) {
233174
return deletionReformatRange(contents, span.outStart());
234175
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/*
2+
* Copyright 2026 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
package com.google.googlejavaformat.java;
16+
17+
import static com.google.common.base.Preconditions.checkArgument;
18+
import static com.google.common.base.Strings.commonPrefix;
19+
import static com.google.common.base.Strings.commonSuffix;
20+
import static java.lang.Math.min;
21+
22+
import com.google.common.collect.ImmutableList;
23+
import com.google.common.collect.ImmutableRangeSet;
24+
import com.google.common.collect.Range;
25+
import com.google.common.collect.RangeSet;
26+
import com.google.common.collect.TreeRangeSet;
27+
import java.nio.CharBuffer;
28+
import java.util.Collection;
29+
import java.util.List;
30+
31+
/// The result of applying sorted, non-overlapping replacements to some text, which can map offsets
32+
/// in the old text to offsets in the new text.
33+
record Edit(String contents, ImmutableList<Edit.Span> spans) {
34+
35+
/// One replacement: `[inStart, inEnd)` in the old contents became `[outStart, outEnd)`.
36+
record Span(int inStart, int inEnd, int outStart, int outEnd) {}
37+
38+
/// Applies sorted, non-overlapping replacements to `contents`.
39+
static Edit apply(String contents, List<Replacement> replacements) {
40+
StringBuilder sb = new StringBuilder(contents.length());
41+
ImmutableList.Builder<Span> spans = ImmutableList.builderWithExpectedSize(replacements.size());
42+
int cursor = 0;
43+
for (Replacement replacement : replacements) {
44+
Range<Integer> range = replacement.replaceRange();
45+
int inStart = range.lowerEndpoint();
46+
int inEnd = range.upperEndpoint();
47+
checkArgument(
48+
inStart >= cursor,
49+
"Replacements must be sorted and non-overlapping, but %s overlaps previous end %s",
50+
range,
51+
cursor);
52+
sb.append(contents, cursor, inStart);
53+
String replacementString = replacement.replacementString();
54+
int outStart = sb.length();
55+
sb.append(replacementString);
56+
int outEnd = sb.length();
57+
// Trim any unchanged prefix and suffix so coarse replacements (such as reformatting an entire
58+
// statement) don't treat unchanged tokens at the start or end of the replacement as part of
59+
// the modified span.
60+
int prefix =
61+
commonPrefix(CharBuffer.wrap(contents, inStart, inEnd), replacementString).length();
62+
int suffix =
63+
commonSuffix(
64+
CharBuffer.wrap(contents, inStart + prefix, inEnd),
65+
CharBuffer.wrap(replacementString, prefix, replacementString.length()))
66+
.length();
67+
if (inStart + prefix < inEnd - suffix || outStart + prefix < outEnd - suffix) {
68+
spans.add(new Span(inStart + prefix, inEnd - suffix, outStart + prefix, outEnd - suffix));
69+
}
70+
cursor = inEnd;
71+
}
72+
sb.append(contents, cursor, contents.length());
73+
return new Edit(sb.toString(), spans.build());
74+
}
75+
76+
/// Maps an offset in the old contents to the corresponding offset in the new contents.
77+
///
78+
/// Offsets in unmodified text are shifted by the cumulative length change of preceding
79+
/// replacements. Offsets inside a replaced range `[inStart, inEnd)` are shifted relative to
80+
/// `inStart` and clamped to `outEnd` if the replacement is shorter than the original range.
81+
int map(int offset) {
82+
int shift = 0;
83+
for (Span span : spans) {
84+
if (offset < span.inStart()) {
85+
return offset + shift;
86+
}
87+
if (offset < span.inEnd()) {
88+
return min(offset + shift, span.outEnd());
89+
}
90+
shift = span.outEnd() - span.inEnd();
91+
}
92+
return offset + shift;
93+
}
94+
95+
/// Maps ranges in the old contents to the corresponding ranges in the new contents, dropping
96+
/// ranges that become empty.
97+
ImmutableRangeSet<Integer> mapRanges(Collection<Range<Integer>> ranges) {
98+
RangeSet<Integer> result = TreeRangeSet.create();
99+
for (Range<Integer> range : ranges) {
100+
int start = map(range.lowerEndpoint());
101+
int end = map(range.upperEndpoint());
102+
if (start < end) {
103+
result.add(Range.closedOpen(start, end));
104+
}
105+
}
106+
return ImmutableRangeSet.copyOf(result);
107+
}
108+
}

‎core/src/main/java/com/google/googlejavaformat/java/Formatter.java‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -189,15 +189,20 @@ String formatSource(
189189
Cleanups.enabledPasses(
190190
options.cleanup(), removeUnusedImports, options.reorderModifiers(), sortImports);
191191
Cleanups.Result cleaned = Cleanups.apply(input, characterRanges, options.style(), passes);
192-
String formatted =
193-
JavaOutput.applyReplacements(
192+
Edit formatted =
193+
Edit.apply(
194194
cleaned.contents(),
195195
getFormatReplacements(
196196
cleaned.contents(), cleaned.characterRanges(), options.cleanup(), cleaned.unit()));
197197
if (reflowLongStrings) {
198-
formatted = StringWrapper.wrap(options.maxLineLength(), formatted, this);
198+
// Only reflow long strings in the requested ranges, mapped onto the formatted output.
199+
return StringWrapper.wrap(
200+
options.maxLineLength(),
201+
formatted.contents(),
202+
this,
203+
formatted.mapRanges(cleaned.characterRanges()));
199204
}
200-
return formatted;
205+
return formatted.contents();
201206
}
202207

203208
/// Formats an input string (a Java compilation unit) and fixes imports.

‎core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java‎

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@
2222
import com.google.common.base.CharMatcher;
2323
import com.google.common.base.Verify;
2424
import com.google.common.collect.ImmutableList;
25+
import com.google.common.collect.ImmutableRangeSet;
2526
import com.google.common.collect.Range;
27+
import com.google.common.collect.RangeSet;
2628
import com.google.common.collect.TreeRangeMap;
2729
import com.google.googlejavaformat.Newlines;
2830
import com.sun.source.tree.BinaryTree;
@@ -58,20 +60,36 @@ public static String wrap(String input, Formatter formatter) throws FormatterExc
5860
/// Reflows string literals in the given Java source code that extend past the given column limit.
5961
static String wrap(final int columnLimit, String input, Formatter formatter)
6062
throws FormatterException {
63+
return wrap(
64+
columnLimit, input, formatter, ImmutableRangeSet.of(Range.closedOpen(0, input.length())));
65+
}
66+
67+
/// Reflows string literals in the given character ranges of the given Java source code that
68+
/// extend past the given column limit.
69+
static String wrap(
70+
final int columnLimit, String input, Formatter formatter, RangeSet<Integer> characterRanges)
71+
throws FormatterException {
6172
JavaFormatterOptions options = formatter.options();
6273
if (!needWrapping(columnLimit, input, options)) {
6374
// fast path
6475
return input;
6576
}
6677

67-
TreeRangeMap<Integer, String> replacements = getReflowReplacements(columnLimit, input, options);
68-
String firstPass = formatter.formatSource(input, replacements.asMapOfRanges().keySet());
78+
TreeRangeMap<Integer, String> replacements =
79+
getReflowReplacements(columnLimit, input, options, characterRanges);
80+
if (replacements.asMapOfRanges().isEmpty()) {
81+
return input;
82+
}
83+
Edit firstPass =
84+
Edit.apply(
85+
input, formatter.getFormatReplacements(input, replacements.asMapOfRanges().keySet()));
6986

70-
if (!firstPass.equals(input)) {
87+
if (!firstPass.contents().equals(input)) {
7188
// If formatting the replacement ranges resulted in a change, recalculate the replacements on
7289
// the updated input.
73-
input = firstPass;
74-
replacements = getReflowReplacements(columnLimit, input, options);
90+
input = firstPass.contents();
91+
characterRanges = firstPass.mapRanges(characterRanges.asRanges());
92+
replacements = getReflowReplacements(columnLimit, input, options, characterRanges);
7593
}
7694

7795
String result = applyReplacements(input, replacements);
@@ -111,24 +129,34 @@ private static FormatterException somethingHasGoneTerriblyWrong(
111129
}
112130

113131
private static TreeRangeMap<Integer, String> getReflowReplacements(
114-
int columnLimit, final String input, JavaFormatterOptions options) throws FormatterException {
115-
return new Reflower(columnLimit, input, options).getReflowReplacements();
132+
int columnLimit,
133+
final String input,
134+
JavaFormatterOptions options,
135+
RangeSet<Integer> characterRanges)
136+
throws FormatterException {
137+
return new Reflower(columnLimit, input, options, characterRanges).getReflowReplacements();
116138
}
117139

118140
private static class Reflower {
119141

120142
private final String input;
121143
private final int columnLimit;
122144
private final JavaFormatterOptions options;
145+
private final RangeSet<Integer> characterRanges;
123146
private final String separator;
124147
private final JCTree.JCCompilationUnit unit;
125148
private final Position.LineMap lineMap;
126149

127-
Reflower(int columnLimit, String input, JavaFormatterOptions options)
150+
Reflower(
151+
int columnLimit,
152+
String input,
153+
JavaFormatterOptions options,
154+
RangeSet<Integer> characterRanges)
128155
throws FormatterException {
129156
this.columnLimit = columnLimit;
130157
this.input = input;
131158
this.options = options;
159+
this.characterRanges = characterRanges;
132160
this.separator = Newlines.guessLineSeparator(input);
133161
this.unit = parse(input, /* allowStringFolding= */ false);
134162
this.lineMap = unit.getLineMap();
@@ -170,6 +198,10 @@ public Void visitLiteral(LiteralTree literalTree, Void aVoid) {
170198
return null;
171199
}
172200
int endPosition = getEndPosition(literalTree, unit);
201+
if (!characterRanges.intersects(
202+
Range.closedOpen(getStartPosition(literalTree), endPosition))) {
203+
return null;
204+
}
173205
int lineEnd = endPosition;
174206
while (Newlines.hasNewlineAt(input, lineEnd) == -1) {
175207
lineEnd++;

0 commit comments

Comments
 (0)