Skip to main content

flm_core/layout/
mod.rs

1//! The layout engine: it lays text out in lines of a given width, for any
2//! output written as characters in fixed-width columns (plain text, a
3//! terminal).
4//!
5//! The engine takes two inputs and produces one output:
6//!
7//! - **A layout document**, built by the caller in a [`DocBuf`]. It describes
8//!   the intended text without deciding where the lines end: the words as
9//!   *atoms* (texts printed whole), the places where a line may end and where
10//!   it must end, indentation, per-line prefixes such as a quotation's `> `,
11//!   verbatim blocks, tables, a text set at the right edge of a line, rule
12//!   lines as wide as the block they stand above or under, and *marks*
13//!   (requests to report where a part of the document is printed). The
14//!   constructors of [`DocBuf`] are the whole set of things a layout document
15//!   can hold; the [`doc`] module lists them.
16//! - **A profile** ([`Profile`]): the target line width in columns, or `None`
17//!   for no wrapping. It is the engine's only option.
18//! - **The output**: the printer, [`print()`] or [`print_full`], decides the
19//!   line breaks for the profile's width and returns the text; [`print_full`]
20//!   also returns, for every mark, the byte range and the line and column range
21//!   of the marked part in that text ([`PrintOutput`], [`MarkSpan`]).
22//!
23//! An emitter (a backend's emit stage, which writes the output's bytes; see
24//! [backends, lowering, and
25//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs))
26//! uses the engine when its output is text in columns: it builds one layout
27//! document while it walks its input, then prints it once. In this library
28//! the text backend's emitter ([`crate::stdlib::backends::text`]) is the only
29//! caller of the printer; the HTML emitter and the presentation helpers use
30//! [`is_breakable_space`] so that they split words at the same characters.
31//! [The plain-text backend](crate::guide::rendering#the-plain-text-backend)
32//! and [the layout engine](crate::guide::rendering#the-layout-engine) sections
33//! of the rendering guide describe both.
34//!
35//! This module does not depend on anything else in the crate (neither on techy
36//! nor on the document model), so any program that writes text in columns can
37//! use it.
38//!
39//! # What the engine guarantees
40//!
41//! - **Breaking by width**: a [`group`](DocBuf::group) prints on one line if
42//!   it fits together with everything that follows it on that line; otherwise
43//!   every break opportunity directly inside it becomes a line break. Prose is
44//!   filled with [`fill_words`](DocBuf::fill_words), which puts one group
45//!   around each space between two words; each space then decides on its own
46//!   whether to stay a space, which gives correct greedy wrapping, even before
47//!   a trailing text that has no break opportunity of its own.
48//! - **Display width by grapheme cluster**: the width of a text in columns is
49//!   the sum, over its grapheme clusters (what a reader sees as one
50//!   character), of each cluster's Unicode width. The width of two texts
51//!   joined is therefore the sum of their widths, and a longer text never
52//!   measures narrower than its beginning. `Über Bäume — 日本語` is 19 columns,
53//!   a family emoji 2. [`display_width`] gives the same measure to an emitter
54//!   that aligns text by hand.
55//! - **One indentation stack**: [`nest`](DocBuf::nest),
56//!   [`align`](DocBuf::align) and [`prefix`](DocBuf::prefix) all push units
57//!   that are written at the start of every line, in nesting order, so a list
58//!   inside a quotation and a quotation inside a list are both laid out
59//!   correctly, and a prefix's width is subtracted from the width available
60//!   for wrapping.
61//! - **Blank lines only from [`blocksep`](DocBuf::blocksep)**: adjacent
62//!   requests for a line break are merged into one, which keeps the larger
63//!   number of blank lines; a line break at the start or at the end of the
64//!   output is dropped; a blank line is written with the part of the
65//!   indentation stack that the lines around it have in common, trimmed of
66//!   trailing whitespace. The blank line between two paragraphs of one
67//!   `> `-prefixed quotation therefore prints `>`, and the blank line between
68//!   two such quotations prints nothing.
69//! - **No trailing whitespace added by the engine**: indentation and the
70//!   space of an unbroken break opportunity are written only when a content
71//!   character follows on the same line.
72//! - **[`raw`](DocBuf::raw) blocks are never reflowed**: their lines, blank
73//!   lines included, are written byte for byte, either under the indentation
74//!   stack or at column 0, as their [`RawPolicy`] says.
75//! - **[`table`](DocBuf::table) columns are computed** from each column's
76//!   narrowest and widest content: the width left over is shared out in
77//!   proportion to each column's room to grow, in whole columns, after the
78//!   gutters or the frame are subtracted from the width; cells are wrapped at
79//!   their column's width and drawn as the table's [`TableFrame`] says: two
80//!   spaces apart with a rule of `-` under the header rows (`Gutter`), or
81//!   inside a frame of box-drawing characters with a rule of the frame under
82//!   the header rows (`Box`). A table given a border mark reports what it
83//!   draws under that mark, one span per run of drawn characters on a line.
84//! - **[`flush_right`](DocBuf::flush_right) reaches the right edge**: its
85//!   child, set on one line, ends at the last column of the width where the
86//!   columns before it on its line, its gap and its own width fit in the
87//!   width, and otherwise follows what precedes it after the gap; inside a
88//!   table cell the edge is the cell's. The fitting scan counts it as an atom
89//!   of its gap and its child.
90//! - **[`ruled`](DocBuf::ruled) rules are as wide as their child**: each rule
91//!   line repeats one character to the display width of the child's widest
92//!   printed line, a line it wraps included, and is written under the
93//!   child's indentation and prefixes. The node reports its rule lines under
94//!   its mark, one span per line.
95//! - **[`mark`](DocBuf::mark) positions**: [`print_full`] reports, for every
96//!   occurrence of a mark, the byte range and the 0-based line and column
97//!   range of the marked part's content characters, in the order the marks
98//!   are opened; a table's border runs and the marks inside its cells follow
99//!   the marks opened before the table, the cells' marks row by row and
100//!   column by column, each placed where its cell's text lands in the table.
101//!   A mark inside a cell over several lines of the cell gives one span per
102//!   line of the cell, because the table interleaves the cell's lines with
103//!   the rest of the row. The marks inside the child of a `flush_right` or a
104//!   `ruled` node are reported where its text lands, in their order, one span
105//!   per mark. A mark never changes the layout.
106//! - **Determinism**: the output depends only on the layout document, the root
107//!   node passed to the printer and the profile. The printer uses no hash-map
108//!   iteration and no floating point, and the record it keeps of the nodes it
109//!   has printed apart (table cells, and the children of `flush_right` and
110//!   `ruled` nodes) depends only on each node and the width, so two runs give
111//!   the same bytes.
112//!
113//! # Example
114//!
115//! ```
116//! use flm_core::layout::{DocBuf, Profile, print};
117//!
118//! let mut b = DocBuf::new();
119//! let label = b.text("  • ");
120//! let body = b.fill_words("a list item whose text wraps under its own first word");
121//! let hung = b.align(body);
122//! let item = b.concat(&[label, hung]);
123//!
124//! let out = print(&b, item, &Profile::new(Some(32)));
125//! assert_eq!(
126//!     out,
127//!     "  • a list item whose text wraps\n    under its own first word\n"
128//! );
129//! ```
130//!
131//! [`Profile`] carries the target width and nothing else: `None` means "never
132//! wrap". Every other behavior is fixed: lines end in `\n`, a non-empty output
133//! ends in exactly one `\n`, and an atom is never split. The width measure
134//! cannot be changed either. The [`printer`] module's documentation explains
135//! how the printer works.
136//!
137//! # Items of this module
138//!
139//! - [`doc`]: the arena [`DocBuf`] and its constructors; [`DocId`],
140//!   [`MarkId`], [`RawPolicy`], [`ColSpec`], [`ColAlign`], [`TableCell`],
141//!   [`is_breakable_space`].
142//! - [`printer`]: [`Profile`], [`print()`], [`print_full`], [`PrintOutput`],
143//!   [`MarkSpan`], [`LineCol`], and the printer itself.
144//! - `table` (crate-internal): the column solver and the assembly of rows into
145//!   lines.
146//! - `width` (crate-internal): the width measures; [`display_width`] is
147//!   re-exported here.
148//!
149//! # Properties of the interface
150//!
151//! - **The constructors of [`DocBuf`] are the whole public interface for
152//!   building a layout document.** The nodes of the arena and the functions
153//!   that read them are crate-internal: a caller only builds layout documents,
154//!   and keeping their representation private leaves it free to change.
155//! - **The width measure is public, and it cannot be replaced.** [`Profile`]
156//!   has no setting for the measure. [`display_width`] is the measure the
157//!   printer wraps against, offered for an emitter that aligns text by hand (a
158//!   rule of `=` as wide as a heading, a label padded to a column).
159//! - **The requirements on the constructors' input are checked in debug builds
160//!   only.** An atom or a prefix must not contain `'\n'` or `'\t'`, the child
161//!   of a [`flush_right`](DocBuf::flush_right) must print on one line, and the
162//!   character of a [`ruled`](DocBuf::ruled) node's rule lines must be one
163//!   column wide. These are requirements on the emitter's code, not on a
164//!   document's content, and a violation has to be fixed in the emitter, so a
165//!   release build does not spend time on the check.
166//! - **A table or a `ruled` node that prints nothing is not a block.** A table
167//!   with no columns, with no rows, or whose cells all print nothing, and a
168//!   [`ruled`](DocBuf::ruled) node whose child prints nothing, leave the
169//!   surrounding line and any requested line break as they are, because
170//!   output that does not exist should not force a line break. The fitting
171//!   scan (the printer's test of whether a group fits on the line, see the
172//!   [`printer`] module) agrees for a `ruled` node, and for the two cases of a
173//!   table it can decide without printing the cells (no columns, no rows); it
174//!   still treats a table whose rows all print nothing as a block.
175//!
176//! # Known limitations
177//!
178//! - The fitting scan does not count indentation, so an indentation node
179//!   inside a group at the start of a line is not counted against that group's
180//!   first line. Emitters keep indentation outside groups, which avoids the
181//!   case.
182//! - A [`raw`](DocBuf::raw) block of one line is measured like an atom by the
183//!   fitting scan, even under [`RawPolicy::Exempt`], where it starts a new
184//!   line.
185//! - The child of a [`ruled`](DocBuf::ruled) node is printed on its own and
186//!   its lines are written under the node's indentation, as a table's cells
187//!   are; a [`raw`](DocBuf::raw) block under [`RawPolicy::Exempt`] inside it
188//!   is therefore written under that indentation, not at column 0.
189//! - The fitting scan stops once the width is used up by content characters,
190//!   but it can pass through many nodes of zero width in a layout document
191//!   whose nodes are shared many times; it has no limit on its number of
192//!   steps.
193
194// Maintainer notes on the points above. The trait behind the width measure
195// stays crate-internal so that the choice of measure remains free to change.
196// The limitations listed above are kept as they are, each pinned by a test, so
197// that a deliberate change to the layout can be told apart from an accidental
198// one. Correcting the indentation limitation is not local: the fitting scan
199// would have to track the indentation accumulated up to a group's first
200// visible character.
201// The scan needs no step limit as long as emitters build layout documents as
202// trees rather than as heavily shared graphs, since its walk is then
203// proportional to the size of the document.
204
205pub mod doc;
206pub mod printer;
207mod table;
208mod width;
209
210pub use doc::{
211    is_breakable_space, ColAlign, ColSpec, DocBuf, DocId, MarkId, RawPolicy, TableCell, TableFrame,
212};
213pub use printer::{print, print_full, LineCol, MarkSpan, PrintOutput, Profile};
214pub use width::display_width;