Skip to content

Commit

Permalink
List, Attrset: Preserve empty line when there are no items
Browse files Browse the repository at this point in the history
  • Loading branch information
piegamesde committed Feb 26, 2024
1 parent d6902b0 commit 6413a12
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/Nixfmt/Pretty.hs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ instance Pretty a => Pretty (Item a) where

-- For lists, attribute sets and let bindings
prettyItems :: Pretty a => Doc -> Items a -> Doc
prettyItems sep = prettyItems' . unItems
-- Special case: Preserve an empty line with no items
-- usually, trailing newlines after the last element are not preserved
prettyItems _ (Items [DetachedComments []]) = emptyline
prettyItems sep items = prettyItems' $ unItems items
where
prettyItems' :: Pretty a => [Item a] -> Doc
prettyItems' [] = mempty
Expand Down Expand Up @@ -124,9 +127,9 @@ instance Pretty Binder where
-- in some situations even that is not sufficient. The wide parameter will
-- be even more eager at expanding, except for empty sets and inherit statements.
prettySet :: Bool -> (Maybe Leaf, Leaf, Items Binder, Leaf) -> Doc
-- Empty, non-recursive attribute set
prettySet _ (Nothing, Ann [] paropen Nothing, Items [], parclose@(Ann [] _ _))
= pretty paropen <> hardspace <> pretty parclose
-- Empty attribute set
prettySet _ (krec, Ann [] paropen Nothing, Items [], parclose@(Ann [] _ _))
= pretty (fmap (, hardspace) krec) <> pretty paropen <> hardspace <> pretty parclose
-- Singleton sets are allowed to fit onto one line,
-- but apart from that always expand.
prettySet wide (krec, Ann pre paropen post, binders, parclose)
Expand Down
8 changes: 8 additions & 0 deletions test/diff/attr_set/in.nix
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
{a=1;
}

{

}

{ a = {

};}

{ b=1; }
{ b=1; /*c*/ }
{ /*a*/ b=1; }
Expand Down
10 changes: 10 additions & 0 deletions test/diff/attr_set/out.nix
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@
{ a = 1; }
{ a = 1; }

{

}

{
a = {

};
}

{ b = 1; }
{
b = 1; # c
Expand Down
8 changes: 8 additions & 0 deletions test/diff/lists/in.nix
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
[
[

]

[ [

] ]

[ {
# multiline
foo = "bar";
Expand Down
10 changes: 10 additions & 0 deletions test/diff/lists/out.nix
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
[
[

]

[
[

]
]

[
{
# multiline
Expand Down

0 comments on commit 6413a12

Please sign in to comment.