Pretty: A pretty-printing library for C++
Version 1.0.1

Table of Contents

1 Summary

Pretty is a library for pretty-printing trees.

It's an implementation of Philip Wadler's paper, except in C++20 instead of Haskell.

The Haskell implementation in the paper is quite short and elegant, but producing a C++ version required some thought and involves much uglier internals.

There are instructions for working on the project and a some notes about its implementation.

1.1 What's a pretty-printer?

A pretty-printer formats a tree-like data structure into a textual representation that looks pretty to humans.

For example, given this representation of an XML document in C++:

Element xml{"p",
        Attributes{Pair{"color", "red"}, Pair{"font", "Times"}, Pair{"size", "10"}},
        with("Here is some",
             Element{"em", Attributes{}, with("emphasized")},
             "text. Here is a",
             Element{"a", Attributes{Pair{"href", ""}}, with("link")},

Pretty will format it to a width of 60 characters like this:

<p color="red" font="Times" size="10" >
  Here is some <em> emphasized </em> text. Here is a
  <a href="" > link </a> elsewhere.

Given less space to work with (30 characters), the XML is instead formatted this way:

  color="red" font="Times"
  Here is some
  <em> emphasized </em> text.
  Here is a
  > link </a>

1.2 Usage

// For convenience.
using namespace pretty;

// Construct a document.
Doc d = text("AA") + text("BB") + line() + text("CC");

// Format it to a fixed width.
Layout l = d.fit_to(80);

// Print the layout.
std::cout << l << std::endl;

The result is


2 Motivation

Wadler's paper, "A prettier printer", was a joy to read.

First, he defines an algebra of documents (where a "document" is something to be pretty-printed).

Next, using just the laws of this algebra, he derives an implementation of the pretty-printing algorithm that is correct by construction. Wow!

I was curious if it was possible implement the algorithm in a more… "traditional" language like C++ while still exposing only the straightforward API of the Haskell version.

2.1 Caveats

Pretty appears to be functionally equivalent to the Haskell version and doesn't suffer from any obvious performance problems. Nonetheless, it's a fairly direct translation of the Haskell into C++ so the code is not idiomatic. Pretty is a fun experiment, but I'd be reluctant to use it for anything serious.

3 License

Pretty is licensed under the terms of version 3 of the GNU General Public License.

4 Resources and contact

Please don't hesitate to contact me with any questions, issues, or suggestions.

5 Build system integration

Assuming Pretty has been installed to your filesystem, the following CMake incantation will link with it:

find_package (Pretty REQUIRED)
target_link_libraries (my_exe Pretty::pretty)

Author: Jesse Haber-Kucharsky

Created: 2021-10-19 Tue 19:55