diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala index a5d969f3cd..a8b829ff01 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala @@ -259,24 +259,35 @@ class FormatWriter(formatOps: FormatOps) { } initStyle.newlines.alwaysBeforeTopLevelStatements && { val formatToken = toks(i).formatToken + def checkPackage: Option[Boolean] = if (!initStyle.activeForEdition_2019_11) None else Some(owners(formatToken.left)) .collect { case term: Term.Name => term.parent } .flatten - .collect { case pkg: Pkg => pkg.stats.headOption } + .collect { + // package a + case pkg: Pkg => + pkg.stats.headOption + + // package a.b.c + case select: Term.Select => + select.parent.collect { case pkg: Pkg => pkg.stats.headOption }.flatten + } .flatten .map { case pkg: Pkg => next(pkg.ref.tokens.last).is[T.LeftBrace] case _ => true } - def checkTopLevelStatement(): Boolean = + + def checkTopLevelStatement: Boolean = topLevelTokens.contains(hash(formatToken.right)) && { val (distance, FormatToken(_, nextNonComment, _)) = nextNonCommentWithCount(formatToken) isMultiline(actualOwner(nextNonComment).tokens.last, i + distance + 1) } + checkPackage.getOrElse(checkTopLevelStatement) } } diff --git a/scalafmt-tests/src/test/resources/newlines/alwaysBeforeTopLevelStatements.source b/scalafmt-tests/src/test/resources/newlines/alwaysBeforeTopLevelStatements.source index f5ba1b864a..23bc0b23f8 100644 --- a/scalafmt-tests/src/test/resources/newlines/alwaysBeforeTopLevelStatements.source +++ b/scalafmt-tests/src/test/resources/newlines/alwaysBeforeTopLevelStatements.source @@ -36,3 +36,37 @@ package b { import a.b.c class d {} } +<<< #1593 1 +package a.b.c +package d.e +package f +import g.h.i.j +package k {} +>>> +package a.b.c +package d.e +package f + +import g.h.i.j +package k {} +<<< #1593 2 +package a.b.c +package d.e +package f +import g.h.i.j + +package k.l.m { + import n.o.p + class q {} +} +>>> +package a.b.c +package d.e +package f + +import g.h.i.j + +package k.l.m { + import n.o.p + class q {} +} \ No newline at end of file