5 ]      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ Safe[WriterT output StateT [style] a!, but with a strict Writer value.The output, type is used to append data chunks to, the styleA is the member of a stack of styles to model nested styles with.#Add a new style to the style stack.Get the topmost style.&If the stack is empty, this raises an .4View the topmost style, but do not modify the stack.&If the stack is empty, this raises an .!Append a value to the output end.,Run the renderer and retrive the writing end    Safe  Raise a hard  if there is a   in a  .  Raise a hard H when an annotation terminator is encountered in an unannotated region. Raise a hard generic  when the   to   conversion fails.  Raise a hard  when the to  4 parser finishes without consuming the full input.    Safe6T[}+Options to influence the layout algorithms.Maximum number of characters that fit in one line. The layout algorithms will try not to exceed the set limit by inserting line breaks when applicable (e.g. via >).9Layouters should not exceed the specified space per line.The c is the number of characters, including whitespace, that fit in a line. A typical value is 80.The  is the ribbon with, i.e. the fraction of the total page width that can be printed on. This allows limiting the length of printable text per line. Values must be between 0 and 1, and 0.4 to 1 is typical.8Layouters should not introduce line breaks on their own.8List of nesting level/document pairs yet to be laid out.Decide whether a # fits the constraints given, namely page widthminimum nesting level to fit in:width in which to fit the first line; Nothing is unbounded Fusion depth parameter, used by |.]Do not dive deep into nested documents, fusing mostly concatenations of text nodes together.Recurse into all parts of the (], including different layout alternatives, and location-sensitive values such as created by U which cannot be fused before, but only during, the layout process. As a result, the performance cost of using deep fusion is often hard to predict, and depends on the interplay between page layout and document to prettyprint.YThis value should only be used if profiling shows it is significantly faster than using .The data type  SimpleDocE represents laid out documents and is used by the display functions.A simplified view is that ( = [],, and the layout functions pick one of the s. This means that " has all complexity contained in (f resolved, making it very easy to convert it to other formats, such as plain text or terminal output.To write your own (= to X converter, it is therefore sufficient to convert from e. The Render submodules provide some built-in converters to do so, and helpers to create own ones.!9Some layout algorithms use the Since the frequently used  of the J, which scales linearly with its length, we cache it in this constructor."Int! = indentation level for the line#,Add an annotation to the remaining document.$&Remove a previously pushed annotation.%Overloaded conversion to (.&,pretty 1 <+> pretty "hello" <+> pretty 1.234 1 hello 1.234'' is only used to define the  instance % a => % [a]#. In normal circumstances only the & function is used.prettyList [1, 23, 456] [1, 23, 456](The abstract data type ( annI represents pretty documents that have been annotated with data of type ann.#More specifically, a value of type ( 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 as7color information (e.g. when rendering to the terminal)1mouseover text (e.g. when rendering to rich HTML)Umetailed whether to show something or not (to allow simple or detailed versions)The simplest way to display a ( is via the  class.)putStrLn (show (vsep ["hello", "world"]))helloworld)kOccurs when flattening a line. The layouter will reject this document, choosing a more suitable rendering.*The empty document; unit of / (observationally)+invariant: char is not '\n',;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  of  is  O(length)#, we cache it in this constructor.- Line break.Lay out the first (, but when flattened (via @o), fall back to the second. The flattened version should in general be higher and narrower than the fallback./Concatenation of two documents0(Document indented by a number of columns1Invariant: first lines of first '(Doc ann)' longer than the first lines of the second one. Used to implement layout alternatives for @.2*React on the current cursor position, see T3#React on the document's width, see W4(React on the current nesting level, see U5"Add an annotation to the enclosed (h. Can be used for example to add styling directives or alt texts that can then be used by the renderer.6 Convert a able value to a ( . If the @ does not contain newlines, consider using the more performant 7.7 Convert a  able value that must not contain newlines to a (. If there are newlines, use 6 instead.8(unsafeText s) contains the literal string s.WThe string must not contain any newline characters, since this is an invariant of the  constructor.9 The empty document behaves like (& "")q, so it has a height of 1. This may lead to surprising behaviour if we expect it to bear no weight inside e.g. P0, where we get an empty line of output from it (` for visibility only):(vsep ["hello", parens emptyDoc, "world"]hello()worldTogether with , 9 forms the  (.:(: i x) lays out the document x2 with the current indentation level increased by iK. Negative values are allowed, and decrease the nesting level accordingly.?vsep [nest 4 (vsep ["lorem", "ipsum", "dolor"]), "sit", "amet"]lorem ipsum dolorsitamet See also D, C and E.;The ;N document advances to the next line and indents to the current nesting level.3let doc = "lorem ipsum" <> line <> "dolor sit amet"doc lorem ipsumdolor sit amet; behaves like q if the line break is undone by @: group doclorem ipsum dolor sit amet<< is like ;, but behaves like ! if the line break is undone by @ (instead of q).4let doc = "lorem ipsum" <> line' <> "dolor sit amet"doc lorem ipsumdolor sit amet group doclorem ipsumdolor sit amet=softline behaves like q8 if the resulting output fits the page, otherwise like ;.9Here, we have enough space to put everything in one line:7let doc = "lorem ipsum" <> softline <> "dolor sit amet"putDocW 80 doclorem ipsum dolor sit ametFIf we narrow the page to width 10, the layouter produces a line break:putDocW 10 doc lorem ipsumdolor sit amet = = @ ; >> is like =, but behaves like ? if the resulting output does not fit on the page (instead of q). In other words, ; is to < how = is to >./With enough space, we get direct concatenation:3let doc = "ThisWord" <> softline' <> "IsWayTooLong"putDocW 80 docThisWordIsWayTooLongFIf we narrow the page to width 10, the layouter produces a line break:putDocW 10 docThisWord IsWayTooLong > = @ < ?A ? is always% laid out as a line break, even when @ged or when there is plenty of space. Note that it might still be simply discarded if it is part of a B inside a @.7let doc = "lorem ipsum" <> hardline <> "dolor sit amet"putDocW 1000 doc lorem ipsumdolor sit amet group doc lorem ipsumdolor sit amet@(@ x) tries laying out x[ into a single line by removing the contained line breaks; if this does not fit the page, x' is laid out without any changes. The @B function is key to layouts that adapt to available space nicely.See P, ;, or B8 for examples that are related, or make good use of it.B(B x fallback) renders as x by default, but falls back to fallback when @(ed. Since the layout algorithms rely on @U having an effect of shortening the width of the contained text, careless usage of B< with wide fallbacks might lead to unappealingly long lines.BC is particularly useful for defining conditional separators such as  softHyphen = B  "-" softline = B q ; 7We can use this to render Haskell's do-notation nicely:!let open = flatAlt "" "{ "!let close = flatAlt "" " }"!let separator = flatAlt "" "; "Elet prettyDo xs = group ("do" <+> 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)Gdo { name:_ <- getArgs; let greet = "Hello, " <> name; putStrLn greet }OWhen 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 greetC(C x) lays out the document xX with the nesting level set to the current column. It is used for example to implement D.qAs an example, we will put a document right above another one, regardless of the current nesting level. Without CGment, the second line is put simply below everything we've had so far,#"lorem" <+> vsep ["ipsum", "dolor"] lorem ipsumdolor If we add an C to the mix, the L*'s contents all start in the same column,+"lorem" <+> align (vsep ["ipsum", "dolor"]) lorem ipsum dolorD(D i x) lays out the document x" with a nesting level set to the current column plus iK. Negative values are allowed, and decrease the nesting level accordingly.2let doc = reflow "Indenting these words with hang"$putDocW 24 ("prefix" <+> hang 4 doc)prefix Indenting these words with hangThis differs from :, which is based on the current nesting level plus i/. When you're not sure, try the more efficient :) first. In our example, this would yield2let doc = reflow "Indenting these words with nest"$putDocW 24 ("prefix" <+> nest 4 doc)prefix Indenting these words with nest D i doc = C (: i doc) E(E i x) indents document x with i4 spaces, 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! E i d = D i ({i spaces} <> d) F(F 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,Tlet doc = "list" <+> encloseSep lbracket rbracket comma (map pretty [1,20,300,4000])putDocW 80 doclist [1,20,300,4000]If there is not enough space, then the input is split into lines entry-wise therwise they are aligned vertically, with separators put in the front:putDocW 10 doclist [1 ,20 ,300 ,4000]FFor putting separators at the end of entries instead, have a look at S.GHaskell-inspired variant of F% 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 ]HHaskell-inspired variant of F* 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 )I(x I y) concatenates document x and y with a q in between."hello" <+> "world" hello world x I y = x  q  y J>Concatenate all documents element-wise with a binary function. J _ [] =  J (**) [x,y,z] = x ** y ** z *Multiple convenience definitions based on J$ are alredy predefined, for example K = J (I) M = J (\x y -> x  =  y) 1This is also useful to define customized joiners,@concatWith (surround dot) ["Data", "Text", "Prettyprint", "Doc"]Data.Text.Prettyprint.DocK(K xs) concatenates all documents xs horizontally with I,, i.e. it puts a space between all entries.2let docs = Util.words "lorem ipsum dolor sit amet" hsep docslorem ipsum dolor sit ametKN 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 M instead.L(L xs) concatenates all documents xs above each other. If a @$ undoes the line breaks inserted by vsep&, the documents are separated with a q instead.Using L alone yields."prefix" <+> vsep ["text", "to", "lay", "out"] prefix texttolayout@ing a L separates the documents with a q< if it fits the page (and does nothing otherwise). See the N) convenience function for this use case.The CH function can be used to align the documents under their first element:6"prefix" <+> align (vsep ["text", "to", "lay", "out"]) prefix text to lay outSince @ing a L is rather common, N is a built-in for doing that.M(M xs) concatenates the documents xs horizontally with I. as long as it fits the page, then inserts a ;0 and continues doing that for all documents in xs. (; means that if @(ed, the documents are separated with a q instead of newlines. Use Q if you do not want a q.)(Let's print some words to fill the line:Elet docs = take 20 (cycle ["lorem", "ipsum", "dolor", "sit", "amet"])%putDocW 80 ("Docs:" <+> fillSep docs)MDocs: lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor#sit amet lorem ipsum dolor sit amet8The same document, printed at a width of only 40, yields%putDocW 40 ("Docs:" <+> fillSep docs)&Docs: lorem ipsum dolor sit amet lorem&ipsum dolor sit amet lorem ipsum dolor#sit amet lorem ipsum dolor sit ametN(N xs) tries laying out the documents xs separated with qjs, and if this does not fit the page, separates them with newlines. This is what differentiates it from L8, which always layouts its contents beneath each other.7let doc = "prefix" <+> sep ["text", "to", "lay", "out"]putDocW 80 docprefix text to lay out>With a narrower layout, the entries are separated by newlines:putDocW 20 doc prefix texttolayout N = @ . L O(O xs) concatenates all documents xs horizontally with  (i.e. without any spacing).>It is provided only for consistency, since it is identical to .)let docs = Util.words "lorem ipsum dolor" hcat docsloremipsumdolorP(P xs)' vertically concatenates the documents xs . If it is @ ed, the line breaks are removed.In other words P is like L0, with newlines removed instead of replaced by qs.)let docs = Util.words "lorem ipsum dolor" vcat docsloremipsumdolorSince @ing a P is rather common, R is a built-in shortcut for it.Q(Q xs) concatenates documents xs horizontally with . as long as it fits the page, then inserts a <0 and continues doing that for all documents in xs. This is similar to how an ordinary word processor lays out the text if you just keep typing after you hit the maximum line length.(< means that if @Ged, the documents are separated with nothing instead of newlines. See M if you want a q instead.)Observe the difference between M and Q. M concatenates the entries qd when @ed,Glet docs = take 20 (cycle (["lorem", "ipsum", "dolor", "sit", "amet"]))0putDocW 40 ("Grouped:" <+> group (fillSep docs))#Grouped: lorem ipsum dolor sit amet&lorem ipsum dolor sit amet lorem ipsum$dolor sit amet lorem ipsum dolor sitametOn the other hand, Q) concatenates the entries directly when @ed,0putDocW 40 ("Grouped:" <+> group (fillCat docs))$Grouped: loremipsumdolorsitametlorem'ipsumdolorsitametloremipsumdolorsitametloremipsumdolorsitametR(R xs) tries laying out the documents xs separated with nothing, and if this does not fit the page, separates them with newlines. This is what differentiates it from P8, which always layouts its contents beneath each other.)let docs = Util.words "lorem ipsum dolor"!putDocW 80 ("Docs:" <+> cat docs)Docs: loremipsumdolorDWhen there is enough space, the documents are put above one another,!putDocW 10 ("Docs:" <+> cat docs) Docs: loremipsumdolor R = @ . P S(S p xs) appends p! to all but the last document in xs.Dlet docs = punctuate comma (Util.words "lorem ipsum dolor sit amet")putDocW 80 (hsep docs)lorem, ipsum, dolor, sit, ametiThe separators are put at the end of the entries, which we can see if we position the result vertically:putDocW 20 (vsep docs)lorem,ipsum,dolor,sit,amet]If you want put the commas in front of their elements instead of at the end, you should use H or, in general, F.T:Layout a document depending on which column it starts at. C is implemented in terms of T.6column (\l -> "Columns are" <+> pretty l <> "-based.")Columns are 0-based.@let doc = "prefix" <+> column (\l -> "| <- column" <+> pretty l)"vsep [indent n doc | n <- [0,4,8]]prefix | <- column 7 prefix | <- column 11 prefix | <- column 15U+Layout a document depending on the current : ing level. C is implemented in terms of U.Hlet doc = "prefix" <+> nesting (\l -> brackets ("Nested:" <+> pretty l))"vsep [indent n doc | n <- [0,4,8]]prefix [Nested: 0] prefix [Nested: 4] prefix [Nested: 8]V(V doc f) lays out the document doc<, and makes the column width of it available to a function.Ilet annotate doc = width (brackets doc) (\w -> " <- width:" <+> pretty w)[align (vsep (map annotate ["---", "------", indent 3 "---", vsep ["---", indent 4 "---"]]))[---] <- width: 5[------] <- width: 8[ ---] <- width: 8[--- ---] <- width: 8WILayout a document depending on the page width, if one has been specified.glet prettyPageWidth (AvailablePerLine l r) = "Width:" <+> pretty l <> ", ribbon fraction:" <+> pretty r=let doc = "prefix" <+> pageWidth (brackets . prettyPageWidth)/putDocW 32 (vsep [indent n doc | n <- [0,4,8]])(prefix [Width: 32, ribbon fraction: 1.0], prefix [Width: 32, ribbon fraction: 1.0]0 prefix [Width: 32, ribbon fraction: 1.0]X(X i x) lays out the document x. It then appends spaces until the width is equal to i. If the width of x) is already larger, nothing is appended.GThis function is quite useful in practice to output a list of bindings:Wlet types = [("empty","Doc"), ("nest","Int -> Doc -> Doc"), ("fillSep","[Doc] -> Doc")]Blet ptype (name, tp) = fill 5 (pretty name) <+> "::" <+> pretty tp("let" <+> align (vcat (map ptype types))let empty :: Doc nest :: Int -> Doc -> Doc fillSep :: [Doc] -> DocY(Y i x) first lays out the document x. It then appends spaces until the width is equal to i. If the width of x is already larger than i$, the nesting level is increased by i and a line is appended. When we redefine ptype in the example given in X to use Y+, we get a useful variation of the output:Wlet types = [("empty","Doc"), ("nest","Int -> Doc -> Doc"), ("fillSep","[Doc] -> Doc")]Glet ptype (name, tp) = fillBreak 5 (pretty name) <+> "::" <+> pretty tp("let" <+> align (vcat (map ptype types))let empty :: Doc nest :: Int -> Doc -> Doc fillSep :: [Doc] -> DocZ6Insert a number of spaces. Negative values count as 0.[([ n one many) is one if n is 1, and many8 otherwise. A typical use case is adding a plural "s".let things = [True]let amount = length thingsD"The list has" <+> pretty amount <+> plural "entry" "entries" amountThe list has 1 entry\(\ l r x) encloses document x between documents l and r using .enclose "A" "Z" ""AZ \ l r x = l  x  r ](] x l r) surrounds document x with l and r.surround "" "A" "Z"AZ)This is merely an argument reordering of \", but allows for definitions like@concatWith (surround ".") ["Data", "Text", "Prettyprint", "Doc"]Data.Text.Prettyprint.Doc^ squotes ""''_ dquotes """"` parens ""()a angles ""<>b brackets ""[]c braces ""{}dsquote'edquote"flparen(grparen)hlangle<irangle>jlbracket[krbracket]llbrace{mrbrace}nsemi;ocolon:pcomma,q"a" <> space <> "b"a bThis is mostly used via I, "a" <+> "b"a brdot.sslash/t backslash\uequals=vpipe|wAdd an annotation to a (. This annotation can then be used by the renderer to e.g. add color to certain parts of the output. For a full tutorial example on how to use it, see the ?Data.Text.Prettyprint.Doc.Render.Tutorials.StackMachineTutorial or @Data.Text.Prettyprint.Doc.Render.Tutorials.TreeRenderingTutorial modules.This function is only relevant for custom formats with their own annotations, and not relevant for basic prettyprinting. The predefined renderers, e.g. %Data.Text.Prettyprint.Doc.Render.Text., should be enough for the most common needs.xRemove all annotations. Although x) is idempotent with respect to rendering, x . x = x it should not be used without caution, for each invocation traverses the entire contained document. If possible, it is preferrable to unannotate after producing the layout by using z.yChange the annotation of a (ument.kUseful in particular to embed documents with one form of annotation in a more generlly annotated document. Since this traverses the entire (L tree, it is preferrable to reannotate after producing the layout by using {. Technically y makes ( a C, but since reannotation is hardly intuitive we omit the instance.zRemove all annotations. x for .{%Change the annotation of a document. y for .|(| depth doc) combines text nodes so they can be rendered more efficiently. A fused document is always laid out identical to its unfused version.When laying a (ument out to a , every component of the input is translated directly to the simpler output format. This sometimes yields undesirable chunking when many pieces have been concatenated together. For example"a" <> "b" <> pretty 'c' <> "d"abcd(results in a chain of four entries in a :, although this is fully equivalent to the tightly packed"abcd" :: Doc annabcdwhich is only a single $ entry, and can be processed faster.#It is therefore a good idea to run |F on concatenations of lots of small strings that are used many times,>let oftenUsed = fuse Shallow ("a" <> "b" <> pretty 'c' <> "d")hsep (replicate 5 oftenUsed)abcd abcd abcd abcd abcd}The default layout options, suitable when you just want some output, and don t particularly care about the details. Used by the  instance, for example.defaultLayoutOptions9LayoutOptions {layoutPageWidth = AvailablePerLine 80 0.4}~8This is the default layout algorithm, and it is used by , putDoc and hPutDoc.~~ commits to rendering something in a certain way if the next element fits the layout constraints; in other words, it has one \ element lookahead when rendering. Consider using the smarter, but a bit less performant, Z algorithm if the results seem to run off to the right before having lots of line breaks.,A layout algorithm with more lookahead than ~h, that introduces line breaks earlier if the content does not (or will not, rather) fit into one line.+Considre the following python-ish document,4let fun x = hang 2 ("fun(" <> softline' <> x) <> ")"Dlet doc = (fun . fun . fun . fun . fun) (list ["abcdef", "ghijklm"])gwhich we ll be rendering using the following pipeline (where the layout algorithm has been left open),import Data.Text.IO as T,import Data.Text.Prettyprint.Doc.Render.Text6let hr = pipe <> pretty (replicate (26-2) '-') <> pipeulet go layouter x = (T.putStrLn . renderStrict . layouter (LayoutOptions (AvailablePerLine 26 1))) (vsep [hr, x, hr])If we render this using ~7 with a page width of 26 characters per line, all the fun: calls fit into the first line so they will be put there,go layoutPretty doc|------------------------|fun(fun(fun(fun(fun( [ abcdef" , ghijklm ])))))|------------------------|^Note that this exceeds the desired 26 character page width. The same document, rendered with , fits the layout contstraints:go layoutSmart doc |------------------------|fun( fun( fun( fun( fun( [ abcdef , ghijklm ])))))|------------------------|The key difference between ~ and  is that the latter will check the potential document up to the end of the current indentation level, instead of just having one element lookahead.(layoutCompact x) lays out the document x without adding any indentation. Since no 'pretty' printing is involved, this layouter is very fast. The resulting output contains fewer characters than a prettyprinted version and can be used for output that is read by other programs.?This layout function does not add any colorisation information.Jlet doc = hang 4 (vsep ["lorem", "ipsum", hang 4 (vsep ["dolor", "sit"])])doclorem ipsum dolor sit=let putDocCompact = renderIO System.IO.stdout . layoutCompactputDocCompact docloremipsumdolorsit Render a  to a , useful to write ' instances based on the prettyprinter.  instance  MyType where  _ =  . ~ } . & ( doc) prettyprints document doc with }, ignoring all annotations.BI tried finding a good example to show here but could not find one(lazy + instance, identical to the strict version)'Automatically converts all newlines to ;.pretty ("hello\nworld" :: Text)helloworld Note that ; can be undone by @:'group (pretty ("hello\nworld" :: Text)) hello world Manually use ? if you  definitely want newlines.Ignore  s, print  contents.pretty (Just True)True'braces (pretty (Nothing :: Maybe Bool)){})pretty [Just 1, Nothing, Just 3, Nothing][1, 3]pretty (123, "hello", False)(123, hello, False)pretty (123, "hello") (123, hello)pretty (exp 1 :: Double)2.718281828459045pretty (pi :: Float) 3.1415927pretty (2^123 :: Integer)&10633823966279326983230456482242756608pretty (123 :: Int)123 Instead of (& '\n'), consider using ;! as a more readable alternative.&pretty 'f' <> pretty 'o' <> pretty 'o'foopretty ("string" :: String)string pretty TrueTrue pretty ()()The argument is not used,pretty (error "Strict?" :: ())()7Does not change the text, but removes all annotations. Pitfallm: since this un-annotates its argument, nesting it means multiple, potentially costly, traversals over the (. pretty 123123pretty (pretty 123)123pretty [1,2,3] [1, 2, 3]pretty ("hello\nworld")helloworldThis instance uses the % ) instance, and uses the same newline to ; conversion.  = 9  = O "mappend "hello" "world" :: Doc ann helloworld x  y = O [x, y] "hello" <> "world" :: Doc ann helloworld !"#$%&'()*+,-./0123456789:Change of nesting level;<=>?@ABDefaultFallback when @edCD@Change of nesting level, relative to the start of the first lineE+Number of spaces to increase indentation byFleft delimiterright delimiter separatorinput documentsGHIJKLMNOPQRSPunctuation, e.g. pTUVWX6Append spaces until the document is at least this wideY6Append spaces until the document is at least this wideZ[1 case other cases\LRxLxR]^_`abcdefghijklmnopqrstuvwxyz{|}~u !"#$%&'(+,)*-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~()*+,-./012345%&&'67 !"#$89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~s !"#$%&&'( )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ Safe(+,)*-./012345()*+,-./012345SafeDaan Leijen (c) 2000, http://www.cs.uu.nl/~daan Max Bolingbroke (c) 2008, http://blog.omega-prime.co.uk David Luposchainsky (c) 2016, http://github.com/quchen#BSD-style (see the file LICENSE.md)/David Luposchainsky <dluposchainsky () google> experimentalportableSafe\ !"#$%&'(9:;<=>?@BCDEFGHIJKLMNOPQRSTUVWXY[\]^_`abcdefghijklmnopqrstuvwxyz{|}~](%&&'9:;<=>?@BCDEFGHIJKLMNOPQRSTUVWXY[\]^_`abcfghilmjkdenopqrstuvwxyz{| !"#$}~Safe[( sdoc) takes the output sdoc; from a rendering function and transforms it to lazy text.Ilet render = TL.putStrLn . renderLazy . layoutPretty defaultLayoutOptionsPlet doc = "lorem" <+> align (vsep ["ipsum dolor", parens "foo bar", "sit amet"]) render doclorem ipsum dolor (foo bar) sit amet( sdoc) takes the output sdoc4 from a rendering and transforms it to strict text.( h sdoc) writes sdoc to the file h.LrenderIO System.IO.stdout (layoutPretty defaultLayoutOptions "hello\nworld")helloworld( doc) prettyprints document doc to standard output. Uses the }.putDoc ("hello" <+> "world") hello world  =   Like , but instead of using F, print to a user-provided handle, e.g. a file or a socket. Uses the }. main =  filename (h ->  h doc) where doc = P4 ["vertical", "text"] filename = "someFile.txt"  h doc =  h (~ } doc) Safe[The  type defines a stack machine suitable for many rendering needs. It has two auxiliary parameters: the type of the end result, and the type of the document s annotations.Most I creations will look like this definition: a recursive walk through the R, pushing styles on the stack and popping them off again, and writing raw output.@The equivalent to this in the tree based rendering approach is . Convert a q annotation to a pair of opening and closing tags. This is where the translation of style to raw output happens.2We can now wrap our stack machine definition from [ in a nicer interface; on successful conversion, we run the builder to give us the final , and before we do that we check that the style stack is empty (i.e. there are no unmatched style applications) after the machine is run.1This function does only a bit of plumbing around g, and is the main API function of a stack machine renderer. The tree renderer equivalent to this is . Safe[A 5 is a linked list of different annotated cons cells (! and then some further , " and then some further 6, &). This format is very suitable as a target for a layout engine, but not very useful for rendering to a structured format such as HTML, where we don t want to do a lookahead until the end of some markup. These formats benefit from a tree-like structure that explicitly marks its contents as annotated.  is that format.DA type for parsers of unique results. Token stream s, results a.3Hand-written to avoid a dependency on a parser lib.0Get the next token, consuming it in the process. Convert a  to its  representation.Remove all annotations. x for .%Change the annotation of a document. y for .           Safe[)To render the HTML, we first convert the  to the @ format, which makes enveloping sub-documents in markup easier.This function is the entry main API function of the renderer; as such, it is only glue for the internal functions. This is similar to 1 from the stack machine tutorial in its purpose. Render a  to a R; this is the workhorse of the tree-based rendering approach, and equivalent to * in the stack machine rendering tutorial. Convert a  to a function that encloses a M in HTML tags. This is where the translation of style to raw output happens.  SafeSplit an input into word-sized (s.+putDoc (tupled (words "Lorem ipsum dolor"))(Lorem, ipsum, dolor)vInsert soft linebreaks between words, so that text is broken into multiple lines when it exceeds the available width.putDocW 32 (reflow "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")Lorem ipsum dolor sit amet,consectetur adipisicing elit, sed do eiusmod tempor incididuntut labore et dolore magnaaliqua.  = M .  Render a document with a certain width. Useful for quick-and-dirty testing of layout behaviour. Used heavily in the doctests of this package, for example.Klet doc = reflow "Lorem ipsum dolor sit amet, consectetur adipisicing elit"putDocW 20 docLorem ipsum dolor sit amet, consecteturadipisicing elitputDocW 30 docLorem ipsum dolor sit amet,consectetur adipisicing elit !""#$%&'()*+,-./  0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  ==     (prettyprinter-0.1-IvyYFUS1clHDHa66TeRnVCData.Text.Prettyprint.Doc2Data.Text.Prettyprint.Doc.Render.Util.StackMachine+Data.Text.Prettyprint.Doc.Render.Util.Panic"Data.Text.Prettyprint.Doc.Internal%Data.Text.Prettyprint.Doc.Render.Text?Data.Text.Prettyprint.Doc.Render.Tutorials.StackMachineTutorial3Data.Text.Prettyprint.Doc.Render.Util.SimpleDocTree@Data.Text.Prettyprint.Doc.Render.Tutorials.TreeRenderingTutorialData.Text.Prettyprint.Doc.UtilSFail SimpleDoc SimpleDocTree'Data.Text.Prettyprint.Doc.Internal.Type&Data.Text.Prettyprint.Doc.Render.ShowS renderTreerenderrenderStackMachinebaseData.Semigroup<> StackMachine pushStyleunsafePopStyleunsafePeekStyle writeOutputexecStackMachine$fMonadStackMachine$fApplicativeStackMachine$fFunctorStackMachinepanicUncaughtFailpanicUnpairedPop"panicSimpleDocTreeConversionFailedpanicInputNotFullyConsumed LayoutOptionslayoutPageWidth PageWidthAvailablePerLine UnboundedLayoutPipelineNilConsUndoAnnFittingPredicateFP FusionDepthShallowDeepSEmptySCharSTextSLineSAnnPushSAnnPopPrettypretty prettyListDocFailEmptyCharTextLineFlatAltCatNestUnionColumn WithPageWidthNesting AnnotatedviaShow unsafeViaShow unsafeTextemptyDocnestlineline'softline softline'hardlinegroupflattenflatAltalignhangindent encloseSeplisttupled<+> concatWithhsepvsepfillSepsephcatvcatfillCatcat punctuatecolumnnestingwidth pageWidthfill fillBreakspacespluralenclosesurroundsquotesdquotesparensanglesbracketsbracessquotedquotelparenrparenlangleranglelbracketrbracketlbracerbracesemicoloncommaspacedotslash backslashequalspipeannotate unAnnotate reAnnotate unAnnotateS reAnnotateSfusedefaultLayoutOptions layoutPretty layoutSmart layoutFits layoutCompact renderShowS $fShowDoc $fPrettyVoid $fPrettyText $fPrettyText0 $fPrettyMaybe $fPretty(,,) $fPretty(,)$fPrettyDouble $fPrettyFloat$fPrettyNatural$fPrettyInteger$fPrettyWord64$fPrettyWord32$fPrettyWord16 $fPrettyWord8 $fPrettyWord $fPrettyInt64 $fPrettyInt32 $fPrettyInt16 $fPrettyInt8 $fPrettyInt $fPrettyChar $fPrettyBool $fPretty() $fPrettyDoc$fPrettyNonEmpty $fPretty[] $fIsStringDoc $fMonoidDoc$fSemigroupDoc $fEqSimpleDoc$fOrdSimpleDoc$fShowSimpleDoc$fEqFusionDepth$fOrdFusionDepth$fShowFusionDepth $fEqPageWidth$fOrdPageWidth$fShowPageWidth$fEqLayoutOptions$fOrdLayoutOptions$fShowLayoutOptions renderLazy renderStrictrenderIOputDochPutDocColorRedGreenBlue SimpleHtmlBoldItalics ParagraphHeadlinebolditalics paragraphheadlinecolorhtmlTagSTEmptySTCharSTTextSTLineSTAnnSTConcattreeForm unAnnotateST reAnnotateST$fAlternativeUniqueParser$fMonadFailUniqueParser$fMonadUniqueParser$fApplicativeUniqueParser$fFunctorUniqueParser$fEqSimpleDocTok$fOrdSimpleDocTok$fShowSimpleDocTok$fEqSimpleDocTree$fOrdSimpleDocTree$fShowSimpleDocTreeencloseInTagForwordsreflowputDocWGHC.Errerrorreportghc-prim GHC.TypesIntDouble#text-1.2.2.1-9Yh8rJoh8fO2JMLWffT3Qs Data.TextlengthData.Text.InternalGHC.ShowShowGHC.BaseStringMonoidmemptymconcatFunctorshowShowS showsPrecNothingJustGHC.IO.Handle.FDstdout System.IOwithFileData.Text.Internal.Lazy UniqueParser nextToken SimpleDocTokTokEmptyTokCharTokTextTokLine TokAnnPush TokAnnPop runParsersdocToTreeParserData.Text.Internal.BuilderBuilder