gdritter repos s-cargot / 65fff36
Pretty-printing indentation now controlled with Indent type Getty Ritter 9 years ago
1 changed file(s) with 28 addition(s) and 13 deletion(s). Collapse all Expand all
44
55 module Data.SCargot.Pretty
66 ( LayoutOptions(..)
7 , Indent(..)
78 , basicPrint
89 , flatPrint
910 , prettyPrintSExpr
1415 import qualified Data.Text as T
1516
1617 import Data.SCargot.Repr
18
19 data Indent
20 = Swing
21 | SwingAfter Int
22 | Align
23 deriving (Eq, Show)
1724
1825 -- | A 'LayoutOptions' value describes how to pretty-print a 'SExpr'.
1926 -- It describes how to print atoms, what horizontal space to fit
5663 -- otherwise, subsequent lines are indented based on the size of the
5764 -- @car@ of the list.
5865 data LayoutOptions a = LayoutOptions
59 { atomPrinter :: a -> Text -- ^ How to serialize a given atom to 'Text'.
60 , swingIndent :: SExpr a -> Bool -- ^ Whether or not to swing
61 , indentAmount :: Int -- ^ How much to indent after a swing
62 , maxWidth :: Maybe Int -- ^ The maximum width (if any)
66 { atomPrinter :: a -> Text -- ^ How to serialize a given atom to 'Text'.
67 , swingIndent :: SExpr a -> Indent -- ^ Whether or not to swing
68 , indentAmount :: Int -- ^ How much to indent after a swing
69 , maxWidth :: Maybe Int -- ^ The maximum width (if any)
6370 }
6471
6572 flatPrint :: (a -> Text) -> LayoutOptions a
6673 flatPrint printer = LayoutOptions
6774 { atomPrinter = printer
68 , swingIndent = const True
75 , swingIndent = const Swing
6976 , indentAmount = 2
7077 , maxWidth = Nothing
7178 }
7380 basicPrint :: (a -> Text) -> LayoutOptions a
7481 basicPrint printer = LayoutOptions
7582 { atomPrinter = printer
76 , swingIndent = const True
83 , swingIndent = const Swing
7784 , indentAmount = 2
7885 , maxWidth = Just 80
7986 }
113120 lst = k []
114121 flat = T.unwords (map (pHead (ind+1)) lst)
115122 headWidth = T.length hd + 1
116 indented
117 | swingIndent h =
123 indented =
124 case swingIndent h of
125 SwingAfter n ->
126 let (l, ls) = splitAt n lst
127 t = T.unwords (map (pHead (ind+1)) l)
128 ts = indentAll (ind + indentAmount)
129 (map (pHead (ind + indentAmount)) ls)
130 in t <> ts
131 Swing ->
118132 indentAll (ind + indentAmount)
119133 (map (pHead (ind + indentAmount)) lst)
120 | otherwise =
134 Align ->
121135 indentSubsequent (ind + headWidth + 1)
122136 (map (pHead (ind + headWidth + 1)) lst)
123 body | length lst == 0 = ""
124 | Just maxAmt <- maxWidth
125 , (T.length flat + ind) > maxAmt = " " <> indented
126 | otherwise = " " <> flat
137 body
138 | length lst == 0 = ""
139 | Just maxAmt <- maxWidth
140 , (T.length flat + ind) > maxAmt = " " <> indented
141 | otherwise = " " <> flat