prettyprinter-0.1: A modern, extensible and well-documented prettyprinter.

CopyrightDaan 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
LicenseBSD-style (see the file LICENSE.md)
MaintainerDavid Luposchainsky <dluposchainsky (λ) google>
Stabilityexperimental
Portabilityportable
Safe HaskellSafe
LanguageHaskell2010

Data.Text.Prettyprint.Doc

Contents

Description

Overview

This module defines a prettyprinter to format text in a flexible and convenient way. The idea is to combine a Document out of many small components, then using a layouter to convert it to an easily renderable SimpleDoc, which can then be rendered to a variety of formats, for example plain Text.

The documentation consists of several parts:

  1. Just below is some general information about the library.
  2. The actual library with extensive documentation and examples
  3. Migration guide for users familiar with (ansi-)wl-pprint

Starting out

As a reading list for starters, some of the most commonly used functions in this module include <>, hsep, <+>, vsep, align, hang. These cover many use cases already, and many other functions are variations or combinations of these.

Simple example

Let’s prettyprint a simple Haskell type definition. First, intersperse -> and add a leading ::,

>>> let prettyType = align . sep . zipWith (<+>) ("::" : repeat "->")

The sep function is one way of concatenating documents, there are multiple others, e.g. vsep, cat and fillSep. In our case, sep space-separates all entries if there is space, and newlines if the remaining line is too short.

Second, prepend the name to the type,

>>> let prettyDecl n tys = pretty n <+> prettyType tys

Now we can define a document that contains some type signature:

>>> let doc = prettyDecl "example" ["Int", "Bool", "Char", "IO ()"]

This document can now be printed, and it automatically adapts to available space. If the page is wide enough (80 characters in this case), the definitions are space-separated,

>>> putDocW 80 doc
example :: Int -> Bool -> Char -> IO ()

If we narrow the page width to only 20 characters, the same document renders vertically aligned:

>>> putDocW 20 doc
example :: Int
        -> Bool
        -> Char
        -> IO ()

Speaking of alignment, had we not used align, the -> would be at the beginning of each line, and not beneath the ::.

General workflow

╭───────────────╮      ╭───────────────────╮
│ vsep, pretty, │      │        Doc        │
│ <+>, nest,    ├─────▷│  (rich document)  │
│ align, …      │      ╰─────────┬─────────╯
╰───────────────╯                │
                                 │ Layout algorithms
                                 │ e.g. layoutPretty
                                 ▽
                       ╭───────────────────╮
                       │     SimpleDoc     │
                       │ (simple document) │
                       ╰─────────┬─────────╯
                                 │
                                 │ Renderers
                                 │
             ╭───────────────────┼───────────────────╮
             │                   │                   │
             ▽                   ▽                   ▽
     ╭───────────────╮   ╭───────────────╮   ╭───────────────╮
     │  Plain Text   │   │ ANSI terminal │   │ other/custom  │
     ╰───────────────╯   ╰───────────────╯   ╰───────────────╯

How the layout works

There are two key concepts to laying a document out: the available width, and grouping.

Available width

The page has a certain maximum width, which the layouter tries to not exceed, by inserting line breaks where possible. The functions given in this module make it fairly straightforward to specify where, and under what circumstances, such a line break may be inserted by the layouter, for example via the sep function.

There is also the concept of ribbon width. The ribbon is the part of a line that is printed, i.e. the line length without the leading indentation. The layouters take a ribbon fraction argument, which specifies how much of a line should be filled before trying to break it up. A ribbon width of 0.5 in a document of width 80 will result in the layouter to try to not exceed 0.5*80 = 40 (ignoring current indentation depth).

Grouping

A document can be grouped, which tells the layouter that it should attempt to collapse it to a single line. If the result does not fit within the constraints (given by page and ribbon widths), the document is rendered unaltered. This allows fallback definitions, so that we get nice results even when the original document would exceed the layout constraints.

