@elastic/pretty-printer
v4.33.0
Published
A general-purpose Wadler-Lindig document algebra and layout engine for width-aware pretty-printing.
Keywords
Readme
@elastic/pretty-printer
A general-purpose pretty-printing library based on the Wadler-Lindig document
algebra (Philip Wadler, "A prettier printer", 2003; Christian Lindig's strict
formulation). The implementation draws heavily from Prettier's internal
doc-printer.
It contains no ES|QL, PromQL, or other domain knowledge — it is the standalone
layout engine used by @elastic/esql's pretty-printers, published so any
project can build width-aware formatters on the same Doc IR.
Install
npm install @elastic/pretty-printerHow it works
Pretty-printing is a two-phase process:
- Build a document tree (
Doc) using combinators (see below). The tree describes the structure of possible layouts — it contains no concrete line breaks or indentation yet. - Layout the tree into a concrete string. The layout engine fits as much
content on each line as possible (up to
printWidth), breakinggroupnodes when the flat representation would exceed the available width.
Example:
import { text, group, indent, line, softline, join, layout } from '@elastic/pretty-printer';
const doc = group([
text('SELECT'),
indent([line, join(
[text(','), line],
[text('a'), text('b'), text('c')])]
),
line,
text('FROM t'),
]);
layout(doc, { printWidth: 40 });
// SELECT
// a,
// b,
// c
// FROM t
layout(doc, { printWidth: 80 });
// SELECT a, b, c FROM tlayout(tree, opts?)
The main entry point. Takes a print tree and returns the formatted string.
Options:
| Option | Type | Default | Description |
|--------------|----------------------------------------|---------|------------------------------------------|
| printWidth | number | 80 | Target maximum line width. |
| tabWidth | number | 2 | Spaces per indentation level. |
| useTabs | boolean | false | Indent with tabs instead of spaces. |
| endOfLine | '\n' | '\r\n' | '\r' | '\n' | Line-ending character(s). |
Combinators / Commands
The printer provides a set of combinators (or "commands") for building print trees. These are the building blocks for describing the structure of the output.
Primitives
text(string)— Literal text, printed as-is. Must not contain newline characters.Doc[](array) — Concatenation. An array of docs is rendered left to right.
Line breaks
line— Space" "in flat mode; newline + indent in break mode.softline— Nothing""in flat mode; newline + indent in break mode.hardline— Always a newline + indent. Forces the enclosing group to break.hardlineWithoutBreakParent— Likehardlinebut does not force the parent group to break.literalline— Hard line break that indents to the root position (set bymarkAsRoot) instead of the current nesting level. Preserves trailing whitespace. Forces enclosing groups to break.literallineWithoutBreakParent— Likeliterallinebut does not force the parent group to break.
Grouping
group(tree, opts?)— The core break-decision unit. Tries to render print tree node flat (single line). If it exceeds the remaining width, switches to break mode. Options:shouldBreak(force break),id(symbol for cross-referencing withifBreak/indentIfBreak).conditionalGroup(states, opts?)— Multi-state group. Provide alternative layouts from most compact to most expanded. The engine tries each in order and uses the first one that fits; if none fits, the last state is rendered in break mode.fill(parts)— Wrapping layout.partsalternate between content and line-break docs:[item, line, item, line, ...]. Fills each line with as many items as fit before breaking — unlikegroup, which is all-or-nothing.
Indentation
indent(tree)— Increase indentation by one tab level.align(n, tree)— Increase indentation by exactlynspaces (not a tab level). Special values:-1(dedent one level),Number.NEGATIVE_INFINITY(reset to root),{ type: 'root' }(mark current indent as root).dedent(tree)— Decrease indentation by one level. Shorthand foralign(-1, tree).dedentToRoot(tree)— Reset indentation to root (column 0 or the position set bymarkAsRoot).markAsRoot(tree)— Mark the current indentation as the "root" position forliteralline.
Conditional content
ifBreak(breakDoc, flatDoc?, opts?)— EmitbreakDocwhen the enclosing group (or a group referenced bygroupId) is in break mode; otherwise emitflatDoc.indentIfBreak(tree, opts)— Conditionally indentdocbased on a referenced group's mode. Optimized form ofifBreak(indent(tree), doc, { groupId }). Setnegate: trueto reverse.breakParent— Force all ancestor groups to break. Propagated during a pre-pass (propagateBreaks).
Comments & line suffixes
lineSuffix(tree)— Bufferdocand emit it at the end of the current line, just before the next line break. Used for trailing comments.lineSuffixBoundary— Force-flush any pendinglineSuffixcontent. Prevents trailing comments from leaking past syntactic boundaries.
Miscellaneous
label(lbl, tree)— Annotate a doc with an opaque label for language-specific heuristic introspection. No effect on layout.trim— Remove all trailing whitespace from the output at the current position.cursor— Placeholder for cursor-position tracking. The layout engine emits a sentinel; callers can locate it to preserve cursor position after formatting.join(separator, trees)— Join an array of docs withseparatorbetween each pair.bracketedList(open, close, sep, items)— Convenience for a grouped, indented, bracketed list. Flat:(a, b, c). Broken:( a, b, c )addAlignmentToDoc(doc, size, tabWidth)— Convert an absolute indentation size into nestedindent/alignwrappers insidededentToRoot. Used for embedded content needing a specific indentation level.
Traversal
traverse(doc, { onEnter?, onExit? })— Generic depth-first traversal of a doc tree using an explicit stack (no recursion). ReturnfalsefromonEnterto skip a node's children.
