From 52696257a3f71158e4730ba47b569d7d6eae75a4 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Mon, 18 Nov 2024 15:54:34 -0800 Subject: [PATCH] Fix logic for checking if text blocks are already deindented Check the last line instead of the first line of the text block contents. Empty lines in the text block have no leading whitespace but do not indicate the contents are deindented, only non-empty lines should be considered. The last line will never be empty, it contains at least the close delimiter. PiperOrigin-RevId: 697785256 --- .../googlejavaformat/java/StringWrapper.java | 3 ++- .../java/StringWrapperTest.java | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java index 42099d6b8..c3a36ab50 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java @@ -207,7 +207,8 @@ private void indentTextBlocks( String stripped = stripIndent(initialLines.stream().skip(1).collect(joining(separator))); ImmutableList lines = stripped.lines().collect(toImmutableList()); int deindent = - initialLines.get(1).stripTrailing().length() - lines.get(0).stripTrailing().length(); + getLast(initialLines).stripTrailing().length() + - getLast(lines).stripTrailing().length(); String prefix = (deindent == 0 diff --git a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperTest.java b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperTest.java index 7854126c4..339ed1340 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperTest.java @@ -174,6 +174,33 @@ public void textBlockSpaceTabMix() throws Exception { assertThat(actual).isEqualTo(expected); } + @Test + public void leadingBlankLine() throws Exception { + assumeTrue(Runtime.version().feature() >= 15); + String input = + lines( + "public class T {", + " String s =", + " \"\"\"", + "", + " lorem", + " ipsum", + " \"\"\";", + "}"); + String expected = + lines( + "public class T {", + " String s =", + " \"\"\"", + "", + " lorem", + " ipsum", + " \"\"\";", + "}"); + String actual = StringWrapper.wrap(100, input, new Formatter()); + assertThat(actual).isEqualTo(expected); + } + private static String lines(String... line) { return Joiner.on('\n').join(line) + '\n'; }