Search code examples
haskellpretty-print

Empty (zero height) documents in Haskell prettyprinter


Is there a way to create a zero height empty document in prettyprinter? emptyDoc has a height of 1 which then results in empty lines. I would also like to avoid using Maybes to solve this.


Solution

  • No, there isn't:

    data Doc ann =
        Fail
        | Empty
        | Char !Char
        | Text !Int !Text
        | Line
        | FlatAlt (Doc ann) (Doc ann)
        | Cat (Doc ann) (Doc ann)
        | Nest !Int (Doc ann)
        | Union (Doc ann) (Doc ann)
        | Column (Int -> Doc ann)
        | WithPageWidth (PageWidth -> Doc ann)
        | Nesting (Int -> Doc ann)
        | Annotated ann (Doc ann)
    

    None of these correspond to anything with a height under 1 -- the closest is Empty, but this is interpreted as a height-1 empty document (and your emptyDoc is emptyDoc = Empty).

    It does seem a bit infelicitous. Perhaps a patch to the library to add a truly empty document would be considered; it would certainly be the cleanest approach.

    Another possibility would be to use the annotation mechanism to make a "this chunk has height 0" annotation, and write your own renderer that handles this annotation.

    But using Maybe (Doc foo) or [Doc foo] as appropriate in positions where you may need a 0-height document is likely to be the most straightforward way to make progress.