Synopsis

Documents

data Doc ann Source #

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)
  • metailed 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

Instances

Show (Doc ann) Source #

(show doc) prettyprints document doc with defaultLayoutOptions, ignoring all annotations.

Methods

showsPrec :: Int -> Doc ann -> ShowS #

show :: Doc ann -> String #

showList :: [Doc ann] -> ShowS #

IsString (Doc ann) Source #
>>> pretty ("hello\nworld")
hello
world

This instance uses the Pretty Text instance, and uses the same newline to line conversion.

Methods

fromString :: String -> Doc ann #

Semigroup (Doc ann) Source #
x <> y = hcat [x, y]
>>> "hello" <> "world" :: Doc ann
helloworld

Methods

(<>) :: Doc ann -> Doc ann -> Doc ann #

sconcat :: NonEmpty (Doc ann) -> Doc ann #

stimes :: Integral b => b -> Doc ann -> Doc ann #

Monoid (Doc ann) Source #
mempty = emptyDoc
mconcat = hcat
>>> mappend "hello" "world" :: Doc ann
helloworld

Methods

mempty :: Doc ann #

mappend :: Doc ann -> Doc ann -> Doc ann #

mconcat :: [Doc ann] -> Doc ann #

Pretty (Doc ann) Source #

Does not change the text, but removes all annotations. Pitfall: since this un-annotates its argument, nesting it means multiple, potentially costly, traversals over the Doc.

>>> pretty 123
123
>>> pretty (pretty 123)
123

Methods

pretty :: Doc ann -> Doc ann Source #

prettyList :: [Doc ann] -> Doc ann Source #

Basic functionality

class Pretty a where Source #

Overloaded conversion to Doc.

Methods

pretty :: a -> Doc ann Source #

>>> pretty 1 <+> pretty "hello" <+> pretty 1.234
1 hello 1.234

pretty :: Show a => a -> Doc ann Source #

>>> pretty 1 <+> pretty "hello" <+> pretty 1.234
1 hello 1.234

prettyList :: [a] -> Doc ann Source #

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]

Instances

Pretty Bool Source #
>>> pretty True
True

Methods

pretty :: Bool -> Doc ann Source #

prettyList :: [Bool] -> Doc ann Source #

Pretty Char Source #

Instead of (pretty '\n'), consider using line as a more readable alternative.

>>> pretty 'f' <> pretty 'o' <> pretty 'o'
foo
>>> pretty ("string" :: String)
string

Methods

pretty :: Char -> Doc ann Source #

prettyList :: [Char] -> Doc ann Source #

Pretty Double Source #
>>> pretty (exp 1 :: Double)
2.718281828459045

Methods

pretty :: Double -> Doc ann Source #

prettyList :: [Double] -> Doc ann Source #

Pretty Float Source #
>>> pretty (pi :: Float)
3.1415927

Methods

pretty :: Float -> Doc ann Source #

prettyList :: [Float] -> Doc ann Source #

Pretty Int Source #
>>> pretty (123 :: Int)
123

Methods

pretty :: Int -> Doc ann Source #

prettyList :: [Int] -> Doc ann Source #

Pretty Int8 Source # 

Methods

pretty :: Int8 -> Doc ann Source #

prettyList :: [Int8] -> Doc ann Source #

Pretty Int16 Source # 

Methods

pretty :: Int16 -> Doc ann Source #

prettyList :: [Int16] -> Doc ann Source #

Pretty Int32 Source # 

Methods

pretty :: Int32 -> Doc ann Source #

prettyList :: [Int32] -> Doc ann Source #

Pretty Int64 Source # 

Methods

pretty :: Int64 -> Doc ann Source #

prettyList :: [Int64] -> Doc ann Source #

Pretty Integer Source #
>>> pretty (2^123 :: Integer)
10633823966279326983230456482242756608

Methods

pretty :: Integer -> Doc ann Source #

