@@ -124,17 +124,24 @@ renderItems separator (Items items) = go items
124124 go (item : rest) =
125125 pretty item <> if null rest then mempty else separator <> go rest
126126
127+ hasOnlyComments :: Items a -> Bool
128+ hasOnlyComments (Items xs) = not (null xs) && all isComment xs
129+ where
130+ isComment (Comments _) = True
131+ isComment _ = False
132+
127133-- Render a list given the separator between items
128134renderList :: Doc -> Ann Token -> Items Term -> Ann Token -> Doc
129135renderList itemSep paropen@ Ann {trailComment = post} items parclose =
130136 pretty (paropen{trailComment = Nothing })
131137 <> surroundWith sur (nest $ pretty post <> renderItems itemSep items)
132138 <> pretty parclose
133139 where
134- -- If the brackets are on different lines, keep them like that
135140 sur
136- | sourceLine paropen /= sourceLine parclose = hardline
137- | null $ unItems items = hardspace
141+ | sourceLine paropen /= sourceLine parclose = hardline -- If the brackets are on different lines, keep them like that
142+ | hasOnlyComments items = hardline -- If the list has only comments, use hardline to ensure idempotency. https://github.com/NixOS/nixfmt/issues/362
143+ | hasTrivia paropen && null items = hardline -- even if the comment got associated with the opening bracket, keep the hardline
144+ | null items = hardspace -- making sure we're not potentially adding extra newlines for empty lists
138145 | otherwise = line
139146
140147instance Pretty Trivia where
@@ -597,6 +604,11 @@ isAbsorbable (Set _ (Ann{sourceLine = line1}) (Items []) (Ann{sourceLine = line2
597604 | line1 /= line2 = True
598605isAbsorbable (List (Ann {sourceLine = line1}) (Items [] ) (Ann {sourceLine = line2}))
599606 | line1 /= line2 = True
607+ -- Lists/sets with only comments are absorbable (https://github.com/NixOS/nixfmt/issues/362)
608+ isAbsorbable (List paropen items _)
609+ | hasTrivia paropen || hasOnlyComments items = True
610+ isAbsorbable (Set _ paropen items _)
611+ | hasTrivia paropen || hasOnlyComments items = True
600612isAbsorbable (Parenthesized (LoneAnn _) (Term t) _) = isAbsorbable t
601613isAbsorbable _ = False
602614
0 commit comments