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 a8375222..c7be0376 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt @@ -2390,16 +2390,19 @@ class KotlinInputAstVisitor( override fun visitKtFile(file: KtFile) { markForPartialFormat() - var importListEmpty = false + val importListEmpty = file.importList?.text?.isBlank() ?: true + var isFirst = true for (child in file.children) { - if (child.text.isBlank()) { - importListEmpty = child is KtImportList - continue - } - if (!isFirst && child !is PsiComment && (child !is KtScript || !importListEmpty)) { - builder.blankLineWanted(OpsBuilder.BlankLineWanted.YES) - } + if (child.text.isBlank()) continue + + builder.blankLineWanted(when { + isFirst -> OpsBuilder.BlankLineWanted.NO + child is PsiComment -> OpsBuilder.BlankLineWanted.NO + child is KtScript && importListEmpty -> OpsBuilder.BlankLineWanted.PRESERVE + else -> OpsBuilder.BlankLineWanted.YES + }) + visit(child) isFirst = false } 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 6d0c9616..90a019e3 100644 --- a/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt +++ b/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt @@ -440,7 +440,7 @@ class FormatterTest { deduceMaxWidth = true) @Test - fun `don't keep adding newlines between these two comments when they're at end of file`() = + fun `don't keep adding newlines between these two comments when they're at end of file`() { assertFormatted( """ |package foo @@ -450,6 +450,37 @@ class FormatterTest { |""" .trimMargin()) + assertFormatted( + """ + |// Comment as first element + |package foo + |// a + | + |/* Another comment */ + |""" + .trimMargin()) + + assertFormatted( + """ + |// Comment as first element then blank line + | + |package foo + |// a + | + |/* Another comment */ + |""" + .trimMargin()) + + assertFormatted( + """ + |// Comment as first element + |package foo + |// Adjacent line comments + |// Don't separate + |""" + .trimMargin()) + } + @Test fun `properties with line comment above initializer`() = assertFormatted(