prettyList :: [Integer] -> Doc ann Source #

Pretty Word Source # 

Methods

pretty :: Word -> Doc ann Source #

prettyList :: [Word] -> Doc ann Source #

Pretty Word8 Source # 

Methods

pretty :: Word8 -> Doc ann Source #

prettyList :: [Word8] -> Doc ann Source #

Pretty Word16 Source # 

Methods

pretty :: Word16 -> Doc ann Source #

prettyList :: [Word16] -> Doc ann Source #

Pretty Word32 Source # 

Methods

pretty :: Word32 -> Doc ann Source #

prettyList :: [Word32] -> Doc ann Source #

Pretty Word64 Source # 

Methods

pretty :: Word64 -> Doc ann Source #

prettyList :: [Word64] -> Doc ann Source #

Pretty () Source #
>>> pretty ()
()

The argument is not used,

>>> pretty (error "Strict?" :: ())
()

Methods

pretty :: () -> Doc ann Source #

prettyList :: [()] -> Doc ann Source #

Pretty Natural Source # 

Methods

pretty :: Natural -> Doc ann Source #

prettyList :: [Natural] -> Doc ann Source #

Pretty Void Source #

I tried finding a good example to show here but could not find one

Methods

pretty :: Void -> Doc ann Source #

prettyList :: [Void] -> Doc ann Source #

Pretty Text Source #

(lazy Text instance, identical to the strict version)

Methods

pretty :: Text -> Doc ann Source #

prettyList :: [Text] -> Doc ann Source #

Pretty Text Source #

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.

Methods

pretty :: Text -> Doc ann Source #

prettyList :: [Text] -> Doc ann Source #

Pretty a => Pretty [a] Source #
>>> pretty [1,2,3]
[1, 2, 3]

Methods

pretty :: [a] -> Doc ann Source #

prettyList :: [[a]] -> Doc ann Source #

Pretty a => Pretty (Maybe a) Source #

Ignore Nothings, print Just contents.

>>> pretty (Just True)
True
>>> braces (pretty (Nothing :: Maybe Bool))
{}
>>> pretty [Just 1, Nothing, Just 3, Nothing]
[1, 3]

Methods

pretty :: Maybe a -> Doc ann Source #

prettyList :: [Maybe a] -> Doc ann Source #

Pretty a => Pretty (NonEmpty a) Source # 

Methods

pretty :: NonEmpty a -> Doc ann Source #

prettyList :: [NonEmpty a] -> Doc ann Source #

Pretty (Doc ann) Source #

Does not change the text, but removes all annotations. Pitfall: since this un-annotates its argument, nesting it means multiple, potentially costly, traversals over the Doc.

>>> pretty 123
123
>>> pretty (pretty 123)
123

Methods

pretty :: Doc ann -> Doc ann Source #

prettyList :: [Doc ann] -> Doc ann Source #

(Pretty a1, Pretty a2) => Pretty (a1, a2) Source #
>>> pretty (123, "hello")
(123, hello)

Methods

pretty :: (a1, a2) -> Doc ann Source #

prettyList :: [(a1, a2)] -> Doc ann Source #

(Pretty a1, Pretty a2, Pretty a3) => Pretty (a1, a2, a3) Source #
>>> pretty (123, "hello", False)
(123, hello, False)

Methods

pretty :: (a1, a2, a3) -> Doc ann Source #

prettyList :: [(a1, a2, a3)] -> Doc ann Source #

emptyDoc :: Doc ann Source #

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.

nest Source #

Arguments

:: Int

Change of nesting level

-> Doc ann 
-> Doc ann 

(nest i x) lays out the document x with the current indentation level 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, align and indent.

line :: Doc ann Source #

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 Source #

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

softline :: Doc ann Source #

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 Source #

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'

hardline :: Doc ann Source #

A hardline is always laid out as a line break, even when grouped 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

