From 7d23e595d82342685b047ce39f1062e6d8f4a882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nivaldo=20Bondan=C3=A7a?= Date: Thu, 6 Jun 2024 21:46:10 -0700 Subject: [PATCH] Preserve new lines between when clauses Summary: Implemented as requested on https://github.com/facebook/ktfmt/issues/342 Reviewed By: davidtorosyan Differential Revision: D58271914 fbshipit-source-id: 048d9a754b40200f313654775eb743c024073d39 --- .../ktfmt/format/KotlinInputAstVisitor.kt | 6 ++- .../facebook/ktfmt/format/FormatterTest.kt | 44 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt b/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt index 6a620222..608af596 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt @@ -1882,8 +1882,12 @@ class KotlinInputAstVisitor( builder.space() builder.token("{", Doc.Token.RealOrImaginary.REAL, blockIndent, Optional.of(blockIndent)) - expression.entries.forEach { whenEntry -> + expression.entries.forEachIndexed { index, whenEntry -> builder.block(blockIndent) { + if (index != 0) { + // preserve new line if there's one + builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE) + } builder.forcedBreak() if (whenEntry.isElse) { builder.token("else") diff --git a/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt b/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt index b88138ba..4e8acc27 100644 --- a/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt +++ b/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt @@ -1635,6 +1635,50 @@ class FormatterTest { |""" .trimMargin()) + @Test + fun `newlines between clauses of when() are preserved`() { + assertThatFormatting( + """ + |fun f(x: Int) { + | when (x) { + | + | + | 1 -> print(1) + | 2 -> print(2) + | + | + | 3 -> + | // Comment + | print(3) + | + | else -> { + | print("else") + | } + | + | } + |} + |""" + .trimMargin()) + .isEqualTo( + """ + |fun f(x: Int) { + | when (x) { + | 1 -> print(1) + | 2 -> print(2) + | + | 3 -> + | // Comment + | print(3) + | + | else -> { + | print("else") + | } + | } + |} + |""" + .trimMargin()) + } + @Test fun `when() with a subject expression`() = assertFormatted(