Skip to content
Single-Pass Pretty Printing
step 1/5

Reading — step 1 of 5

Read

~1 min readWhy Formatters

Single-Pass Pretty Printing

Naive approach: format token by token; insert newline if line gets too wide.

python

Problems:

  • Doesn't break BEFORE a long expression. The decision to wrap should consider the WHOLE expression.
  • No indentation.
  • Coarse: line break every 80 chars regardless of structure.

Better:

  • Group structural units (function calls, lists, etc.).
  • For each group: try to fit on one line. If fits, emit on one line. If not, BREAK + indent each child.
[1, 2, 3]                   ← fits → emit "[1, 2, 3]"
[1, 2, 3, ..., 100]         ← doesn't fit → emit:
[
  1, 2, 3,
  4, ...
]

Wadler's pretty printer formalizes this. We'll see.

Other concerns:

  • Comments: preserve associated comments in output. Hard.
  • Blank lines: collapse runs of blank lines to at most 2.
  • Trailing commas: preserve or insert (style choice).

Modern formatters parse to AST, format from AST, write back. AST-based:

  • Robust to whitespace mangling.
  • Can do non-trivial restructuring.
  • Lose: original line numbers, exact spacing, comment positions.

CST (Concrete Syntax Tree): like AST but preserves whitespace + comments. Better for formatters; what tree-sitter produces.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…