group :: Doc ann -> Doc ann Source #

(group 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 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.

flatAlt Source #

Arguments

:: Doc ann

Default

-> Doc ann

Fallback when grouped

-> Doc ann 

(flatAlt x fallback) renders as x by default, but falls back to fallback when grouped. Since the layout algorithms rely on group having an effect of shortening the width of the contained text, careless usage of flatAlt with wide fallbacks might lead to unappealingly long lines.

flatAlt is particularly useful for defining conditional separators such as

softHyphen = flatAlt mempty "-"
softline   = flatAlt space line

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" <+> 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

Alignment functions

The functions in this section cannot be described by Wadler's original functions. They align their output relative to the current output position - in contrast to nest which always aligns to the current nesting level. This deprives these functions from being 'optimal'. In practice however they prove to be very useful. The functions in this section should be used with care, since they are more expensive than the other functions. For example, align shouldn't be used to pretty print all top-level declarations of a language, but using hang for let expressions is fine.

align :: Doc ann -> Doc ann Source #

(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 alignment, 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

hang Source #

Arguments

:: Int

Change of nesting level, relative to the start of the first line

-> Doc ann 
-> Doc ann 

(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)

indent Source #

Arguments

:: Int

Number of spaces to increase indentation by

-> Doc ann 
-> Doc ann 

(indent i x) indents document x with i 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!
indent i d = hang i ({i spaces} <> d)

encloseSep Source #

Arguments

:: Doc ann

left delimiter

-> Doc ann

right delimiter

-> Doc ann

separator

-> [Doc ann]

input documents

-> Doc ann 

(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" <+> 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 aligned vertically, with separators put in the front:

>>> putDocW 10 doc
list [1
     ,20
     ,300
     ,4000]

For putting separators at the end of entries instead, have a look at punctuate.

list :: [Doc ann] -> Doc ann Source #

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 ]

tupled :: [Doc ann] -> Doc ann Source #

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 )

Binary functions

(<>) :: Semigroup a => a -> a -> a #

An associative operation.

(a <> b) <> c = a <> (b <> c)

If a is also a Monoid we further require

(<>) = mappend

(<+>) :: Doc ann -> Doc ann -> Doc ann Source #

(x <+> y) concatenates document x and y with a space in between.

>>> "hello" <+> "world"
hello world
x <+> y = x <> space <> y

List functions

The sep and cat functions differ in one detail: when grouped, the seps replace newlines wich spaces, while the cats simply remove them. If you're not sure what you want, start with the seps.

concatWith :: Foldable t => (Doc ann -> Doc ann -> Doc ann) -> t (Doc ann) -> Doc ann Source #

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 alredy predefined, for example

hsep    = concatWith (<+>)
fillSep = concatWith (\x y -> x <> softline <> y)

This is also useful to define customized joiners,

>>> concatWith (surround dot) ["Data", "Text", "Prettyprint", "Doc"]
Data.Text.Prettyprint.Doc

sep family

When grouped, these will replace newlines with spaces.

hsep :: [Doc ann] -> Doc ann Source #

(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.

vsep :: [Doc ann] -> Doc ann Source #

(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

grouping 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:

>>> "prefix" <+> align (vsep ["text", "to", "lay", "out"])
prefix text
       to
       lay
       out

Since grouping a vsep is rather common, sep is a built-in for doing that.

fillSep :: [Doc ann] -> Doc ann Source #

(fillSep xs) concatenates the documents xs horizontally with <+> as long as it fits the page, then inserts a line and continues doing that for all documents in xs. (line means that if grouped, the documents are separated with a space instead of newlines. Use fillCat if you do not want a space.)

Let's print some words to fill the line:

>>> let docs = take 20 (cycle ["lorem", "ipsum", "dolor", "sit", "amet"])
>>> putDocW 80 ("Docs:" <+> fillSep docs)
Docs: lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor
sit amet lorem ipsum dolor sit amet

The 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 amet

sep :: [Doc ann] -> Doc ann Source #

(sep xs) tries laying out the documents xs separated with spaces, and if this does not fit the page, separates them with newlines. This is what differentiates it from vsep, which always layouts its contents beneath each other.

>>> let doc = "prefix" <+> sep ["text", "to", "lay", "out"]
>>> putDocW 80 doc
prefix text to lay out

With a narrower layout, the entries are separated by newlines:

>>> putDocW 20 doc
prefix text
to
lay
out
sep = group . vsep

cat family

When grouped, these will remove newlines.

hcat :: [Doc ann] -> Doc ann Source #

(hcat xs) concatenates all documents xs horizontally with <> (i.e. without any spacing).

It is provided only for consistency, since it is identical to mconcat.

>>> let docs = Util.words "lorem ipsum dolor"
>>> hcat docs
loremipsumdolor

vcat :: [Doc ann] -> Doc ann Source #

(vcat xs) vertically concatenates the documents xs. If it is grouped, the line breaks are removed.

In other words vcat is like vsep, with newlines removed instead of replaced by spaces.

>>> let docs = Util.words "lorem ipsum dolor"
>>> vcat docs
lorem
ipsum
dolor

Since grouping a vcat is rather common, cat is a built-in shortcut for it.

fillCat :: [Doc ann] -> Doc ann Source #

(fillCat xs) concatenates documents xs horizontally with <> as long as it fits the page, then inserts a line' 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.

(line' means that if grouped, the documents are separated with nothing instead of newlines. See fillSep if you want a space instead.)

Observe the difference between fillSep and fillCat. fillSep concatenates the entries spaced when grouped,

>>> let docs = take 20 (cycle (["lorem", "ipsum", "dolor", "sit", "amet"]))
>>> putDocW 40 ("Grouped:" <+> group (fillSep docs))
Grouped: lorem ipsum dolor sit amet
lorem ipsum dolor sit amet lorem ipsum
dolor sit amet lorem ipsum dolor sit
amet

On the other hand, fillCat concatenates the entries directly when grouped,

>>> putDocW 40 ("Grouped:" <+> group (fillCat docs))
Grouped: loremipsumdolorsitametlorem
ipsumdolorsitametloremipsumdolorsitamet
loremipsumdolorsitamet

cat :: [Doc ann] -> Doc ann Source #

(cat 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 vcat, which always layouts its contents beneath each other.

>>> let docs = Util.words "lorem ipsum dolor"
>>> putDocW 80 ("Docs:" <+> cat docs)
Docs: loremipsumdolor

When there is enough space, the documents are put above one another,

>>> putDocW 10 ("Docs:" <+> cat docs)
Docs: lorem
ipsum
dolor
cat = group . vcat

Others

punctuate Source #

Arguments

:: Doc ann

Punctuation, e.g. comma

-> [Doc ann] 
-> [Doc ann] 

(punctuate p xs) appends p to all but the last document in xs.

>>> let docs = punctuate comma (Util.words "lorem ipsum dolor sit amet")
>>> putDocW 80 (hsep docs)
lorem, ipsum, dolor, sit, amet

The 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 tupled or, in general, encloseSep.

Reactive/conditional layouts

Lay documents out differently based on current position and the page layout.

column :: (Int -> Doc ann) -> Doc ann Source #

Layout a document depending on which column it starts at. align is implemented in terms of column.

>>> column (\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 15

nesting :: (Int -> Doc ann) -> Doc ann Source #

Layout a document depending on the current nesting level. align is implemented in terms of nesting.

>>> let 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]

width :: Doc ann -> (Int -> Doc ann) -> Doc ann Source #

(width doc f) lays out the document doc, and makes the column width of it available to a function.

>>> let 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: 8

pageWidth :: (PageWidth -> Doc ann) -> Doc ann Source #

Layout a document depending on the page width, if one has been specified.

>>> let 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]
        prefix [Width: 32, ribbon fraction: 1.0]

Filler functions

Fill up available space

fill Source #

Arguments

:: Int

Append spaces until the document is at least this wide

-> Doc ann 
-> Doc ann 

(fill 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.

This function is quite useful in practice to output a list of bindings:

>>> let types = [("empty","Doc"), ("nest","Int -> Doc -> Doc"), ("fillSep","[Doc] -> Doc")]
>>> let ptype (name, tp) = fill 5 (pretty name) <+> "::" <+> pretty tp
>>> "let" <+> align (vcat (map ptype types))
let empty :: Doc
    nest  :: Int -> Doc -> Doc
    fillSep :: [Doc] -> Doc

fillBreak Source #

Arguments

:: Int

Append spaces until the document is at least this wide

-> Doc ann 
-> Doc ann 

(fillBreak 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 fill to use fillBreak, we get a useful variation of the output:

>>> let types = [("empty","Doc"), ("nest","Int -> Doc -> Doc"), ("fillSep","[Doc] -> Doc")]
>>> let ptype (name, tp) = fillBreak 5 (pretty name) <+> "::" <+> pretty tp
>>> "let" <+> align (vcat (map ptype types))
let empty :: Doc
    nest  :: Int -> Doc -> Doc
    fillSep
          :: [Doc] -> Doc

General convenience

Useful helper functions.

plural Source #

Arguments

:: (Num amount, Eq amount) 
=> doc

1 case

-> doc

other cases

-> amount 
-> doc 

(plural n one many) is one if n is 1, and many otherwise. A typical use case is adding a plural "s".

>>> let things = [True]
>>> let amount = length things
>>> "The list has" <+> pretty amount <+> plural "entry" "entries" amount
The list has 1 entry

enclose Source #

Arguments

:: Doc ann

L

-> Doc ann

R

-> Doc ann

x

-> Doc ann

LxR

(enclose l r x) encloses document x between documents l and r using <>.

>>> enclose "A" "Z" "·"
A·Z
enclose l r x = l <> x <> r

surround :: Doc ann -> Doc ann -> Doc ann -> Doc ann Source #

(surround x l r) surrounds document x with l and r.

>>> surround "·" "A" "Z"
A·Z

This is merely an argument reordering of enclose, but allows for definitions like

>>> concatWith (surround ".") ["Data", "Text", "Prettyprint", "Doc"]
Data.Text.Prettyprint.Doc

Bracketing functions

Enclose documents in common ways.

squotes :: Doc ann -> Doc ann Source #

>>> squotes "·"
'·'

dquotes :: Doc ann -> Doc ann Source #

>>> dquotes "·"
"·"

parens :: Doc ann -> Doc ann Source #

>>> parens "·"
(·)

angles :: Doc ann -> Doc ann Source #

>>> angles "·"
<·>

brackets :: Doc ann -> Doc ann Source #

>>> brackets "·"
[·]

braces :: Doc ann -> Doc ann Source #

>>> braces "·"
{·}

Named characters

Convenience definitions for common characters

lparen :: Doc ann Source #

>>> lparen
(

rparen :: Doc ann Source #

>>> rparen
)

langle :: Doc ann Source #

>>> langle
<

rangle :: Doc ann Source #

>>> rangle
>

lbrace :: Doc ann Source #

>>> lbrace
{

rbrace :: Doc ann Source #

>>> rbrace
}

lbracket :: Doc ann Source #

>>> lbracket
[

rbracket :: Doc ann Source #

>>> rbracket
]

squote :: Doc ann Source #

>>> squote
'

dquote :: Doc ann Source #

>>> dquote
"

semi :: Doc ann Source #

>>> semi
;

colon :: Doc ann Source #

>>> colon
:

comma :: Doc ann Source #

>>> comma
,

space :: Doc ann Source #

>>> "a" <> space <> "b"
a b

This is mostly used via <+>,

>>> "a" <+> "b"
a b

dot :: Doc ann Source #

>>> dot
.

slash :: Doc ann Source #

>>> slash
/

backslash :: Doc ann Source #

>>> backslash
\

equals :: Doc ann Source #

>>> equals
=

pipe :: Doc ann Source #

>>> pipe
|

Annotations

annotate :: ann -> Doc ann -> Doc ann Source #

Add an annotation to a Doc. 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.

unAnnotate :: Doc ann -> Doc xxx Source #

Remove all annotations.

Although unAnnotate is idempotent with respect to rendering,

unAnnotate . unAnnotate = unAnnotate

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 unAnnotateS.

reAnnotate :: (ann -> ann') -> Doc ann -> Doc ann' Source #

Change the annotation of a Document.

Useful in particular to embed documents with one form of annotation in a more generlly annotated document.

Since this traverses the entire Doc tree, it is preferrable to reannotate after producing the layout by using reAnnotateS.

Technically reAnnotate makes Doc a Functor, but since reannotation is hardly intuitive we omit the instance.

unAnnotateS :: SimpleDoc ann -> SimpleDoc xxx Source #

Remove all annotations. unAnnotate for SimpleDoc.

reAnnotateS :: (ann -> ann') -> SimpleDoc ann -> SimpleDoc ann' Source #

Change the annotation of a document. reAnnotate for SimpleDoc.

Optimization

fuse :: FusionDepth -> Doc ann -> Doc ann Source #

(fuse 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 Document out to a SimpleDoc, 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 SimpleDoc, although this is fully equivalent to the tightly packed

>>> "abcd" :: Doc ann
abcd

which is only a single SimpleDoc entry, and can be processed faster.

It is therefore a good idea to run fuse 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

data FusionDepth Source #

Fusion depth parameter, used by fuse.

Constructors

Shallow

Do not dive deep into nested documents, fusing mostly concatenations of text nodes together.

Deep

Recurse into all parts of the Doc, including different layout alternatives, and location-sensitive values such as created by nesting 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.

This value should only be used if profiling shows it is significantly faster than using Shallow.

Layout

Laying a Document out produces a straightforward SimpleDoc based on parameters such as page width and ribbon size, by evaluating how a Doc fits these constraints the best. There are various ways to render a SimpleDoc. For the common case of rendering a SimpleDoc as plain Text take a look at Data.Text.Prettyprint.Doc.Render.Text.

data SimpleDoc ann Source #

The data type SimpleDoc represents laid out documents and is used by the display functions.

A simplified view is that Doc = [SimpleDoc], and the layout functions pick one of the SimpleDocs. This means that SimpleDoc has all complexity contained in Doc resolved, making it very easy to convert it to other formats, such as plain text or terminal output.

To write your own Doc to X converter, it is therefore sufficient to convert from SimpleDoc. The »Render« submodules provide some built-in converters to do so, and helpers to create own ones.

Constructors

SFail 
SEmpty 
SChar Char (SimpleDoc ann) 
SText !Int Text (SimpleDoc ann)

Some layout algorithms use the Since the frequently used length of the Text, which scales linearly with its length, we cache it in this constructor.

SLine !Int (SimpleDoc ann)

Int = indentation level for the line

SAnnPush ann (SimpleDoc ann)

Add an annotation to the remaining document.

SAnnPop (SimpleDoc ann)

Remove a previously pushed annotation.

Instances

Eq ann => Eq (SimpleDoc ann) Source # 

Methods

(==) :: SimpleDoc ann -> SimpleDoc ann -> Bool #

(/=) :: SimpleDoc ann -> SimpleDoc ann -> Bool #

Ord ann => Ord (SimpleDoc ann) Source # 

Methods

compare :: SimpleDoc ann -> SimpleDoc ann -> Ordering #

(<) :: SimpleDoc ann -> SimpleDoc ann -> Bool #

(<=) :: SimpleDoc ann -> SimpleDoc ann -> Bool #

(>) :: SimpleDoc ann -> SimpleDoc ann -> Bool #

(>=) :: SimpleDoc ann -> SimpleDoc ann -> Bool #

max :: SimpleDoc ann -> SimpleDoc ann -> SimpleDoc ann #

min :: SimpleDoc ann -> SimpleDoc ann -> SimpleDoc ann #

Show ann => Show (SimpleDoc ann) Source # 

Methods

showsPrec :: Int -> SimpleDoc ann -> ShowS #

show :: SimpleDoc ann -> String #

showList :: [SimpleDoc ann] -> ShowS #

data PageWidth Source #

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 softline').

Constructors

AvailablePerLine Int Double

Layouters should not exceed the specified space per line.

  • The Int is the number of characters, including whitespace, that fit in a line. A typical value is 80.
  • The Double 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.
Unbounded

Layouters should not introduce line breaks on their own.

defaultLayoutOptions :: LayoutOptions Source #

The default layout options, suitable when you just want some output, and don’t particularly care about the details. Used by the Show instance, for example.

>>> defaultLayoutOptions
LayoutOptions {layoutPageWidth = AvailablePerLine 80 0.4}

layoutPretty :: LayoutOptions -> Doc ann -> SimpleDoc ann Source #

This is the default layout algorithm, and it is used by show, putDoc and hPutDoc.

layoutPretty commits to rendering something in a certain way if the next element fits the layout constraints; in other words, it has one SimpleDoc element lookahead when rendering. Consider using the smarter, but a bit less performant, layoutSmart algorithm if the results seem to run off to the right before having lots of line breaks.

layoutCompact :: Doc ann -> SimpleDoc ann Source #

(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.

>>> let doc = hang 4 (vsep ["lorem", "ipsum", hang 4 (vsep ["dolor", "sit"])])
>>> doc
lorem
    ipsum
    dolor
        sit
>>> let putDocCompact = renderIO System.IO.stdout . layoutCompact
>>> putDocCompact doc
lorem
ipsum
dolor
sit

layoutSmart :: LayoutOptions -> Doc ann -> SimpleDoc ann Source #

A layout algorithm with more lookahead than layoutPretty, that introduces line breaks earlier if the content does not (or will not, rather) fit into one line.

Considre the following python-ish document,

>>> let fun x = hang 2 ("fun(" <> softline' <> x) <> ")"
>>> let doc = (fun . fun . fun . fun . fun) (list ["abcdef", "ghijklm"])

which 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.Text
>>> let hr = pipe <> pretty (replicate (26-2) '-') <> pipe
>>> let go layouter x = (T.putStrLn . renderStrict . layouter (LayoutOptions (AvailablePerLine 26 1))) (vsep [hr, x, hr])

If we render this using layoutPretty 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 layoutSmart, fits the layout contstraints:

>>> go layoutSmart doc
|------------------------|
fun(
  fun(
    fun(
      fun(
        fun(
          [ abcdef
          , ghijklm ])))))
|------------------------|

The key difference between layoutPretty and layoutSmart 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.

Migration guide

If you're already familiar with (ansi-)wl-pprint, you'll recognize many functions in this module, and they work just the same way. However, a couple of definitions are missing:

  • char, string, double, … – these are all special cases of the overloaded pretty function.
  • <$>, <$$>, </>, <//> are special cases of vsep, vcat, fillSep, fillCat with only two documents.
  • If you need String output, use unpack on the generated renderings.
  • The display functions are moved to the rendering submodules, for example conversion to plain Text is in the Data.Text.Prettyprint.Doc.Render.Text module.
  • The render functions are called layout functions.
  • Instead of providing an own colorization function for each color/intensity/layer combination, they have been combined in color, colorDull, bgColor, and bgColorDull functions.