Format Code

Problem

You have some Erlang code that you want to format readably.

Solution

The erl_pp module provides this functionality. The only complicated thing is that it expects to deal with intermediate Erlang forms, such as those produced by the erl_parse module. Of course, the erl_parse module wants to deal with lexically-scanned tokens, such as those produced by the erl_scan module. Consequently, taking a chunk of badly-formatted Erlang code and generating beautiful output is generally a three-step process.

Whew! That's a lot of work to make the code a bit easier to read. However, you generally would not use this as shown in the example. We would wrap everything up in a nice set of functions to produce a single output:

To be truly useful, we should probably create a full-featured pretty_print function that would allow us to control formatting, such as the desired columns width, perhaps a maximum level to parse, etc.

In fact, it appears someone has already done so. Richard Carlsson (a member of the HIPE Project) has written a number of tools for parsing and manipulating Erlang text. His edoc package appears to support everything you could possibly want with respect to pretty printing.