[Haskell-cafe] Indenting with PPrint

Brandon Michael Moore brandon at heave.ugcs.caltech.edu
Mon May 7 19:33:42 EDT 2007


On Mon, May 07, 2007 at 10:38:19PM +0100, Joel Reymont wrote:
> Folks,
> 
> Are you using UU.PPrint [1]? Can you tell me how to print stuff like  
> this?
> 
> {
>      blah
>      blah
> }
> 
> I tried the following which sort of works but doesn't return the  
> closing brace to the indentation level of the first one.
> 
> braces x = PP.braces $ linebreak <> indent 4 x

You could use

braces x = PP.braces $ indent 4 (linebreak <> x) <> linebreak


The tricky thing with PPrint is remembering that the current indentation
level is only applied when you hit a "line", so nest doesn't affect a leading word.
nest n (text "a" <> line <> doc) = text "a" <> nest (line <> doc)

If you want to give the pretty printer some freedom in laying out your
document, and you care about how the alternate layouts look (and why
else would you be using a pretty printer), you might prefer

braces x = group (PP. braces (nest 4 (linebreak <> x) <> linesbreak)

That will make a one-line form like

{blah, blah}

rather than

{    blah, blah}

and it lets the printer flatten a brace group whenever it fits on one line,
not just if it happens to be inside an enclosing group.

The trick for getting GNU braces with Text.PrettyPrint is
braces x = cat [lbrace, text "", nest 4 x, rbrace]

without (text "") vertical composition would overlap the indented blah with
the opening brace.

If you happen to be formatting C I've also worked out how to get nice argument
lists out of both pretty printers.

Brandon


More information about the Haskell-Cafe mailing list