-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathInternal.hs
More file actions
executable file
·2240 lines (1992 loc) · 73.6 KB
/
Internal.hs
File metadata and controls
executable file
·2240 lines (1992 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_HADDOCK not-home #-}
#include "version-compatibility-macros.h"
-- | __Warning: internal module!__ This means that the API may change
-- arbitrarily between versions without notice. Depending on this module may
-- lead to unexpected breakages, so proceed with caution!
--
-- For a stable API, use the non-internal modules. For the special case of
-- writing adaptors to this library’s @'Doc'@ type, see
-- "Prettyprinter.Internal.Type".
module Prettyprinter.Internal (
-- * Documents
Doc(..),
-- * Basic functionality
Pretty(..),
viaShow, unsafeViaShow, unsafeTextWithoutNewlines,
emptyDoc, nest, line, line', softline, softline', hardline,
-- ** Primitives for alternative layouts
group, flatAlt,
-- * Alignment functions
align, hang, indent, encloseSep, list, tupled,
-- * Binary functions
(<+>),
-- * List functions
concatWith,
-- ** 'sep' family
hsep, vsep, fillSep, sep,
-- ** 'cat' family
hcat, vcat, fillCat, cat,
-- ** Others
punctuate,
-- * Reactive/conditional layouts
column, nesting, width, pageWidth,
-- * Filler functions
fill, fillBreak,
-- * General convenience
plural, enclose, surround,
-- ** Annotations
annotate,
unAnnotate,
reAnnotate,
alterAnnotations,
unAnnotateS,
reAnnotateS,
alterAnnotationsS,
-- * Optimization
fuse, FusionDepth(..),
-- * Layout
SimpleDocStream(..),
PageWidth(..), defaultPageWidth,
LayoutOptions(..), defaultLayoutOptions,
layoutPretty, layoutCompact, layoutSmart,
removeTrailingWhitespace,
-- * Rendering
renderShowS,
-- * Internal helpers
textSpaces
) where
import Control.Applicative
import Data.Int
import Data.List.NonEmpty (NonEmpty (..))
import Data.Maybe
import Data.String (IsString (..))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as Lazy
import Data.Typeable (Typeable)
import Data.Void
import Data.Word
import GHC.Generics (Generic)
-- Depending on the Cabal file, this might be from base, or for older builds,
-- from the semigroups package.
import Data.Semigroup
#if NATURAL_IN_BASE
import Numeric.Natural
#endif
#if !(FOLDABLE_TRAVERSABLE_IN_PRELUDE)
import Data.Foldable (Foldable (..))
import Data.Traversable (Traversable (..))
import Prelude hiding (foldr, foldr1)
#endif
#if FUNCTOR_IDENTITY_IN_BASE
import Data.Functor.Identity
#endif
import Prettyprinter.Render.Util.Panic
-- | The abstract data type @'Doc' ann@ represents pretty documents that have
-- been annotated with data of type @ann@.
--
-- More specifically, a value of type @'Doc'@ represents a non-empty set of
-- possible layouts of a document. The layout functions select one of these
-- possibilities, taking into account things like the width of the output
-- document.
--
-- The annotation is an arbitrary piece of data associated with (part of) a
-- document. Annotations may be used by the rendering backends in order to
-- display output differently, such as
--
-- - color information (e.g. when rendering to the terminal)
-- - mouseover text (e.g. when rendering to rich HTML)
-- - whether to show something or not (to allow simple or detailed versions)
--
-- The simplest way to display a 'Doc' is via the 'Show' class.
--
-- >>> putStrLn (show (vsep ["hello", "world"]))
-- hello
-- world
data Doc ann =
-- | Occurs when flattening a line. The layouter will reject this document,
-- choosing a more suitable rendering.
Fail
-- | The empty document; conceptually the unit of 'Cat'
| Empty
-- | invariant: not '\n'
| Char !Char
-- | Invariants: at least two characters long, does not contain '\n'. For
-- empty documents, there is @Empty@; for singleton documents, there is
-- @Char@; newlines should be replaced by e.g. @Line@.
--
-- Since the frequently used 'T.length' of 'Text' is /O(length)/, we cache
-- it in this constructor.
| Text !Int !Text
-- | Hard line break
| Line
-- | Lay out the first 'Doc', but when flattened (via 'group'), prefer
-- the second.
--
-- The layout algorithms work under the assumption that the first
-- alternative is less wide than the flattened second alternative.
| FlatAlt (Doc ann) (Doc ann)
-- | Concatenation of two documents
| Cat (Doc ann) (Doc ann)
-- | Document indented by a number of columns
| Nest !Int (Doc ann)
-- | Invariant: The first lines of first document should be longer than the
-- first lines of the second one, so the layout algorithm can pick the one
-- that fits best. Used to implement layout alternatives for 'group'.
| Union (Doc ann) (Doc ann)
-- | React on the current cursor position, see 'column'
| Column (Int -> Doc ann)
-- | React on the document's width, see 'pageWidth'
| WithPageWidth (PageWidth -> Doc ann)
-- | React on the current nesting level, see 'nesting'
| Nesting (Int -> Doc ann)
-- | Add an annotation to the enclosed 'Doc'. Can be used for example to add
-- styling directives or alt texts that can then be used by the renderer.
| Annotated ann (Doc ann)
deriving (Generic, Typeable)
-- |
-- @
-- x '<>' y = 'hcat' [x, y]
-- @
--
-- >>> "hello" <> "world" :: Doc ann
-- helloworld
instance Semigroup (Doc ann) where
(<>) = Cat
sconcat (x :| xs) = hcat (x:xs)
stimes n x
| n <= 0 = Empty
| n == 1 = x
| otherwise =
let n' = fromIntegral n
nx = hcat (replicate n' x)
in case x of
Fail -> Fail
Empty -> Empty
Char c -> Text n' (T.replicate n' (T.singleton c))
Text l t -> Text (n' * l) (T.replicate n' t)
Line -> nx
FlatAlt{} -> nx
Cat{} -> nx
Nest{} -> nx
Union{} -> nx
Column{} -> nx
WithPageWidth{} -> nx
Nesting{} -> nx
Annotated{} -> nx
-- |
-- @
-- 'mempty' = 'emptyDoc'
-- 'mconcat' = 'hcat'
-- @
--
-- >>> mappend "hello" "world" :: Doc ann
-- helloworld
instance Monoid (Doc ann) where
mempty = emptyDoc
mappend = (<>)
mconcat = hcat
-- | >>> pretty ("hello\nworld")
-- hello
-- world
--
-- This instance uses the 'Pretty' 'Text' instance, and uses the same newline to
-- 'line' conversion.
instance IsString (Doc ann) where
fromString = pretty . T.pack
-- | Alter the document’s annotations.
--
-- This instance makes 'Doc' more flexible (because it can be used in
-- 'Functor'-polymorphic values), but @'fmap'@ is much less readable compared to
-- using @'reAnnotate'@ in code that only works for @'Doc'@ anyway. Consider
-- using the latter when the type does not matter.
instance Functor Doc where
fmap = reAnnotate
-- | Overloaded conversion to 'Doc'.
--
-- Laws:
--
-- 1. output should be pretty. :-)
class Pretty a where
-- | >>> pretty 1 <+> pretty "hello" <+> pretty 1.234
-- 1 hello 1.234
pretty :: a -> Doc ann
default pretty :: Show a => a -> Doc ann
pretty = viaShow
-- | @'prettyList'@ is only used to define the @instance
-- 'Pretty' a => 'Pretty' [a]@. In normal circumstances only the @'pretty'@
-- function is used.
--
-- >>> prettyList [1, 23, 456]
-- [1, 23, 456]
prettyList :: [a] -> Doc ann
prettyList = align . list . map pretty
-- $
-- Issue #67: Nested lists were not aligned with »pretty«, leading to non-pretty
-- output, violating the Pretty class law.
--
-- >>> pretty (replicate 2 (replicate 4 (1, replicate 8 2)))
-- [ [ (1, [2, 2, 2, 2, 2, 2, 2, 2])
-- , (1, [2, 2, 2, 2, 2, 2, 2, 2])
-- , (1, [2, 2, 2, 2, 2, 2, 2, 2])
-- , (1, [2, 2, 2, 2, 2, 2, 2, 2]) ]
-- , [ (1, [2, 2, 2, 2, 2, 2, 2, 2])
-- , (1, [2, 2, 2, 2, 2, 2, 2, 2])
-- , (1, [2, 2, 2, 2, 2, 2, 2, 2])
-- , (1, [2, 2, 2, 2, 2, 2, 2, 2]) ] ]
instance Pretty a => Pretty (Const a b) where
pretty = pretty . getConst
#if FUNCTOR_IDENTITY_IN_BASE
-- | >>> pretty (Identity 1)
-- 1
instance Pretty a => Pretty (Identity a) where
pretty = pretty . runIdentity
#endif
-- | >>> pretty [1,2,3]
-- [1, 2, 3]
instance Pretty a => Pretty [a] where
pretty = prettyList
instance Pretty a => Pretty (NonEmpty a) where
pretty (x:|xs) = prettyList (x:xs)
-- | >>> pretty ()
-- ()
--
-- The argument is not used:
--
-- >>> pretty (error "Strict?" :: ())
-- ()
instance Pretty () where
pretty _ = "()"
-- | >>> pretty True
-- True
instance Pretty Bool where
pretty True = "True"
pretty False = "False"
-- | Instead of @('pretty' '\n')@, consider using @'line'@ as a more readable
-- alternative.
--
-- >>> pretty 'f' <> pretty 'o' <> pretty 'o'
-- foo
-- >>> pretty ("string" :: String)
-- string
instance Pretty Char where
pretty '\n' = line
pretty c = Char c
#ifdef MIN_VERSION_text
prettyList = pretty . (id :: Text -> Text) . fromString
#else
prettyList = vsep . map unsafeTextWithoutNewlines . T.splitOn "\n"
#endif
-- | Convenience function to convert a 'Show'able value to a 'Doc'. If the
-- 'String' does not contain newlines, consider using the more performant
-- 'unsafeViaShow'.
viaShow :: Show a => a -> Doc ann
viaShow = pretty . T.pack . show
-- | Convenience function to convert a 'Show'able value /that must not contain
-- newlines/ to a 'Doc'. If there may be newlines, use 'viaShow' instead.
unsafeViaShow :: Show a => a -> Doc ann
unsafeViaShow = unsafeTextWithoutNewlines . T.pack . show
-- | >>> pretty (123 :: Int)
-- 123
instance Pretty Int where pretty = unsafeViaShow
instance Pretty Int8 where pretty = unsafeViaShow
instance Pretty Int16 where pretty = unsafeViaShow
instance Pretty Int32 where pretty = unsafeViaShow
instance Pretty Int64 where pretty = unsafeViaShow
instance Pretty Word where pretty = unsafeViaShow
instance Pretty Word8 where pretty = unsafeViaShow
instance Pretty Word16 where pretty = unsafeViaShow
instance Pretty Word32 where pretty = unsafeViaShow
instance Pretty Word64 where pretty = unsafeViaShow
-- | >>> pretty (2^123 :: Integer)
-- 10633823966279326983230456482242756608
instance Pretty Integer where pretty = unsafeViaShow
#if NATURAL_IN_BASE
instance Pretty Natural where pretty = unsafeViaShow
#endif
-- | >>> pretty (pi :: Float)
-- 3.1415927
instance Pretty Float where pretty = unsafeViaShow
-- | >>> pretty (exp 1 :: Double)
-- 2.71828182845904...
instance Pretty Double where pretty = unsafeViaShow
-- | >>> pretty (123, "hello")
-- (123, hello)
instance (Pretty a1, Pretty a2) => Pretty (a1,a2) where
pretty (x1,x2) = tupled [pretty x1, pretty x2]
-- | >>> pretty (123, "hello", False)
-- (123, hello, False)
instance (Pretty a1, Pretty a2, Pretty a3) => Pretty (a1,a2,a3) where
pretty (x1,x2,x3) = tupled [pretty x1, pretty x2, pretty x3]
-- -- | >>> pretty (123, "hello", False, ())
-- -- (123, hello, False, ())
-- instance (Pretty a1, Pretty a2, Pretty a3, Pretty a4) => Pretty (a1,a2,a3,a4) where
-- pretty (x1,x2,x3,x4) = tupled [pretty x1, pretty x2, pretty x3, pretty x4]
--
-- -- | >>> pretty (123, "hello", False, (), 3.14)
-- -- (123, hello, False, (), 3.14)
-- instance (Pretty a1, Pretty a2, Pretty a3, Pretty a4, Pretty a5) => Pretty (a1,a2,a3,a4,a5) where
-- pretty (x1,x2,x3,x4,x5) = tupled [pretty x1, pretty x2, pretty x3, pretty x4, pretty x5]
--
-- -- | >>> pretty (123, "hello", False, (), 3.14, Just 2.71)
-- -- ( 123
-- -- , hello
-- -- , False
-- -- , ()
-- -- , 3.14
-- -- , 2.71 )
-- instance (Pretty a1, Pretty a2, Pretty a3, Pretty a4, Pretty a5, Pretty a6) => Pretty (a1,a2,a3,a4,a5,a6) where
-- pretty (x1,x2,x3,x4,x5,x6) = tupled [pretty x1, pretty x2, pretty x3, pretty x4, pretty x5, pretty x6]
--
-- -- | >>> pretty (123, "hello", False, (), 3.14, Just 2.71, [1,2,3])
-- -- ( 123
-- -- , hello
-- -- , False
-- -- , ()
-- -- , 3.14
-- -- , 2.71
-- -- , [1, 2, 3] )
-- instance (Pretty a1, Pretty a2, Pretty a3, Pretty a4, Pretty a5, Pretty a6, Pretty a7) => Pretty (a1,a2,a3,a4,a5,a6,a7) where
-- pretty (x1,x2,x3,x4,x5,x6,x7) = tupled [pretty x1, pretty x2, pretty x3, pretty x4, pretty x5, pretty x6, pretty x7]
-- | Ignore 'Nothing's, print 'Just' contents.
--
-- >>> pretty (Just True)
-- True
-- >>> braces (pretty (Nothing :: Maybe Bool))
-- {}
--
-- >>> pretty [Just 1, Nothing, Just 3, Nothing]
-- [1, 3]
instance Pretty a => Pretty (Maybe a) where
pretty = maybe mempty pretty
prettyList = prettyList . catMaybes
#ifdef MIN_VERSION_text
-- | Automatically converts all newlines to @'line'@.
--
-- >>> pretty ("hello\nworld" :: Text)
-- hello
-- world
--
-- Note that @'line'@ can be undone by @'group'@:
--
-- >>> group (pretty ("hello\nworld" :: Text))
-- hello world
--
-- Manually use @'hardline'@ if you /definitely/ want newlines.
instance Pretty Text where pretty = vsep . map unsafeTextWithoutNewlines . T.splitOn "\n"
-- | (lazy 'Text' instance, identical to the strict version)
instance Pretty Lazy.Text where pretty = pretty . Lazy.toStrict
#endif
-- | Finding a good example for printing something that does not exist is hard,
-- so here is an example of printing a list full of nothing.
--
-- >>> pretty ([] :: [Void])
-- []
instance Pretty Void where pretty = absurd
-- | @(unsafeTextWithoutNewlines s)@ contains the literal string @s@.
--
-- The string must not contain any newline characters, since this is an
-- invariant of the 'Text' constructor.
unsafeTextWithoutNewlines :: Text -> Doc ann
unsafeTextWithoutNewlines text = case T.uncons text of
Nothing -> Empty
Just (t,ext)
| T.null ext -> Char t
| otherwise -> Text (T.length text) text
-- | The empty document behaves like @('pretty' "")@, so it has a height of 1.
-- This may lead to surprising behaviour if we expect it to bear no weight
-- inside e.g. 'vcat', where we get an empty line of output from it ('parens'
-- for visibility only):
--
-- >>> vsep ["hello", parens emptyDoc, "world"]
-- hello
-- ()
-- world
--
-- Together with '<>', 'emptyDoc' forms the 'Monoid' 'Doc'.
emptyDoc :: Doc ann
emptyDoc = Empty
-- | @('nest' i x)@ lays out the document @x@ with the current nesting level
-- (indentation of the following lines) increased by @i@. Negative values are
-- allowed, and decrease the nesting level accordingly.
--
-- >>> vsep [nest 4 (vsep ["lorem", "ipsum", "dolor"]), "sit", "amet"]
-- lorem
-- ipsum
-- dolor
-- sit
-- amet
--
-- See also
--
-- * 'hang' ('nest' relative to current cursor position instead of
-- current nesting level)
-- * 'align' (set nesting level to current cursor position)
-- * 'indent' (increase indentation on the spot, padding with spaces).
nest
:: Int -- ^ Change of nesting level
-> Doc ann
-> Doc ann
nest 0 x = x -- Optimization
nest i x = Nest i x
-- | The @'line'@ document advances to the next line and indents to the current
-- nesting level.
--
-- >>> let doc = "lorem ipsum" <> line <> "dolor sit amet"
-- >>> doc
-- lorem ipsum
-- dolor sit amet
--
-- @'line'@ behaves like @'space'@ if the line break is undone by 'group':
--
-- >>> group doc
-- lorem ipsum dolor sit amet
line :: Doc ann
line = FlatAlt Line (Char ' ')
-- | @'line''@ is like @'line'@, but behaves like @'mempty'@ if the line break
-- is undone by 'group' (instead of @'space'@).
--
-- >>> let doc = "lorem ipsum" <> line' <> "dolor sit amet"
-- >>> doc
-- lorem ipsum
-- dolor sit amet
-- >>> group doc
-- lorem ipsumdolor sit amet
line' :: Doc ann
line' = FlatAlt Line mempty
-- | @softline@ behaves like @'space'@ if the resulting output fits the page,
-- otherwise like @'line'@.
--
-- Here, we have enough space to put everything in one line:
--
-- >>> let doc = "lorem ipsum" <> softline <> "dolor sit amet"
-- >>> putDocW 80 doc
-- lorem ipsum dolor sit amet
--
-- If we narrow the page to width 10, the layouter produces a line break:
--
-- >>> putDocW 10 doc
-- lorem ipsum
-- dolor sit amet
--
-- @
-- 'softline' = 'group' 'line'
-- @
softline :: Doc ann
softline = Union (Char ' ') Line
-- | @'softline''@ is like @'softline'@, but behaves like @'mempty'@ if the
-- resulting output does not fit on the page (instead of @'space'@). In other
-- words, @'line'@ is to @'line''@ how @'softline'@ is to @'softline''@.
--
-- With enough space, we get direct concatenation:
--
-- >>> let doc = "ThisWord" <> softline' <> "IsWayTooLong"
-- >>> putDocW 80 doc
-- ThisWordIsWayTooLong
--
-- If we narrow the page to width 10, the layouter produces a line break:
--
-- >>> putDocW 10 doc
-- ThisWord
-- IsWayTooLong
--
-- @
-- 'softline'' = 'group' 'line''
-- @
softline' :: Doc ann
softline' = Union mempty Line
-- | A @'hardline'@ is /always/ laid out as a line break, even when 'group'ed or
-- when there is plenty of space. Note that it might still be simply discarded
-- if it is part of a 'flatAlt' inside a 'group'.
--
-- >>> let doc = "lorem ipsum" <> hardline <> "dolor sit amet"
-- >>> putDocW 1000 doc
-- lorem ipsum
-- dolor sit amet
--
-- >>> group doc
-- lorem ipsum
-- dolor sit amet
hardline :: Doc ann
hardline = Line
-- | @('group' x)@ tries laying out @x@ into a single line by removing the
-- contained line breaks; if this does not fit the page, or when a 'hardline'
-- within @x@ prevents it from being flattened, @x@ is laid out without any
-- changes.
--
-- The 'group' function is key to layouts that adapt to available space nicely.
--
-- See 'vcat', 'line', or 'flatAlt' for examples that are related, or make good
-- use of it.
group :: Doc ann -> Doc ann
-- See note [Group: special flattening]
group x = case x of
Union{} -> x
FlatAlt a b -> case changesUponFlattening b of
Flattened b' -> Union b' a
AlreadyFlat -> Union b a
NeverFlat -> a
_ -> case changesUponFlattening x of
Flattened x' -> Union x' x
AlreadyFlat -> x
NeverFlat -> x
-- Note [Group: special flattening]
--
-- Since certain documents do not change under removal of newlines etc, there is
-- no point in creating a 'Union' of the flattened and unflattened version – all
-- this does is introducing two branches for the layout algorithm to take,
-- resulting in potentially exponential behavior on deeply nested examples, such
-- as
--
-- pathological n = iterate (\x -> hsep [x, sep []] ) "foobar" !! n
--
-- See https://github.com/quchen/prettyprinter/issues/22 for the corresponding
-- ticket.
data FlattenResult a
= Flattened a
-- ^ @a@ is likely flatter than the input.
| AlreadyFlat
-- ^ The input was already flat, e.g. a 'Text'.
| NeverFlat
-- ^ The input couldn't be flattened: It contained a 'Line' or 'Fail'.
instance Functor FlattenResult where
fmap f (Flattened a) = Flattened (f a)
fmap _ AlreadyFlat = AlreadyFlat
fmap _ NeverFlat = NeverFlat
-- | Choose the first element of each @Union@, and discard the first field of
-- all @FlatAlt@s.
--
-- The result is 'Flattened' if the element might change depending on the layout
-- algorithm (i.e. contains differently renderable sub-documents), and 'AlreadyFlat'
-- if the document is static (e.g. contains only a plain 'Empty' node).
-- 'NeverFlat' is returned when the document cannot be flattened because it
-- contains a hard 'Line' or 'Fail'.
-- See [Group: special flattening] for further explanations.
changesUponFlattening :: Doc ann -> FlattenResult (Doc ann)
changesUponFlattening = \doc -> case doc of
FlatAlt _ y -> Flattened (flatten y)
Line -> NeverFlat
Union x _ -> Flattened x
Nest i x -> fmap (Nest i) (changesUponFlattening x)
Annotated ann x -> fmap (Annotated ann) (changesUponFlattening x)
Column f -> Flattened (Column (flatten . f))
Nesting f -> Flattened (Nesting (flatten . f))
WithPageWidth f -> Flattened (WithPageWidth (flatten . f))
Cat x y -> case (changesUponFlattening x, changesUponFlattening y) of
(NeverFlat , _ ) -> NeverFlat
(_ , NeverFlat ) -> NeverFlat
(Flattened x' , Flattened y') -> Flattened (Cat x' y')
(Flattened x' , AlreadyFlat ) -> Flattened (Cat x' y)
(AlreadyFlat , Flattened y') -> Flattened (Cat x y')
(AlreadyFlat , AlreadyFlat ) -> AlreadyFlat
Empty -> AlreadyFlat
Char{} -> AlreadyFlat
Text{} -> AlreadyFlat
Fail -> NeverFlat
where
-- Flatten, but don’t report whether anything changes.
flatten :: Doc ann -> Doc ann
flatten = \doc -> case doc of
FlatAlt _ y -> flatten y
Cat x y -> Cat (flatten x) (flatten y)
Nest i x -> Nest i (flatten x)
Line -> Fail
Union x _ -> flatten x
Column f -> Column (flatten . f)
WithPageWidth f -> WithPageWidth (flatten . f)
Nesting f -> Nesting (flatten . f)
Annotated ann x -> Annotated ann (flatten x)
x@Fail -> x
x@Empty -> x
x@Char{} -> x
x@Text{} -> x
-- | By default, @('flatAlt' x y)@ renders as @x@. However when 'group'ed,
-- @y@ will be preferred, with @x@ as the fallback for the case when @y@
-- doesn't fit.
--
-- >>> let doc = flatAlt "a" "b"
-- >>> putDoc doc
-- a
-- >>> putDoc (group doc)
-- b
-- >>> putDocW 0 (group doc)
-- a
--
-- 'flatAlt' is particularly useful for defining conditional separators such as
--
-- @
-- softline = 'group' ('flatAlt' 'hardline' " ")
-- @
--
-- >>> let hello = "Hello" <> softline <> "world!"
-- >>> putDocW 12 hello
-- Hello world!
-- >>> putDocW 11 hello
-- Hello
-- world!
--
-- === __Example: Haskell's do-notation__
--
-- We can use this to render Haskell's do-notation nicely:
--
-- >>> let open = flatAlt "" "{ "
-- >>> let close = flatAlt "" " }"
-- >>> let separator = flatAlt "" "; "
-- >>> let prettyDo xs = group ("do" <+> align (encloseSep open close separator xs))
-- >>> let statements = ["name:_ <- getArgs", "let greet = \"Hello, \" <> name", "putStrLn greet"]
--
-- This is put into a single line with @{;}@ style if it fits:
--
-- >>> putDocW 80 (prettyDo statements)
-- do { name:_ <- getArgs; let greet = "Hello, " <> name; putStrLn greet }
--
-- When there is not enough space the statements are broken up into lines
-- nicely:
--
-- >>> putDocW 10 (prettyDo statements)
-- do name:_ <- getArgs
-- let greet = "Hello, " <> name
-- putStrLn greet
--
-- === Notes
--
-- Users should be careful to choose @x@ to be less wide than @y@.
-- Otherwise, if @y@ turns out not to fit the page, we fall back on an even
-- wider layout:
--
-- >>> let ugly = group (flatAlt "even wider" "too wide")
-- >>> putDocW 7 ugly
-- even wider
--
-- Also note that 'group' will flatten @y@:
--
-- >>> putDoc (group (flatAlt "x" ("y" <> line <> "y")))
-- y y
--
-- This also means that an "unflattenable" @y@ which contains a hard linebreak
-- will /never/ be rendered:
--
-- >>> putDoc (group (flatAlt "x" ("y" <> hardline <> "y")))
-- x
flatAlt
:: Doc ann -- ^ Default
-> Doc ann -- ^ Preferred when 'group'ed
-> Doc ann
flatAlt = FlatAlt
-- | @('align' x)@ lays out the document @x@ with the nesting level set to the
-- current column. It is used for example to implement 'hang'.
--
-- As an example, we will put a document right above another one, regardless of
-- the current nesting level. Without 'align'ment, the second line is put simply
-- below everything we've had so far:
--
-- >>> "lorem" <+> vsep ["ipsum", "dolor"]
-- lorem ipsum
-- dolor
--
-- If we add an 'align' to the mix, the @'vsep'@'s contents all start in the
-- same column:
--
-- >>> "lorem" <+> align (vsep ["ipsum", "dolor"])
-- lorem ipsum
-- dolor
align :: Doc ann -> Doc ann
align d = column (\k -> nesting (\i -> nest (k - i) d)) -- nesting might be negative!
-- | @('hang' i x)@ lays out the document @x@ with a nesting level set to the
-- /current column/ plus @i@. Negative values are allowed, and decrease the
-- nesting level accordingly.
--
-- >>> let doc = reflow "Indenting these words with hang"
-- >>> putDocW 24 ("prefix" <+> hang 4 doc)
-- prefix Indenting these
-- words with
-- hang
--
-- This differs from 'nest', which is based on the /current nesting level/ plus
-- @i@. When you're not sure, try the more efficient 'nest' first. In our
-- example, this would yield
--
-- >>> let doc = reflow "Indenting these words with nest"
-- >>> putDocW 24 ("prefix" <+> nest 4 doc)
-- prefix Indenting these
-- words with nest
--
-- @
-- 'hang' i doc = 'align' ('nest' i doc)
-- @
hang
:: Int -- ^ Change of nesting level, relative to the start of the first line
-> Doc ann
-> Doc ann
hang i d = align (nest i d)
-- | @('indent' i x)@ indents document @x@ by @i@ columns, starting from the
-- current cursor position.
--
-- >>> let doc = reflow "The indent function indents these words!"
-- >>> putDocW 24 ("prefix" <> indent 4 doc)
-- prefix The indent
-- function
-- indents these
-- words!
--
-- @
-- 'indent' i d = 'hang' i ({i spaces} <> d)
-- @
indent
:: Int -- ^ Number of spaces to increase indentation by
-> Doc ann
-> Doc ann
indent i d = hang i (spaces i <> d)
-- | @('encloseSep' l r sep xs)@ concatenates the documents @xs@ separated by
-- @sep@, and encloses the resulting document by @l@ and @r@.
--
-- The documents are laid out horizontally if that fits the page:
--
-- >>> let doc = "list" <+> align (encloseSep lbracket rbracket comma (map pretty [1,20,300,4000]))
-- >>> putDocW 80 doc
-- list [1,20,300,4000]
--
-- If there is not enough space, then the input is split into lines entry-wise
-- therwise they are laid out vertically, with separators put in the front:
--
-- >>> putDocW 10 doc
-- list [1
-- ,20
-- ,300
-- ,4000]
--
-- Note that @doc@ contains an explicit call to 'align' so that the list items
-- are aligned vertically.
--
-- For putting separators at the end of entries instead, have a look at
-- 'punctuate'.
encloseSep
:: Doc ann -- ^ left delimiter
-> Doc ann -- ^ right delimiter
-> Doc ann -- ^ separator
-> [Doc ann] -- ^ input documents
-> Doc ann
encloseSep l r s ds = case ds of
[] -> l <> r
[d] -> l <> d <> r
_ -> cat (zipWith (<>) (l : repeat s) ds) <> r
-- | Haskell-inspired variant of 'encloseSep' with braces and comma as
-- separator.
--
-- >>> let doc = list (map pretty [1,20,300,4000])
--
-- >>> putDocW 80 doc
-- [1, 20, 300, 4000]
--
-- >>> putDocW 10 doc
-- [ 1
-- , 20
-- , 300
-- , 4000 ]
list :: [Doc ann] -> Doc ann
list = group . encloseSep (flatAlt "[ " "[")
(flatAlt " ]" "]")
", "
-- | Haskell-inspired variant of 'encloseSep' with parentheses and comma as
-- separator.
--
-- >>> let doc = tupled (map pretty [1,20,300,4000])
--
-- >>> putDocW 80 doc
-- (1, 20, 300, 4000)
--
-- >>> putDocW 10 doc
-- ( 1
-- , 20
-- , 300
-- , 4000 )
tupled :: [Doc ann] -> Doc ann
tupled = group . encloseSep (flatAlt "( " "(")
(flatAlt " )" ")")
", "
-- | @(x '<+>' y)@ concatenates document @x@ and @y@ with a @'space'@ in
-- between.
--
-- >>> "hello" <+> "world"
-- hello world
--
-- @
-- x '<+>' y = x '<>' 'space' '<>' y
-- @
(<+>) :: Doc ann -> Doc ann -> Doc ann
x <+> y = x <> Char ' ' <> y
infixr 6 <+> -- like <>
-- | Concatenate all documents element-wise with a binary function.
--
-- @
-- 'concatWith' _ [] = 'mempty'
-- 'concatWith' (**) [x,y,z] = x ** y ** z
-- @
--
-- Multiple convenience definitions based on 'concatWith' are already predefined,
-- for example:
--
-- @
-- 'hsep' = 'concatWith' ('<+>')
-- 'fillSep' = 'concatWith' (\\x y -> x '<>' 'softline' '<>' y)
-- @
--
-- This is also useful to define customized joiners:
--
-- >>> concatWith (surround dot) ["Prettyprinter", "Render", "Text"]
-- Prettyprinter.Render.Text
concatWith :: Foldable t => (Doc ann -> Doc ann -> Doc ann) -> t (Doc ann) -> Doc ann
concatWith f ds
#if !(FOLDABLE_TRAVERSABLE_IN_PRELUDE)
| foldr (\_ _ -> False) True ds = mempty
#else
| null ds = mempty
#endif
| otherwise = foldr1 f ds
{-# INLINE concatWith #-}
{-# SPECIALIZE concatWith :: (Doc ann -> Doc ann -> Doc ann) -> [Doc ann] -> Doc ann #-}
-- | @('hsep' xs)@ concatenates all documents @xs@ horizontally with @'<+>'@,
-- i.e. it puts a space between all entries.
--
-- >>> let docs = Util.words "lorem ipsum dolor sit amet"
--
-- >>> hsep docs
-- lorem ipsum dolor sit amet
--
-- @'hsep'@ does not introduce line breaks on its own, even when the page is too
-- narrow:
--
-- >>> putDocW 5 (hsep docs)
-- lorem ipsum dolor sit amet
--
-- For automatic line breaks, consider using 'fillSep' instead.
hsep :: Foldable f => f (Doc ann) -> Doc ann
hsep = concatWith (<+>)
-- | @('vsep' xs)@ concatenates all documents @xs@ above each other. If a
-- 'group' undoes the line breaks inserted by @vsep@, the documents are
-- separated with a 'space' instead.
--
-- Using 'vsep' alone yields
--
-- >>> "prefix" <+> vsep ["text", "to", "lay", "out"]
-- prefix text
-- to
-- lay
-- out
--
-- 'group'ing a 'vsep' separates the documents with a 'space' if it fits the
-- page (and does nothing otherwise). See the @'sep'@ convenience function for
-- this use case.
--
-- The 'align' function can be used to align the documents under their first
-- element:
--