Skip to main content

flm_core/stdlib/backends/text/
emit.rs

1//! The text emitter: it walks the text backend's lowered trees and lowered
2//! pieces, builds one layout document from them, and prints it into a
3//! [`TextOutput`].
4//!
5//! An emitter is a backend's emit stage: it walks the lowered trees and writes
6//! the output's bytes into a table, from which the backend's final stage makes
7//! the artifact set (see [backends, lowering, and
8//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)).
9//! [`emit()`] is this module's entry point; the emit stage
10//! ([`TextEmitStage`](super::stages::TextEmitStage)) calls it once per run.
11//! The [layout engine](crate::layout) breaks the lines, indents and pads; this
12//! module maps each presentation element onto the engine's constructors and
13//! lets the engine produce the characters.
14//!
15//! # The pieces and the content
16//!
17//! The emitter prints, in order, the pieces placed before the content (such
18//! as the title, the authors, the date and the table of contents), the
19//! lowered trees in document order, and the pieces placed after the content
20//! (such as the list of notes), each one blank line after the one before it.
21//! A piece or a tree that prints nothing adds no blank line, so a document
22//! with no piece starts with its content.
23//!
24//! # What each element prints
25//!
26//! In a **run of blocks** (a tree's top level, a block's body, a list item),
27//! blocks are separated by one blank line. The blocks of a run are `par`,
28//! `block`, `block-heading`, `list`, `cells`, `lines`, `subtree`, the construct
29//! element `text.ruled`, a block `image`, a block `verbatim` and an `unknown`
30//! environment, and the containers holding one of them. Everything else in
31//! the run, a displayed formula, `unsupported` and `dropped` included, is
32//! inline content: each maximal stretch of it is filled as one paragraph, as
33//! inside a `par`, so a displayed formula takes lines of its own with no blank
34//! line beside it, and a blank line separates blocks only. The table below
35//! says how each element prints wherever it stands in a run of blocks:
36//!
37//! | lowered element | printed as |
38//! |---|---|
39//! | `par` | its inline content, filled word by word; decorations printed at their decoration marks |
40//! | `block-heading` | the heading text, then a rule under it (see below) |
41//! | `block` | its body as a run of blocks; the role and the kinds are dropped; a decoration whose decoration mark is among its blocks prints at that decoration mark, on a line of its own when a block follows |
42//! | `list` | one entry per label/item pair, the item hanging after the label (see below) |
43//! | `cells` | one table of the layout engine: each cell's blocks in its column, in the cell's own alignment, a spanned cell's content at the first position of its span; the leading rows of column headers above a rule (see below) |
44//! | `lines` / `line` | one printed line per `line`, indented by its `indent_left` converted to columns ([`TextRenderOptions::columns`]) |
45//! | `verbatim` (block) | the content byte for byte, indented like its surroundings |
46//! | `unsupported` | `[unsupported: <element>]` |
47//! | `dropped` | `[dropped: <detail>]` |
48//! | `unknown` (environment) | its begin and end lines around its body blocks (see below) |
49//! | `image` (block) | `[image: <alt or src>]` |
50//! | `subtree` | the placed tree's lowered blocks, printed at this node |
51//! | `text.ruled` ([`RULED`]) | its body as a run of blocks, with a rule line above it and one under it as its payload asks (see below) |
52//! | `flm.container`, `flm.group`, `flm.opaque-wrapper` | their children: as a run of blocks when a block of a run is among their descendants, otherwise as inline content filled with the text around them |
53//! | `flm.comment`, `flm.parbreak` | nothing; the blocks on either side of them are separate |
54//!
55//! The rows that need more room:
56//!
57//! - An unattributed environment (an environment no feature declares) prints
58//!   `\begin{name}` on a line of its own, then its lowered body as a run of
59//!   blocks, then `\end{name}` on a line of its own.
60//! - A `block-heading` prints the heading text, then a rule as wide as the
61//!   widest line that text prints, so a title that wraps gets a rule as wide
62//!   as its longest line: `=` for a heading at the root heading level
63//!   ([`TextRenderOptions::root_heading_level`], 1 by default), `-` for a
64//!   heading one level deeper, or `═` and `─` when
65//!   [`TextRenderOptions::heading_rules`] is
66//!   [`Unicode`](super::HeadingRules::Unicode). A heading deeper still has no
67//!   rule; it is preceded by `#` characters and a space: three `#` two levels
68//!   below the root, one more for each further level. A heading above the root
69//!   level is reported as `flm.pres.heading-above-root`
70//!   ([`HeadingAboveRoot`](crate::stdlib::backends::pres::HeadingAboveRoot))
71//!   and printed like one at the root level.
72//! - A `list` prints, for each entry, the label's text (a superscript or
73//!   subscript span in it written as in running text, below), padded to the
74//!   width of the widest label plus one, and the item's blocks hanging at that
75//!   column; when every label of the list is empty, the items start at the
76//!   margin. An entry with an empty item prints its label alone. Entries are
77//!   one blank line apart.
78//! - A `cells` table is laid out as one table of the layout engine
79//!   ([`DocBuf::table`]): one column per column of the grid, the column widths
80//!   computed from their cells' content, each cell's blocks printed at its
81//!   column's width and padded in the cell's own alignment (left where it has
82//!   none). The positions covered by a span, other than the span's first, print
83//!   nothing. The leading rows whose cells all head their columns are the
84//!   header rows. [`TextRenderOptions::table_frame`] chooses how the table is
85//!   drawn: its columns two spaces apart with a rule of `-` under the header
86//!   rows (the default), or inside a frame of box-drawing characters with a
87//!   rule of the frame under the header rows. Row headers, rules at the edges
88//!   of cells and custom cell styles are not shown in this output.
89//! - A `text.ruled` node, the construct element `flm.pres.text.ruled`
90//!   ([`RULED`], [`RuledPayload`]), prints its body as a run of blocks on lines
91//!   of its own, with a rule line above it when its payload's `above` is set
92//!   and one under it when `below` is set. A rule line is the character of a
93//!   heading at the root level (`=`, or `═` under
94//!   [`Unicode`](super::HeadingRules::Unicode) rules) repeated to the width of
95//!   the widest line the body prints, written under the same indentation as
96//!   the body ([`DocBuf::ruled`]). A body that prints nothing prints no rule
97//!   line either.
98//!
99//! In **inline content**, text is split into words at breakable whitespace
100//! ([`is_breakable_space`]: every whitespace character except the
101//! non-breaking spaces); each word is an atom of the layout engine, each
102//! space between two words a place where the line may break, and nothing is
103//! escaped:
104//!
105//! | lowered element | printed as |
106//! |---|---|
107//! | `span` | its content; a superscript or subscript style converts its text (see below); a `Bold`, `Italic`, `Emphasis`, `Underline`, `Monospace` or `SmallCaps` style is recorded as a style mark (below) and not printed; any other style, the role, the document role and the kinds are dropped |
108//! | `runin-heading` | its content, with a style mark; the payload is dropped |
109//! | `link` | its content, with a style mark, then ` <address>` for a link to an address outside the document, as the render options say (below) |
110//! | `math-passthrough` (inline) | one atom, `\(source\)`, each run of whitespace replaced by one space |
111//! | `math-passthrough` (display) | on lines of its own, the source inside `\[…\]` (or `\begin{env}…\end{env}` for an environment), indented by two columns |
112//! | `verbatim` (inline) | one atom; content holding a newline or a tab is printed as a block instead |
113//! | `deco-mark` | the decoration, printed at its decoration mark (see below) |
114//! | `text.flush-right` ([`FLUSH_RIGHT`]) | its content on one line, ending at the last column of the line width where the columns already on its line, a gap of [`FLUSH_RIGHT_GAP`] columns and the content fit there; otherwise, and where the line has no width, the gap and then the content after what precedes it ([`DocBuf::flush_right`]); content that cannot print on one line is reported ([`FlushRightLines`]) and printed where the node stands |
115//! | `unknown` (macro) | its source spelling, `\name`, as one atom |
116//! | `image` (inline), `unsupported`, `dropped` | as in a run of blocks, as one atom |
117//! | a `flm.parbreak` | a space |
118//! | any block of a run, inside inline content | on lines of its own |
119//!
120//! ## Decorations
121//!
122//! A decoration is a node whose element carries the
123//! [`Decoration`](crate::stdlib::backends::pres::Decoration) aspect (a run-in
124//! heading, a margin note, a closing mark); the lowering driver moves it out of
125//! the content it was written in into an attached slot of the enclosing
126//! presentation node, and leaves a decoration mark (a `flm.pres.deco-mark`
127//! node) where it was (see [decorations, roles and
128//! kinds](crate::guide::concepts_overview#decorations-roles-and-kinds)). The
129//! emitter prints each decoration at its decoration mark, as one atom made of
130//! its text:
131//!
132//! - a run-in decoration (`flm.pres.deco-runin`) as its text followed by the
133//!   stop [`TextRenderOptions::run_in_stop`] (a period by default), then a
134//!   breakable space. The stop is added only where the decoration's content
135//!   does not already end in sentence punctuation (`.`, `,`, `:`, `;`, `?` or
136//!   `!`, as [`ends_in_sentence_punctuation`] tests): a feature that wants
137//!   another stop, for instance a colon after a defined term, writes it in the
138//!   content, and the emitter adds nothing;
139//! - a closing decoration (`flm.pres.deco-final`) after a non-breaking space
140//!   (U+00A0), so that it never starts a line by itself;
141//! - a margin decoration (`flm.pres.deco-margin`) as `[text]`, between
142//!   breakable spaces.
143//!
144//! A decoration whose content holds no text prints nothing. A decoration that
145//! was not moved (because the content it is written in belongs to no
146//! presentation node, for instance at the top level of a fragment laid out as
147//! inline content) prints the same way where it is written.
148//!
149//! ## Links
150//!
151//! Under the default render options, a `link` to an address outside the
152//! document prints the address after its content, as ` <address>`; it prints
153//! its content alone when [`TextRenderOptions::link_addresses`] is off. A link
154//! whose content already shows its address (the payload's
155//! [`shows_target`](crate::stdlib::backends::pres::LinkPayload::shows_target),
156//! set by `\url` and `\email`) prints its content alone unless
157//! [`TextRenderOptions::link_addresses_when_shown`] is on as well. A link to a
158//! place inside the document (an address beginning with `#`) prints its
159//! content alone. A link with no content prints `<address>` where the address
160//! would be printed, and nothing otherwise.
161//!
162//! # Position marks: where a printed byte came from
163//!
164//! The emitter wraps every presentation node it prints in a mark of the layout
165//! engine, and records which lowered node each mark stands for: a
166//! [`LoweredAddr`], which gives the document tree the node was lowered from
167//! and the node's position in that tree's lowered form. [`TextOutput::marks`]
168//! holds the result ([`TextMark`]): a range of printed bytes leads to a
169//! lowered node, which [`LoweredAddr::resolve`] finds in the lowered-trees
170//! table; that node's span and provenance lead to the source the text was
171//! written from. A position mark never refers to a node of a [frozen
172//! tree](crate::guide::concepts_overview#frozen-trees-and-computed-data),
173//! because a lowered node may stand for no single node of the document. The
174//! bytes printed for a piece carry no mark.
175//!
176//! # Style marks: what plain text could not show
177//!
178//! Some content carries a property that plain text cannot show: a heading's
179//! title, a bold or an emphasized span, the address of a link. The emitter
180//! prints such content as plain text, and records where it printed it in a
181//! *style mark* ([`TextStyleMark`], in [`TextOutput::styles`]). It also records
182//! a style mark for the characters it draws to set content apart: the rule
183//! under a heading, the rule lines of a `text.ruled` node, the frame or the
184//! rule of a table. A style mark holds the byte range and the line and column
185//! range of the characters it covers, and the property ([`TextStyle`]). A
186//! program that writes the text to a medium able to show the property reads
187//! the style marks; the extension `profile-tty`, which is compiled into the
188//! `flm` program, paints them with terminal escape sequences. A style mark
189//! never changes the printed text.
190//!
191//! The marks belong to the text backend, and the painting to the program
192//! that writes the text. Only the printer knows where a node's content lands
193//! once the lines are broken and indented, so only the backend can say which
194//! bytes are bold. A medium's codes, such as a terminal's escape sequences,
195//! belong to the program that writes to that medium: the text output stays
196//! the same for every reader, and a medium is served without a backend of
197//! its own that would lay the text out a second time.
198//!
199//! The printed ranges that get a style mark:
200//!
201//! | lowered node | style mark |
202//! |---|---|
203//! | `block-heading` | [`Heading`](TextStyle::Heading), holding the heading's depth below the root heading level, over the title as printed, with the `#` characters in front of a deep heading; the rule under a heading is outside it; [`HeadingRule`](TextStyle::HeadingRule) over that rule, and over the `#` characters with the space after them |
204//! | `runin-heading` | [`Heading`](TextStyle::Heading), holding the heading's depth, over the title; the stop written after it is outside it |
205//! | `span` of style `Bold`, `Italic`, `Emphasis`, `Underline`, `Monospace` or `SmallCaps` | the style of the same name over the span's content |
206//! | `link` | [`Link`](TextStyle::Link), holding the link's target as the payload has it, over the link's content; the ` <address>` printed after it is outside it |
207//! | `verbatim`, inline or as a block | [`Verbatim`](TextStyle::Verbatim) over the content |
208//! | `cells` | [`TableBorder`](TextStyle::TableBorder) over each run of characters drawn for the table on a line: a whole frame line or rule line, each bar of a line of the rows |
209//! | `text.ruled` | [`Rule`](TextStyle::Rule) over each rule line, one mark per line |
210//!
211//! A superscript or subscript span gets no style mark, since its text is
212//! already written in Unicode superscript or subscript forms; nor does any
213//! other node. The text of a list label and of a decoration (a run-in heading,
214//! a theorem's heading) is printed as one piece of flattened text, and the
215//! styled nodes inside it get style marks over their parts of that text. The
216//! style marks are recorded inside pieces too (the title, the list of notes,
217//! the bibliography, the table of contents), unlike the position marks, because
218//! a piece is printed with the same styles as the document's content.
219//! [`TextOutput::styles`] holds them in the order the printer reaches their
220//! nodes, a node's mark before the marks inside it, and the ranges of two style
221//! marks are either nested or apart. A styled node whose content prints no
222//! character gets no style mark, so the range of a style mark is never empty.
223//!
224//! The content of a `cells` table has its position marks and style marks
225//! like any other content, each over its text where the cell stands in the
226//! table. They follow the marks of the table's node: first the table's
227//! [`TableBorder`](TextStyle::TableBorder) marks, then the marks inside its
228//! cells, row by row and column by column. A mark over several lines of a
229//! cell is one range per line of the cell on which it covers a character,
230//! each over that line's part of the cell's text and the ranges of one mark
231//! consecutive, because the table prints the cell's lines between the frame
232//! or the gutter and the other cells of the row. A range never covers a
233//! character its cell did not print.
234//!
235//! # Further rules of the mapping
236//!
237//! - **A group inside verbatim content prints without its braces.** A parse
238//!   never produces a group inside a [verbatim
239//!   region](crate::guide::concepts_overview#verbatim-regions), since `{` is an
240//!   ordinary character there. A content group found inside one is therefore
241//!   the wrapper of an argument that a user definition's template
242//!   ([`template`](crate::lang::rewrites::userdefs::template)) substituted
243//!   there, and its braces belong to the syntax of the call, not to the
244//!   content: its children are printed and its braces are not. Every other
245//!   node inside verbatim content is printed as its source spelling, braces
246//!   included, since a macro's braces are part of what the author wrote.
247//! - **Mathematics prints as its source, with delimiters**: `\(…\)` for inline
248//!   mathematics, `\[…\]` for display mathematics, `\begin{env}…\end{env}` for
249//!   a math environment. The delimiters the author wrote are not part of the
250//!   payload, so every way of writing inline mathematics prints as `\(…\)`.
251//! - **A superscript span prints its text raised, a subscript span lowered**:
252//!   each character of the span's text is written in its Unicode superscript or
253//!   subscript form ([`superscript_form`], [`subscript_form`]), and a character
254//!   that has none is written unchanged, so `10` is `¹⁰`, `a` is `ᵃ`, and `q`
255//!   stays `q`. No marker such as `^` is added, since the output is read by a
256//!   person. The conversion applies to the text of everything nested inside the
257//!   span (a link, another span), and a nested span of the other of the two
258//!   styles converts its own text its own way. What is not text of the document
259//!   is written unchanged: the address printed after a link, mathematics and
260//!   verbatim content (printed as their source), a decoration moved out of the
261//!   span, a stand-in such as `[dropped: …]`.
262//! - **What plain text cannot express is dropped without a diagnostic**: a
263//!   span's style other than superscript and subscript (a `Bold`, `Italic`,
264//!   `Emphasis`, `Underline`, `Monospace` or `SmallCaps` style recorded as a
265//!   style mark, but not printed); the document role of a
266//!   block, a span or a link; a link's accessible name; the role and kinds of a
267//!   block or a span; a list's kinds; every anchor; an image's width and
268//!   alternative sources; a line's right indentation and its alignment; a
269//!   verbatim node's kind and language; a link's kind and a target inside the
270//!   document. Presentation is dropped that way; content never is.
271//! - **A lowered tree need not be structured into blocks.** Consecutive inline
272//!   nodes in a run of blocks are filled together as one paragraph, split at
273//!   the blocks of the run and at paragraph breaks, so a tree that went through
274//!   no block-structure pass still prints.
275//! - **The walk is bounded** by a depth limit, read once when the walk starts
276//!   from the stack that remains on its worker thread for guarded operations:
277//!   that stack divided by an estimate of the stack one level of the walk uses
278//!   (12 KiB). At the top of a thread of the library, which declares
279//!   [`WORKER_STACK_SIZE`](crate::lang::guard::WORKER_STACK_SIZE), the limit is
280//!   just under 4096 levels; a thread that declares a smaller stack gives a
281//!   smaller limit. A tree that nests deeper, counting the trees it places,
282//!   prints nothing and is reported as `flm.text.nesting-too-deep`
283//!   ([`NestingTooDeep`]).
284//!
285//! # Diagnostics
286//!
287//! The emitter reports, at error severity: [`MissingSubtree`] and
288//! [`SubtreeCycle`] for a tree placed inside another that cannot be printed;
289//! [`PiecePlacement`] for a piece that places a tree; [`NestingTooDeep`] for a
290//! tree nested beyond the depth limit; [`NoWorkerThread`] when it cannot run at
291//! all; [`FlushRightLines`] for content of a `text.flush-right` node that
292//! cannot print on one line; and the presentation condition
293//! `flm.pres.heading-above-root`
294//! ([`HeadingAboveRoot`](crate::stdlib::backends::pres::HeadingAboveRoot))
295//! for a heading above the root heading level. A
296//! [condition](crate::guide::concepts_overview#diagnostics) is the typed body
297//! of a diagnostic; each condition's documentation states what the emitter
298//! prints instead.
299
300use std::borrow::Cow;
301use std::collections::BTreeSet;
302use std::fmt;
303use std::ops::Range;
304use std::sync::Arc;
305
306use techy::core::node::{NodeId, NodeKind, NodeRef, NodeTree};
307use techy::error::{Diagnostic, DiagnosticInfo};
308use techy::serialize::SerialValue;
309
310use crate::model::addr::TreeId;
311use crate::model::element::element_of;
312use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
313use crate::lang::guard;
314use crate::lang::structural;
315use crate::lang::{nowhere, Flm, FlmDiagnostics, FlmGroupType, FlmOrigin};
316use crate::layout::{
317    self, ColAlign, ColSpec, DocBuf, DocId, LineCol, MarkId, Profile, RawPolicy, TableCell,
318    display_width, is_breakable_space, print, print_full,
319};
320use crate::core::piece::PiecePlace;
321use crate::model::names::Name;
322use crate::stdlib::backends::lowering::{LoweredAddr, LoweredTrees};
323use crate::stdlib::backends::pieces::{LoweredPiece, LoweredPieces};
324use crate::stdlib::backends::pres::{
325    self, CellAlign, CellHeader, CellsPayload, DroppedPayload, GridPosition, HeadingPayload, ImageDisplay, ImagePayload, LinePayload, LinkPayload, MathDisplay,
326    MathPassthroughPayload, MathTextPayload, SpanPayload, SpanStyle, SubtreePayload, UnknownKind,
327    UnknownPayload, UnsupportedPayload, VerbatimDisplay, VerbatimPayload, cells_of, decoration_at,
328    ends_in_sentence_punctuation, heading_depth, holds_text, is_presentation, list_entries,
329    payload_of, plain_text, recompose_source,
330};
331
332use super::construct::{FLUSH_RIGHT, FLUSH_RIGHT_GAP, RULED, RuledPayload};
333use super::stages::{TableFrame, TextRenderOptions};
334use super::superscript::{subscript_form, superscript_form};
335
336// --- the output table --------------------------------------------------------------------
337
338/// A position mark of the text output: where the text printed for one lowered
339/// node is in [`TextOutput::text`].
340///
341/// It holds the layout engine's mark identifier, the lowered node it stands
342/// for, and the byte range and the line and column range of that node's printed
343/// content characters. [`TextOutput::marks`] holds one per printed presentation
344/// node, except a node printed over several lines of a table's cell, which has
345/// one mark per line of the cell on which it prints a character (see the
346/// [module documentation](self#style-marks-what-plain-text-could-not-show));
347/// and [`TextOutput::slice`] returns the text it covers.
348///
349/// Two runs over the same document produce equal marks, because a lowered node
350/// is addressed by its position rather than by an identifier assigned during
351/// the run.
352#[derive(Debug, Clone, PartialEq, Eq)]
353pub struct TextMark {
354    /// The layout engine's identifier of the mark. The emitter assigns
355    /// identifiers in the order it builds the marked parts, so the mark of an
356    /// enclosing node has a larger identifier than the marks inside it; the
357    /// order of [`TextOutput::marks`] is the order in which the printer opens
358    /// the marks.
359    pub id: MarkId,
360    /// The lowered node this mark stands for. Find the node in the backend's
361    /// lowered-trees table with
362    /// [`LoweredAddr::resolve`](crate::stdlib::backends::lowering::LoweredAddr::resolve);
363    /// the address refers to no node of a [frozen
364    /// tree](crate::guide::concepts_overview#frozen-trees-and-computed-data).
365    pub addr: LoweredAddr,
366    /// The byte range of [`TextOutput::text`] that holds the node's printed
367    /// content characters.
368    pub bytes: Range<usize>,
369    /// The line and column of the first content character printed for the
370    /// node, counted from 0.
371    pub start: LineCol,
372    /// The line and column just after the last content character printed for
373    /// the node.
374    pub end: LineCol,
375}
376
377/// What a style mark ([`TextStyleMark`]) says about the printed range it
378/// covers: a property of the content that plain text cannot show, such as
379/// bold weight or the address of a link, or the characters the text output
380/// draws to set content apart, such as the rule under a heading.
381///
382/// The emitter records one for each presentation node that carries such a
383/// property, and one for each such drawing (the
384/// [module documentation](self#style-marks-what-plain-text-could-not-show)
385/// lists them). A program that writes the text to a medium able to show the
386/// property reads the style marks: the extension `profile-tty`, which is
387/// compiled into the `flm` program, paints them with terminal escape
388/// sequences.
389///
390/// # Examples
391///
392/// ```
393/// use flm_core::stdlib::backends::text::TextStyle;
394///
395/// assert_eq!(TextStyle::Bold.name(), "bold");
396/// let link = TextStyle::Link { href: String::from("https://example.com") };
397/// assert_eq!(link.name(), "link");
398/// ```
399#[derive(Debug, Clone, PartialEq, Eq, Hash)]
400pub enum TextStyle {
401    /// The title of a heading, block or run-in.
402    Heading {
403        /// How deep the heading is below the root heading level, as
404        /// [`heading_depth`] counts it: 0 for a heading at the root level
405        /// ([`TextRenderOptions::root_heading_level`]), 1 for one level
406        /// deeper, and so on; 0 for a heading above the root level.
407        depth: u8,
408    },
409    /// The characters the text output draws to mark a heading: the rule
410    /// under a heading at depth 0 or 1, and the `#` characters in front of a
411    /// deeper heading, with the space after them.
412    HeadingRule {
413        /// The depth of the heading the characters mark, as for
414        /// [`Heading`](Self::Heading).
415        depth: u8,
416    },
417    /// A rule line the text output draws above or under the body of a
418    /// [`flm.pres.text.ruled`](super::construct::RULED) node, such as the
419    /// rules around a document's title. The emitter records one mark for each
420    /// rule line.
421    Rule,
422    /// The characters the text output draws for a table: its frame, or the
423    /// rule of `-` under its header rows
424    /// ([`TextRenderOptions::table_frame`]).
425    /// The emitter records one mark for each maximal run of such characters on
426    /// a line: a whole rule or frame line, and each bar before, between and
427    /// after the cells on its own; the padding spaces around the cells are
428    /// outside them.
429    TableBorder,
430    /// A span of bold weight (`\textbf`).
431    Bold,
432    /// A span of italic shape (`\textit`).
433    Italic,
434    /// A span of semantic emphasis (`\emph`).
435    Emphasis,
436    /// An underlined span.
437    Underline,
438    /// A span in a monospaced face (`\texttt`).
439    Monospace,
440    /// A span in small capitals.
441    SmallCaps,
442    /// Verbatim content, inline or as a block.
443    Verbatim,
444    /// The content of a link, without the address the text output may print
445    /// after it.
446    Link {
447        /// The link's target exactly as the link's payload holds it
448        /// ([`LinkPayload::href`](crate::stdlib::backends::pres::LinkPayload::href)):
449        /// `#` followed by an anchor for a place inside the document, an
450        /// address otherwise.
451        href: String,
452    },
453}
454
455impl TextStyle {
456    /// Returns the style's name as the projection of [`TextOutput`] writes it
457    /// (the `style` key of each style mark): `heading`, `heading-rule`, `rule`,
458    /// `table-border`, `bold`, `italic`, `emphasis`, `underline`, `monospace`,
459    /// `small-caps`, `verbatim` or `link`.
460    pub fn name(&self) -> &'static str {
461        match self {
462            TextStyle::Heading { .. } => "heading",
463            TextStyle::HeadingRule { .. } => "heading-rule",
464            TextStyle::Rule => "rule",
465            TextStyle::TableBorder => "table-border",
466            TextStyle::Bold => "bold",
467            TextStyle::Italic => "italic",
468            TextStyle::Emphasis => "emphasis",
469            TextStyle::Underline => "underline",
470            TextStyle::Monospace => "monospace",
471            TextStyle::SmallCaps => "small-caps",
472            TextStyle::Verbatim => "verbatim",
473            TextStyle::Link { .. } => "link",
474        }
475    }
476}
477
478/// A style mark of the text output: a range of [`TextOutput::text`] whose
479/// content carries a property that plain text cannot show ([`TextStyle`]).
480///
481/// It holds the style, and the byte range and the line and column range of
482/// the content characters it covers, counted as for a position mark
483/// ([`TextMark`]). [`TextOutput::styles`] holds one per styled node printed,
484/// or one per line of a table's cell for a node styled over several lines of
485/// it, and [`TextOutput::style_slice`] returns the text it covers. Unlike
486/// position marks, style marks are recorded inside pieces too (the title, the
487/// list of notes), so that a program painting the text sees every styled
488/// range.
489///
490/// # Examples
491///
492/// ```
493/// use flm_core::layout::LineCol;
494/// use flm_core::stdlib::backends::text::{TextOutput, TextStyle, TextStyleMark};
495///
496/// let output = TextOutput {
497///     text: String::from("A bold word.\n"),
498///     marks: Vec::new(),
499///     styles: vec![TextStyleMark {
500///         style: TextStyle::Bold,
501///         bytes: 2..6,
502///         start: LineCol { line: 0, col: 2 },
503///         end: LineCol { line: 0, col: 6 },
504///     }],
505/// };
506/// assert_eq!(output.style_slice(&output.styles[0]), "bold");
507/// ```
508#[derive(Debug, Clone, PartialEq, Eq)]
509pub struct TextStyleMark {
510    /// The property the covered content carries.
511    pub style: TextStyle,
512    /// The byte range of [`TextOutput::text`] that holds the styled content
513    /// characters.
514    pub bytes: Range<usize>,
515    /// The line and column of the first styled content character, counted
516    /// from 0.
517    pub start: LineCol,
518    /// The line and column just after the last styled content character.
519    pub end: LineCol,
520}
521
522/// The value of the text backend's output table `flm.output.text`
523/// ([`TEXT_OUTPUT`]): the printed document, its position marks and its style
524/// marks.
525///
526/// The emit stage ([`TextEmitStage`](super::stages::TextEmitStage)) writes it
527/// once per run, since the printed text is one document; the regions stage
528/// and the final stage then publish its text as the `text` output's artifact
529/// set (`flm.output.text.document`). A program that writes the text to a
530/// medium able to show what plain text cannot reads its style marks, as the
531/// extension `profile-tty` does to paint the text for a terminal. A caller
532/// that wants the characters and where each part of the document was printed
533/// reads this table; a caller that wants the file reads the artifact set.
534#[derive(Debug, Clone, Default, PartialEq, Eq)]
535pub struct TextOutput {
536    /// The printed text: empty when nothing is printed, otherwise ending in
537    /// exactly one newline.
538    pub text: String,
539    /// The position marks, in the order the printer reaches their nodes in
540    /// the printed text (a node's mark before the marks of its descendants).
541    /// The marks inside the cells of a table follow the table's own marks,
542    /// row by row and column by column, each over its text where the cell
543    /// stands in the table, one mark per line of the cell for a node printed
544    /// over several lines of it.
545    pub marks: Vec<TextMark>,
546    /// The style marks, in the same order: the order the printer reaches
547    /// their nodes, a node's mark before the marks inside it, and a table's
548    /// [`TableBorder`](TextStyle::TableBorder) marks before the marks inside
549    /// its cells, one mark per line of a cell for a node styled over several
550    /// lines of it. See the [module
551    /// documentation](self#style-marks-what-plain-text-could-not-show).
552    pub styles: Vec<TextStyleMark>,
553}
554
555impl TextOutput {
556    /// Returns the printed text that `mark` covers.
557    ///
558    /// # Panics
559    ///
560    /// Panics if the byte range of `mark` lies outside this output's text or
561    /// does not start and end on character boundaries. A mark taken from this
562    /// output's own [`marks`](Self::marks), with the output unchanged since
563    /// printing, never panics; a mark from another output, a mark built or
564    /// changed by hand, or an output whose `text` was changed after printing
565    /// can.
566    pub fn slice(&self, mark: &TextMark) -> &str {
567        &self.text[mark.bytes.clone()]
568    }
569
570    /// Returns the printed text that the style mark `mark` covers.
571    ///
572    /// # Panics
573    ///
574    /// Panics if the byte range of `mark` lies outside this output's text or
575    /// does not start and end on character boundaries. A mark taken from this
576    /// output's own [`styles`](Self::styles), with the output unchanged since
577    /// printing, never panics; a mark from another output, a mark built or
578    /// changed by hand, or an output whose `text` was changed after printing
579    /// can.
580    pub fn style_slice(&self, mark: &TextStyleMark) -> &str {
581        &self.text[mark.bytes.clone()]
582    }
583
584    /// Returns the marks that stand for the lowered node at `addr`, in the order
585    /// of [`marks`](Self::marks). A node printed several times (for instance in a
586    /// tree placed twice) has several marks; a node for which nothing was
587    /// printed has none.
588    pub fn marks_at(&self, addr: LoweredAddr) -> impl Iterator<Item = &TextMark> + '_ {
589        self.marks.iter().filter(move |mark| mark.addr == addr)
590    }
591
592    /// Whether the output holds no text and no mark.
593    fn is_empty(&self) -> bool {
594        self.text.is_empty() && self.marks.is_empty() && self.styles.is_empty()
595    }
596}
597
598impl Table for TextOutput {
599    /// The table is written once per run, so it receives one table piece (the
600    /// part of a table one stage invocation produced); a non-empty table piece
601    /// replaces the value held so far.
602    fn absorb(&mut self, piece: TextOutput) {
603        if !piece.is_empty() {
604            *self = piece;
605        }
606    }
607
608    fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
609        let position = |at: LineCol| SerialValue::Str(format!("{}:{}", at.line, at.col));
610        let bytes = |range: &Range<usize>| {
611            SerialValue::List(vec![
612                SerialValue::Int(range.start as i64),
613                SerialValue::Int(range.end as i64),
614            ])
615        };
616        let styles = self
617            .styles
618            .iter()
619            .map(|mark| {
620                let mut entries =
621                    vec![(String::from("style"), SerialValue::Str(String::from(mark.style.name())))];
622                match &mark.style {
623                    TextStyle::Heading { depth } | TextStyle::HeadingRule { depth } => {
624                        entries.push((String::from("depth"), SerialValue::Int(i64::from(*depth))));
625                    }
626                    TextStyle::Link { href } => {
627                        entries.push((String::from("href"), SerialValue::Str(href.clone())));
628                    }
629                    _ => {}
630                }
631                entries.push((String::from("bytes"), bytes(&mark.bytes)));
632                entries.push((String::from("start"), position(mark.start)));
633                entries.push((String::from("end"), position(mark.end)));
634                SerialValue::Map(entries)
635            })
636            .collect();
637        SerialValue::Map(vec![
638            (String::from("text"), SerialValue::Str(self.text.clone())),
639            (
640                String::from("marks"),
641                SerialValue::List(
642                    self.marks
643                        .iter()
644                        .map(|mark| {
645                            SerialValue::Map(vec![
646                                (String::from("addr"), SerialValue::Str(mark.addr.to_string())),
647                                (String::from("bytes"), bytes(&mark.bytes)),
648                                (String::from("start"), position(mark.start)),
649                                (String::from("end"), position(mark.end)),
650                            ])
651                        })
652                        .collect(),
653                ),
654            ),
655            (String::from("styles"), SerialValue::List(styles)),
656        ])
657    }
658
659    fn piece_class(&self) -> PieceClass {
660        if self.is_empty() {
661            PieceClass::Empty
662        } else {
663            PieceClass::DocumentFact
664        }
665    }
666}
667
668impl SingletonTable for TextOutput {
669    const NAME: &'static str = "flm.output.text";
670}
671
672/// The typed name of the text output table, `flm.output.text`, which holds a
673/// [`TextOutput`].
674pub const TEXT_OUTPUT: TableName<TextOutput> = TableName::new("flm.output.text");
675
676// --- conditions ---------------------------------------------------------------------------
677
678/// Condition `flm.text.flush-right-lines`: the content of a
679/// [`flm.pres.text.flush-right`](super::construct::FLUSH_RIGHT) node prints on
680/// more than one line, so it cannot be set at the right edge of one line.
681///
682/// Content takes several lines when it holds a line break: two blocks of a
683/// run, for instance, or verbatim content of several lines. The lowering rule
684/// that staged the node gave it that content, so this condition reports a
685/// mistake in a feature rather than in a document. Reported at error severity, at the
686/// node. Recovery: the content is printed where the node stands, as the
687/// content of a span is, and nothing is set at the right edge.
688#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
689#[diagnostic(
690    id = "flm.text.flush-right-lines",
691    message = "Misconfigured element ‘flm.pres.text.flush-right’: its content must fit on \
692               one line (it takes {lines} lines)"
693)]
694pub struct FlushRightLines {
695    /// The number of lines the content prints on when printed alone, with no
696    /// line width.
697    pub lines: usize,
698}
699
700/// Condition `flm.text.missing-subtree`: a `flm.pres.subtree` node places a
701/// tree that has no lowered form for the text backend, because its lowering
702/// failed or because the document has no tree with that identifier.
703///
704/// A `flm.pres.subtree` node stands for a tree placed inside another one (a
705/// fragment placed inside another fragment); the emitter prints the placed
706/// tree at that node. Reported at error severity, at the node. Recovery:
707/// nothing is printed for the node.
708#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
709#[diagnostic(
710    id = "flm.text.missing-subtree",
711    message = "the document tree `{tree}` is placed inside another tree, but it has no text to \
712               print there: no tree has that identifier, or that tree could not be converted to \
713               text"
714)]
715pub struct MissingSubtree {
716    /// The placed tree's identifier.
717    pub tree: String,
718}
719
720/// Condition `flm.text.subtree-cycle`: a `flm.pres.subtree` node places a
721/// tree that is being printed already, because it contains this node,
722/// directly or through other placed trees (a cycle of placements).
723///
724/// Reported at error severity, at the node. Recovery: nothing is printed for
725/// the node; every tree of the cycle is still printed once.
726#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
727#[diagnostic(
728    id = "flm.text.subtree-cycle",
729    message = "the document tree `{tree}` must not be placed inside itself, but it is, \
730               directly or through other trees"
731)]
732pub struct SubtreeCycle {
733    /// The placed tree's identifier.
734    pub tree: String,
735}
736
737/// Condition `flm.text.piece-placement`: a `flm.pres.subtree` node is inside
738/// a piece.
739///
740/// A piece ([`Piece`](crate::core::piece::Piece)) is a document-level value
741/// that a backend places before or after the document's content (the title,
742/// the list of footnotes); it is never placed inside a tree, and it must not
743/// place a tree inside itself. Reported at error severity, at the node.
744/// Recovery: nothing is printed for the node.
745#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
746#[diagnostic(
747    id = "flm.text.piece-placement",
748    message = "the document tree `{tree}` cannot be placed inside `{piece}`, which the text \
749               output places beside the document's content"
750)]
751pub struct PiecePlacement {
752    /// The piece's name.
753    pub piece: String,
754    /// The identifier of the tree the node places.
755    pub tree: String,
756}
757
758/// Condition `flm.text.worker-thread-unavailable`: the emitter could not run
759/// on a worker thread, so it was not run.
760///
761/// A worker thread is a thread marked with the size of its stack
762/// ([`mark_worker_thread`](crate::lang::guard::mark_worker_thread));
763/// [`on_worker_thread`](crate::lang::guard::on_worker_thread) creates one, with
764/// [`WORKER_STACK_SIZE`](crate::lang::guard::WORKER_STACK_SIZE) bytes of stack, when
765/// the calling thread is not one (see [the recursion guard and worker
766/// threads](crate::guide::concepts_overview#the-recursion-guard-and-worker-threads)). The emitter
767/// needs one because its walk recurses as deeply as the trees nest, and its
768/// depth limit is read from the stack that the thread declares. The
769/// calling thread was not a worker thread, and the operating system refused to
770/// create one. Reported at error severity, with no position in the document.
771/// Recovery: the run has no text output.
772// The emitter creates the worker thread itself rather than requiring the
773// caller to run it on one, so that a deeply nested document never crashes the
774// process. The refusal is the operating system's and cannot be provoked without
775// injecting a failure, so no test covers this arm; the spawning half of the
776// contract is what the emitter tests exercise.
777#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
778#[diagnostic(
779    id = "flm.text.worker-thread-unavailable",
780    message = "printing the text output needs a thread with a large stack, and the operating \
781               system refused to create one: {detail}"
782)]
783pub struct NoWorkerThread {
784    /// The operating system's error message.
785    pub detail: String,
786}
787
788/// The emitter's estimate of the stack one level of nesting of its walk uses:
789/// an upper bound on two frames of the inline or of the block recursion,
790/// measured under 4 KiB in a debug build (a thousand nested spans print on a
791/// 4 MiB stack and overflow a 2 MiB one). It is three times the measurement,
792/// so that the limit holds in every build profile. A walk's depth limit is the
793/// stack that remains for guarded operations when it starts, divided by this
794/// estimate.
795const LEVEL_STACK_ESTIMATE: usize = 12 * 1024;
796
797/// Condition `flm.text.nesting-too-deep`: a lowered tree, counting the trees
798/// it places, nests deeper than the emitter's depth limit, which the walk
799/// reads when it starts from the stack that remains on its thread (see the
800/// [module documentation](self)). The detail gives the limit, in levels.
801///
802/// A tree that came from a parsed document never comes near the limit on a
803/// thread of the library, since the parse refuses far shallower nesting. A
804/// lowered tree can, when its lowering rules stage (build into the lowered
805/// tree) levels of their own, or when placed trees form a long chain; the
806/// levels of the placed trees count toward the depth of the tree that places
807/// them.
808///
809/// Every recursive walk of a tree in this library is bounded in this way, and
810/// each reports its own condition, so a diagnostic tells which step reached
811/// its limit. Reported at error severity, once, at the root of the top-level
812/// tree (or piece). Recovery: that tree prints nothing.
813#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
814#[diagnostic(
815    id = "flm.text.nesting-too-deep",
816    message = "the content nests too deeply to be printed as text: {detail}"
817)]
818pub struct NestingTooDeep {
819    /// The limit that was exceeded, as text.
820    pub detail: String,
821}
822
823/// The label `text backend` that a diagnostic shows in place of a position,
824/// for a condition this backend reports that has no position in the document:
825/// the label of the empty source that [`nowhere`] spans.
826pub(crate) const NOWHERE_LABEL: &str = "text backend";
827
828// --- the entry point ----------------------------------------------------------------------
829
830/// The result of [`emit()`]: the output, and the diagnostics reported.
831///
832/// When the emitter cannot print at all, [`output`](Self::output) is `None`
833/// and a diagnostic says why; [`emit()`] never returns an error.
834#[derive(Debug)]
835pub struct Emitted {
836    /// The printed text and its position marks; `None` when the emitter could
837    /// not run.
838    pub output: Option<TextOutput>,
839    /// The diagnostics, in the order they were reported.
840    pub diags: FlmDiagnostics,
841}
842
843/// Prints the lowered trees of `trees` listed in `order`, in that order, with
844/// the lowered `pieces` placed before and after them, under the render options
845/// `options`, and returns the printed text with its position marks and the
846/// diagnostics.
847///
848/// The pieces placed before the content come first, in their order, then the
849/// trees, then the pieces placed after the content; any two of them are
850/// separated by one blank line. Position marks are recorded for the bytes
851/// printed for the trees, not for a piece's bytes. A `flm.pres.subtree` node
852/// inside a piece prints nothing and is reported as [`PiecePlacement`].
853///
854/// A tree placed by a `flm.pres.subtree` node of another tree is printed at
855/// that node, and is not printed again at the top level even when `order`
856/// lists it. Trees that place each other in a cycle are printed after the
857/// others, so that every tree of `order` is printed once; the cycle is
858/// reported ([`SubtreeCycle`]). A placed tree that has no lowered form is
859/// reported ([`MissingSubtree`]) and prints nothing. A tree of `order` that
860/// has no lowered form in `trees` is left out without a diagnostic; when its
861/// lowering failed, the lowering stage reported the failure. The module
862/// documentation
863/// lists what each element prints.
864///
865/// The walk recurses as deeply as the trees nest, so it must run on a worker
866/// thread, a thread that declared its stack size
867/// ([`on_worker_thread`](crate::lang::guard::on_worker_thread)): `emit` runs it
868/// on the calling thread when that thread is a worker thread, and on a new
869/// worker thread otherwise. A problem in the trees never makes `emit` fail or
870/// panic: a tree that cannot be printed is left out and reported, and when the
871/// emitter cannot run at all, [`Emitted::output`] is `None` beside an Error
872/// diagnostic ([`NoWorkerThread`]).
873pub fn emit(
874    trees: &LoweredTrees,
875    order: &[TreeId],
876    pieces: &LoweredPieces,
877    options: &TextRenderOptions,
878) -> Emitted {
879    match guard::on_worker_thread(|| emit_on_worker_thread(trees, order, pieces, options)) {
880        Ok(emitted) => emitted,
881        Err(error) => {
882            let mut diags = FlmDiagnostics::new();
883            diags.push(Diagnostic::error(
884                NoWorkerThread { detail: error.to_string() },
885                nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
886            ));
887            Emitted { output: None, diags }
888        }
889    }
890}
891
892/// The emission itself, once the caller is known to be on a worker thread: the
893/// pieces placed before the content, every tree of `order` that no other tree
894/// places, in order, then the trees a placement cycle left unprinted, then the
895/// pieces placed after the content, one blank line apart (see the [module
896/// documentation](self#the-pieces-and-the-content)), printed at the width of
897/// `options`.
898fn emit_on_worker_thread(
899    trees: &LoweredTrees,
900    order: &[TreeId],
901    pieces: &LoweredPieces,
902    options: &TextRenderOptions,
903) -> Emitted {
904    let mut emitter = Emitter {
905        buf: DocBuf::new(),
906        trees,
907        run_in_stop: &options.run_in_stop,
908        link_addresses: options.link_addresses,
909        link_addresses_when_shown: options.link_addresses_when_shown,
910        options,
911        tree: order.first().copied().unwrap_or(TreeId::tree(0)),
912        placing: Vec::new(),
913        printed: BTreeSet::new(),
914        block_containers: Vec::new(),
915        depth: 0,
916        depth_limit: guard::levels_within_budget(LEVEL_STACK_ESTIMATE),
917        refused: false,
918        piece: None,
919        script: None,
920        marks: Vec::new(),
921        diags: FlmDiagnostics::new(),
922    };
923    let placed = emitter.placed_trees();
924    let mut parts: Vec<DocId> = Vec::new();
925    for piece in pieces.at(PiecePlace::BeforeContent) {
926        emitter.piece_part(piece, &mut parts);
927    }
928    // First the trees no other tree places, in order — each splices what it
929    // places; then whatever is still unprinted (trees placing each other in
930    // a cycle), so that every tree of the order prints once and a cycle is
931    // diagnosed rather than swallowed.
932    for pass in 0..2 {
933        for id in order {
934            if emitter.printed.contains(id) || (pass == 0 && placed.contains(id)) {
935                continue;
936            }
937            let Some(lowered) = trees.get(*id) else { continue };
938            let tree = Arc::clone(&lowered.tree);
939            if let Some(doc) = emitter.tree_doc(*id, &tree) {
940                if !parts.is_empty() {
941                    let separator = emitter.buf.blocksep(1);
942                    parts.push(separator);
943                }
944                parts.push(doc);
945            }
946        }
947    }
948    for piece in pieces.at(PiecePlace::AfterContent) {
949        emitter.piece_part(piece, &mut parts);
950    }
951    let root = emitter.buf.concat(&parts);
952    let Emitter { buf, marks, diags, .. } = emitter;
953    let printed = print_full(&buf, root, &Profile::new(options.width));
954    let mut output = TextOutput { text: printed.text, marks: Vec::new(), styles: Vec::new() };
955    for span in printed.marks {
956        match marks.get(span.id.0 as usize) {
957            Some(MarkFor::Position(addr)) => output.marks.push(TextMark {
958                id: span.id,
959                addr: *addr,
960                bytes: span.bytes,
961                start: span.start,
962                end: span.end,
963            }),
964            // A styled node that printed no character gets no style mark,
965            // though the layout engine may report its mark as an empty range.
966            Some(MarkFor::Style(style)) if !span.bytes.is_empty() => {
967                output.styles.push(TextStyleMark {
968                    style: style.clone(),
969                    bytes: span.bytes,
970                    start: span.start,
971                    end: span.end,
972                })
973            }
974            Some(MarkFor::Style(_)) => {}
975            None => {}
976        }
977    }
978    Emitted { output: Some(output), diags }
979}
980
981// --- the emitter ---------------------------------------------------------------------------
982
983/// One token of an inline run: an atom (possibly itself filled prose), a
984/// breakable space (a *gap*), a non-breaking space joining the atoms on either
985/// side of it (a *tie*, which, like a gap, prints nothing at the start of a
986/// run), or a node that takes lines of its own: a block of a run
987/// ([`is_run_block`]) or a displayed formula.
988enum Tok {
989    Gap,
990    Tie,
991    Atom(DocId),
992    Block(DocId),
993}
994
995/// The two ways a span's text is written through other forms of its
996/// characters.
997#[derive(Debug, Clone, Copy, PartialEq, Eq)]
998enum Script {
999    /// Through the superscript forms ([`superscript_form`]).
1000    Raised,
1001    /// Through the subscript forms ([`subscript_form`]).
1002    Lowered,
1003}
1004
1005impl Script {
1006    /// The way a span of `style` writes its text, if it has one of its own.
1007    fn of(style: Option<SpanStyle>) -> Option<Script> {
1008        match style {
1009            Some(SpanStyle::Superscript) => Some(Script::Raised),
1010            Some(SpanStyle::Subscript) => Some(Script::Lowered),
1011            _ => None,
1012        }
1013    }
1014
1015    /// `word` with each character that has a form written in it; a
1016    /// character with none stays as it is.
1017    fn write(self, word: &str) -> String {
1018        let form = match self {
1019            Script::Raised => superscript_form,
1020            Script::Lowered => subscript_form,
1021        };
1022        word.chars().map(|c| form(c).unwrap_or(c)).collect()
1023    }
1024}
1025
1026/// The walk in progress: the layout document being built, where in the trees
1027/// the walk is, and what it has collected.
1028struct Emitter<'t> {
1029    buf: DocBuf,
1030    trees: &'t LoweredTrees,
1031    /// The stop written after a run-in heading's title that does not already
1032    /// end in sentence punctuation; the empty text writes none.
1033    run_in_stop: &'t str,
1034    /// Whether a link to an address prints the address after its content
1035    /// ([`TextRenderOptions::link_addresses`]).
1036    link_addresses: bool,
1037    /// Whether a link showing its own address's display prints the address
1038    /// too ([`TextRenderOptions::link_addresses_when_shown`]).
1039    link_addresses_when_shown: bool,
1040    /// The render options, read for the conversion of lengths to columns
1041    /// ([`TextRenderOptions::columns`]) and for the root heading level.
1042    options: &'t TextRenderOptions,
1043    /// The document tree whose lowered form is being walked.
1044    tree: TreeId,
1045    /// The trees being printed, outermost first (the placement cycle guard).
1046    placing: Vec<TreeId>,
1047    /// The trees printed so far, at the top level or spliced.
1048    printed: BTreeSet<TreeId>,
1049    /// Per tree being printed (innermost last): the indices of its
1050    /// non-presentation containers holding a block of a run.
1051    block_containers: Vec<BTreeSet<usize>>,
1052    /// The open levels of the walk.
1053    depth: usize,
1054    /// The number of levels the walk may open, read when it starts.
1055    depth_limit: usize,
1056    /// Whether the depth limit was hit while printing the current top-level
1057    /// tree.
1058    refused: bool,
1059    /// The piece being printed, if any: its bytes carry no position mark,
1060    /// and it places no tree.
1061    piece: Option<Name>,
1062    /// How the text being walked is written: raised or lowered inside a
1063    /// superscript or subscript span, unchanged (`None`) elsewhere.
1064    script: Option<Script>,
1065    /// The mark table: index = mark id; each entry is a position mark or a
1066    /// style mark.
1067    marks: Vec<MarkFor>,
1068    diags: FlmDiagnostics,
1069}
1070
1071/// What one layout mark of the emitter records.
1072#[derive(Debug, Clone)]
1073enum MarkFor {
1074    /// A position mark: the lowered node printed inside the mark.
1075    Position(LoweredAddr),
1076    /// A style mark: what the content printed inside the mark carries.
1077    Style(TextStyle),
1078}
1079
1080/// The style mark a presentation node gets, if any: a block or run-in
1081/// heading's title, at its depth below the root heading level `root`
1082/// ([`heading_style_depth`]), a span of a style plain text cannot show (a
1083/// superscript or subscript span gets none, its text being written in Unicode
1084/// forms), a link's content, and verbatim content.
1085fn style_of(node: &NodeRef<'_, Flm>, root: u8) -> Option<TextStyle> {
1086    match element_of(node).name.as_str() {
1087        pres::BLOCK_HEADING | pres::RUNIN_HEADING => {
1088            Some(TextStyle::Heading { depth: heading_style_depth(node, root) })
1089        }
1090        pres::SPAN => match payload_of::<SpanPayload>(node)?.style? {
1091            SpanStyle::Bold => Some(TextStyle::Bold),
1092            SpanStyle::Italic => Some(TextStyle::Italic),
1093            SpanStyle::Emphasis => Some(TextStyle::Emphasis),
1094            SpanStyle::Underline => Some(TextStyle::Underline),
1095            SpanStyle::Monospace => Some(TextStyle::Monospace),
1096            SpanStyle::SmallCaps => Some(TextStyle::SmallCaps),
1097            SpanStyle::Superscript | SpanStyle::Subscript | SpanStyle::UnresolvedReference => None,
1098        },
1099        pres::LINK => {
1100            payload_of::<LinkPayload>(node).map(|payload| TextStyle::Link { href: payload.href.clone() })
1101        }
1102        pres::VERBATIM => Some(TextStyle::Verbatim),
1103        _ => None,
1104    }
1105}
1106
1107/// The depth of the heading `node` below the root heading level `root`
1108/// ([`heading_depth`]), its level read from its payload (`root` when it has
1109/// none): 0 for a heading above the root level, which the emitter reports
1110/// where it writes a block heading.
1111fn heading_style_depth(node: &NodeRef<'_, Flm>, root: u8) -> u8 {
1112    let level = payload_of::<HeadingPayload>(node).map_or(root, |payload| payload.level);
1113    heading_depth(level, root).unwrap_or(0)
1114}
1115
1116impl fmt::Debug for Emitter<'_> {
1117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1118        f.debug_struct("Emitter")
1119            .field("tree", &self.tree)
1120            .field("marks", &self.marks.len())
1121            .finish()
1122    }
1123}
1124
1125/// Whether the element of `node` has the name `name`.
1126fn is_element(node: &NodeRef<'_, Flm>, name: &str) -> bool {
1127    element_of(node).name == name
1128}
1129
1130/// Whether a node is a block of a run of blocks, separated from its
1131/// neighbors in the run by a blank line: a paragraph, a block, a block
1132/// heading, a list, cells, lines, a placed subtree, a ruled run of blocks
1133/// ([`RULED`]), a block image, a block verbatim, an unattributed environment.
1134///
1135/// An image is a block where its payload says it is one (the content of a
1136/// float, where two images are two blocks) and an atom of the text where it
1137/// is inline; verbatim content likewise follows its payload. A displayed
1138/// formula is not a block of a run: it stands in the inline content around it,
1139/// on lines of its own.
1140fn is_run_block(node: &NodeRef<'_, Flm>) -> bool {
1141    let name = element_of(node).name.as_str();
1142    match name {
1143        pres::PAR
1144        | pres::BLOCK
1145        | pres::BLOCK_HEADING
1146        | pres::LIST
1147        | pres::CELLS
1148        | pres::LINES
1149        | pres::SUBTREE
1150        | RULED => true,
1151        pres::IMAGE => payload_of::<ImagePayload>(node)
1152            .is_some_and(|payload| payload.display == ImageDisplay::Block),
1153        pres::VERBATIM => payload_of::<VerbatimPayload>(node)
1154            .is_some_and(|payload| payload.display == VerbatimDisplay::Block),
1155        // An unattributed environment prints its begin and end lines around its
1156        // body; an unattributed macro is one inline atom.
1157        pres::UNKNOWN => payload_of::<UnknownPayload>(node)
1158            .is_some_and(|payload| payload.kind == UnknownKind::Environment),
1159        _ => false,
1160    }
1161}
1162
1163/// The layout engine's alignment for a cell's alignment.
1164fn col_align(align: CellAlign) -> ColAlign {
1165    match align {
1166        CellAlign::Left => ColAlign::Left,
1167        CellAlign::Center => ColAlign::Center,
1168        CellAlign::Right => ColAlign::Right,
1169    }
1170}
1171
1172/// How many leading rows of a table of cells are rows of column headers: a
1173/// row counts when at least one of its positions holds a cell, and every cell
1174/// at its positions (at the cell's top-left or covered by its span) carries
1175/// [`CellHeader::Column`]; an empty position counts neither way. The engine
1176/// takes at most `u8::MAX` header rows.
1177fn header_rows(payload: &CellsPayload, grid: &[Vec<GridPosition>]) -> u8 {
1178    let is_header = |row: &Vec<GridPosition>| {
1179        let mut held = row.iter().filter_map(|position| match *position {
1180            GridPosition::TopLeft(index) | GridPosition::Covered(index) => Some(index),
1181            GridPosition::Empty => None,
1182        });
1183        let first = held.next();
1184        first.is_some()
1185            && first
1186                .into_iter()
1187                .chain(held)
1188                .all(|index| payload.cells[index].header == Some(CellHeader::Column))
1189    };
1190    let count = grid.iter().take_while(|row| is_header(row)).count();
1191    u8::try_from(count).unwrap_or(u8::MAX)
1192}
1193
1194/// Whether a node is inert in a run (nothing is printed for it).
1195fn is_inert(node: &NodeRef<'_, Flm>) -> bool {
1196    node.is_comment() || is_element(node, structural::PARBREAK)
1197}
1198
1199/// The containers of a tree that are not presentation nodes (lists, groups)
1200/// and hold a block of a run ([`is_run_block`]) somewhere below them; they are laid out as
1201/// runs of blocks. Computed in one pass in reverse storage order (a child's
1202/// index is always greater than its parent's), so the walk looks the
1203/// container up in a set instead of walking its subtree again.
1204fn block_containers(tree: &NodeTree<Flm>) -> BTreeSet<usize> {
1205    let nodes: Vec<NodeRef<'_, Flm>> = tree.iter_storage_order().collect();
1206    let mut set = BTreeSet::new();
1207    for node in nodes.iter().rev() {
1208        if is_presentation(node) || !matches!(node.kind(), NodeKind::List | NodeKind::Group(_)) {
1209            continue;
1210        }
1211        let holds = node
1212            .children()
1213            .iter()
1214            .any(|child| is_run_block(&child) || set.contains(&child.id().index()));
1215        if holds {
1216            set.insert(node.id().index());
1217        }
1218    }
1219    set
1220}
1221
1222/// `text` with every line break and tab replaced by a space: the newline, the
1223/// carriage return, the tab, the vertical tab, the form feed, the next-line
1224/// character and the Unicode line and paragraph separators (an atom may hold
1225/// none of them).
1226fn one_line(text: &str) -> String {
1227    text.replace(
1228        ['\n', '\r', '\t', '\u{000B}', '\u{000C}', '\u{0085}', '\u{2028}', '\u{2029}'],
1229        " ",
1230    )
1231}
1232
1233/// The text of a list label or of a decoration ([`label_text`]), with the
1234/// style marks of the nodes inside it as byte ranges of that text.
1235#[derive(Debug)]
1236struct Flat {
1237    /// The text, whitespace-normalized (one space between words).
1238    text: String,
1239    /// One entry per styled node that contributed text, in document order (a
1240    /// node before the nodes inside it); each range is non-empty, holds no
1241    /// space at either end, and lies inside the ranges of the nodes that
1242    /// contain its node.
1243    styles: Vec<(Range<usize>, TextStyle)>,
1244}
1245
1246impl Flat {
1247    /// `text` with `before` written in front of it and `after` behind it, the
1248    /// style ranges moved with the text.
1249    fn around(self, before: &str, after: &str) -> Flat {
1250        let shift = before.len();
1251        Flat {
1252            text: format!("{before}{}{after}", self.text),
1253            styles: self
1254                .styles
1255                .into_iter()
1256                .map(|(range, style)| (range.start + shift..range.end + shift, style))
1257                .collect(),
1258        }
1259    }
1260}
1261
1262/// The text of a list label or of a decoration: its plain text
1263/// ([`plain_text`]), whitespace-normalized ([`normalized`]), each character
1264/// inside a superscript or subscript span written in the forms of the
1265/// innermost such span, as in running text, and the range each styled node
1266/// inside it covers ([`style_of`]). A label and a decoration are printed as
1267/// one text, not walked as a run.
1268fn label_text<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>, root: u8) -> Flat {
1269    let mut text = String::new();
1270    // The styled nodes met so far, in document order, with the range of the
1271    // text they contributed so far (none yet: `None`).
1272    let mut styles: Vec<(Option<Range<usize>>, TextStyle)> = Vec::new();
1273    let mut styled: Vec<(NodeId, usize)> = Vec::new();
1274    let mut pending_space = false;
1275    for node in nodes {
1276        for piece in std::iter::once(node).chain(node.descendants()) {
1277            if let Some(style) = style_of(&piece, root) {
1278                styled.push((piece.id(), styles.len()));
1279                styles.push((None, style));
1280            }
1281            let Some(chars) = piece.chars() else { continue };
1282            let ancestors: Vec<NodeRef<'_, Flm>> = std::iter::successors(Some(piece), |at| {
1283                (at.id() != node.id()).then(|| at.parent()).flatten()
1284            })
1285            .collect();
1286            let script = ancestors
1287                .iter()
1288                .filter(|at| is_element(at, pres::SPAN))
1289                .find_map(|at| Script::of(payload_of::<SpanPayload>(at).and_then(|span| span.style)));
1290            let written = match script {
1291                Some(script) => Cow::Owned(script.write(chars)),
1292                None => Cow::Borrowed(chars),
1293            };
1294            let entries: Vec<usize> = ancestors
1295                .iter()
1296                .filter_map(|at| styled.iter().find(|(id, _)| *id == at.id()).map(|(_, index)| *index))
1297                .collect();
1298            for c in written.chars() {
1299                if is_breakable_space(c) {
1300                    pending_space = !text.is_empty();
1301                    continue;
1302                }
1303                if pending_space {
1304                    text.push(' ');
1305                    pending_space = false;
1306                }
1307                let at = text.len();
1308                text.push(c);
1309                for index in &entries {
1310                    let range = &mut styles[*index].0;
1311                    let start = range.as_ref().map_or(at, |range| range.start);
1312                    *range = Some(start..text.len());
1313                }
1314            }
1315        }
1316    }
1317    // A styled node that contributed no text has no range.
1318    let styles = styles.into_iter().filter_map(|(range, style)| Some((range?, style))).collect();
1319    Flat { text, styles }
1320}
1321
1322/// The whitespace-normalized text of a run (one space between words). Words are
1323/// separated at breakable whitespace only ([`is_breakable_space`]), so a
1324/// non-breaking space stays in the text as written.
1325fn normalized(text: &str) -> String {
1326    text.split(is_breakable_space).filter(|word| !word.is_empty()).collect::<Vec<_>>().join(" ")
1327}
1328
1329/// How this backend prints a decoration of the element `element`: the text to
1330/// print, what goes before it, and whether a breakable space goes after it.
1331///
1332/// A run-in decoration is its text followed by `stop`, with a space after it
1333/// and none before, since it starts the content it introduces. A closing
1334/// decoration follows a non-breaking space, so that it stays on the line of
1335/// the word before it (with nothing before it when nothing precedes it). A
1336/// margin decoration is written between brackets and spaces. The caller has
1337/// already chosen `stop`: the empty text when the title ends in sentence
1338/// punctuation, or when the render option asks for no stop. The style ranges
1339/// of `plain` move with its text; the stop and the brackets are outside them.
1340fn deco_shape(element: &str, plain: Flat, stop: &str) -> (Flat, Before, bool) {
1341    match element {
1342        pres::DECO_RUNIN => (plain.around("", stop), Before::Nothing, true),
1343        pres::DECO_FINAL => (plain, Before::Tie, false),
1344        pres::DECO_MARGIN => (plain.around("[", "]"), Before::Gap, true),
1345        _ => (plain, Before::Gap, true),
1346    }
1347}
1348
1349/// What a decoration is preceded by ([`deco_shape`]).
1350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1351enum Before {
1352    /// Nothing of its own.
1353    Nothing,
1354    /// A breakable space.
1355    Gap,
1356    /// A non-breaking space, joining it to the atom before it.
1357    Tie,
1358}
1359
1360impl<'t> Emitter<'t> {
1361    /// The trees that a `subtree` node of another lowered tree places (a tree
1362    /// that places itself forms a cycle; it is printed at the top level and
1363    /// reported).
1364    fn placed_trees(&self) -> BTreeSet<TreeId> {
1365        let mut placed = BTreeSet::new();
1366        for (id, lowered) in &self.trees.trees {
1367            for node in lowered.tree.iter_storage_order() {
1368                if let Some(payload) = payload_of::<SubtreePayload>(&node) {
1369                    if payload.tree != *id {
1370                        placed.insert(payload.tree);
1371                    }
1372                }
1373            }
1374        }
1375        placed
1376    }
1377
1378    /// Opens one level of the walk; returns `false`, and records the refusal,
1379    /// past the depth limit.
1380    fn descend(&mut self) -> bool {
1381        if self.depth >= self.depth_limit {
1382            self.refused = true;
1383            return false;
1384        }
1385        self.depth += 1;
1386        true
1387    }
1388
1389    /// Closes one level of the walk.
1390    fn ascend(&mut self) {
1391        self.depth -= 1;
1392    }
1393
1394    /// The blocks of one lowered tree; nothing, with the condition recorded
1395    /// at the root of the outermost tree, when the depth limit was reached.
1396    ///
1397    /// Inside a piece, `tree` is the piece's lowered value: it is not a
1398    /// document tree, so it is neither recorded as printed nor added to the
1399    /// chain of placing trees.
1400    fn tree_doc(&mut self, id: TreeId, tree: &Arc<NodeTree<Flm>>) -> Option<DocId> {
1401        if !self.descend() {
1402            return None;
1403        }
1404        let in_piece = self.piece.is_some();
1405        let saved = self.tree;
1406        if !in_piece {
1407            self.tree = id;
1408            self.placing.push(id);
1409            self.printed.insert(id);
1410        }
1411        self.block_containers.push(block_containers(tree));
1412        let root = tree.root();
1413        let children: Vec<NodeRef<'_, Flm>> = root.children().iter().collect();
1414        let doc = if root.is_list() { self.block_run(&children) } else { self.block_run(&[root]) };
1415        self.block_containers.pop();
1416        if !in_piece {
1417            self.placing.pop();
1418        }
1419        self.tree = saved;
1420        self.ascend();
1421        if !self.refused {
1422            return doc;
1423        }
1424        if self.placing.is_empty() {
1425            self.refused = false;
1426            self.diags.push(Diagnostic::error(
1427                NestingTooDeep {
1428                    detail: format!("more than {} levels", self.depth_limit),
1429                },
1430                root.span().clone(),
1431            ));
1432        }
1433        None
1434    }
1435
1436    /// One piece at the top level, one block separation after what `parts`
1437    /// already holds; nothing when it prints nothing.
1438    fn piece_part(&mut self, piece: &LoweredPiece, parts: &mut Vec<DocId>) {
1439        let saved = self.piece.replace(piece.name.clone());
1440        let tree = Arc::clone(&piece.tree.tree);
1441        let doc = self.tree_doc(self.tree, &tree);
1442        self.piece = saved;
1443        if let Some(doc) = doc {
1444            if !parts.is_empty() {
1445                let separator = self.buf.blocksep(1);
1446                parts.push(separator);
1447            }
1448            parts.push(doc);
1449        }
1450    }
1451
1452    /// Wraps `doc` in a new layout mark and records which lowered node that
1453    /// mark stands for; inside a piece, returns `doc` unchanged.
1454    fn marked(&mut self, node: &NodeRef<'_, Flm>, doc: DocId) -> DocId {
1455        if self.piece.is_some() {
1456            return doc;
1457        }
1458        self.mark(MarkFor::Position(LoweredAddr::new(self.tree, node.id())), doc)
1459    }
1460
1461    /// Wraps `doc` in a new layout mark recording `what`.
1462    fn mark(&mut self, what: MarkFor, doc: DocId) -> DocId {
1463        let id = self.mark_id(what);
1464        self.buf.mark(id, doc)
1465    }
1466
1467    /// A new layout mark recording `what`, for the layout engine to report
1468    /// under it.
1469    fn mark_id(&mut self, what: MarkFor) -> MarkId {
1470        let id = MarkId(self.marks.len() as u32);
1471        self.marks.push(what);
1472        id
1473    }
1474
1475    /// Wraps `doc` in a style mark for `style`, inside a piece as well as
1476    /// outside one.
1477    fn styled(&mut self, style: TextStyle, doc: DocId) -> DocId {
1478        self.mark(MarkFor::Style(style), doc)
1479    }
1480
1481    /// Wraps `doc` in the style mark that `node` gets ([`style_of`]); returns
1482    /// `doc` unchanged for a node that gets none.
1483    fn styled_as(&mut self, node: &NodeRef<'_, Flm>, doc: DocId) -> DocId {
1484        match style_of(node, self.options.root_heading_level) {
1485            Some(style) => self.styled(style, doc),
1486            None => doc,
1487        }
1488    }
1489
1490    /// One atom printing the text of `flat`, each of its style ranges
1491    /// wrapped in a style mark. The atom prints exactly what one text node
1492    /// holding `flat.text` prints: the parts are text nodes concatenated with
1493    /// no place to break between them.
1494    fn flat_atom(&mut self, flat: Flat) -> DocId {
1495        // The levels open: the parts gathered so far, the style that closes
1496        // the level (none for the outermost), and where the level ends.
1497        let mut levels: Vec<(Vec<DocId>, Option<TextStyle>, usize)> =
1498            vec![(Vec::new(), None, flat.text.len())];
1499        let mut at = 0;
1500        for (range, style) in flat.styles {
1501            while levels.len() > 1 && levels.last().is_some_and(|(_, _, end)| *end <= range.start) {
1502                at = self.close_flat_level(&flat.text, at, &mut levels);
1503            }
1504            if at < range.start {
1505                let text = self.buf.text(&flat.text[at..range.start]);
1506                if let Some((parts, _, _)) = levels.last_mut() {
1507                    parts.push(text);
1508                }
1509                at = range.start;
1510            }
1511            levels.push((Vec::new(), Some(style), range.end));
1512        }
1513        while levels.len() > 1 {
1514            at = self.close_flat_level(&flat.text, at, &mut levels);
1515        }
1516        let (mut parts, _, end) = levels.pop().unwrap_or_default();
1517        if at < end {
1518            parts.push(self.buf.text(&flat.text[at..end]));
1519        }
1520        match parts.as_slice() {
1521            [] => self.buf.text(""),
1522            [single] => *single,
1523            _ => self.buf.concat(&parts),
1524        }
1525    }
1526
1527    /// Closes the innermost level of [`flat_atom`](Self::flat_atom): its text
1528    /// up to its end, wrapped in its style mark and added to the level
1529    /// around it. Returns where the text written so far ends.
1530    fn close_flat_level(
1531        &mut self,
1532        text: &str,
1533        mut at: usize,
1534        levels: &mut Vec<(Vec<DocId>, Option<TextStyle>, usize)>,
1535    ) -> usize {
1536        let Some((mut parts, style, end)) = levels.pop() else { return at };
1537        if at < end {
1538            parts.push(self.buf.text(&text[at..end]));
1539            at = end;
1540        }
1541        let doc = self.buf.concat(&parts);
1542        let doc = match style {
1543            Some(style) => self.styled(style, doc),
1544            None => doc,
1545        };
1546        if let Some((outer, _, _)) = levels.last_mut() {
1547            outer.push(doc);
1548        }
1549        at
1550    }
1551
1552    // --- block context ---------------------------------------------------------------------
1553
1554    /// A run of nodes in block context: the blocks of the run
1555    /// ([`is_run_block`]) as blocks, maximal runs of the other nodes filled
1556    /// together, one blank line between blocks.
1557    fn block_run(&mut self, nodes: &[NodeRef<'_, Flm>]) -> Option<DocId> {
1558        self.block_run_of(None, nodes)
1559    }
1560
1561    /// [`block_run`](Self::block_run) over the content run of the
1562    /// presentation node `carrier`, when there is one: a decoration the
1563    /// lowering driver moved out of that run is printed at its decoration
1564    /// mark, as inline
1565    /// content, on a line of its own when a block follows it.
1566    fn block_run_of(&mut self, carrier: Option<&NodeRef<'_, Flm>>, nodes: &[NodeRef<'_, Flm>]) -> Option<DocId> {
1567        let mut parts: Vec<DocId> = Vec::new();
1568        let mut inline: Vec<Tok> = Vec::new();
1569        let flush = |this: &mut Emitter<'_>, inline: &mut Vec<Tok>, parts: &mut Vec<DocId>| {
1570            if inline.is_empty() {
1571                return;
1572            }
1573            let toks = std::mem::take(inline);
1574            if let Some(doc) = this.fill(toks) {
1575                parts.push(doc);
1576            }
1577        };
1578        for node in nodes {
1579            if is_inert(node) {
1580                flush(self, &mut inline, &mut parts);
1581                continue;
1582            }
1583            if is_run_block(node) || self.is_block_container(node) {
1584                flush(self, &mut inline, &mut parts);
1585                if let Some(doc) = self.block(node) {
1586                    parts.push(doc);
1587                }
1588            } else if let (Some(carrier), true) = (carrier, is_element(node, pres::DECO_MARK)) {
1589                inline.extend(self.decoration(carrier, node));
1590            } else {
1591                inline.extend(self.inline_tokens(node));
1592            }
1593        }
1594        flush(self, &mut inline, &mut parts);
1595        if parts.is_empty() {
1596            return None;
1597        }
1598        let mut separated: Vec<DocId> = Vec::with_capacity(parts.len() * 2);
1599        for (index, part) in parts.into_iter().enumerate() {
1600            if index > 0 {
1601                let separator = self.buf.blocksep(1);
1602                separated.push(separator);
1603            }
1604            separated.push(part);
1605        }
1606        Some(self.buf.concat(&separated))
1607    }
1608
1609    /// Whether a container that is not a presentation node, in a run of
1610    /// blocks, holds a block of a run; it is then laid out as a run of
1611    /// blocks (the set [`block_containers`] computed on entering the tree).
1612    fn is_block_container(&self, node: &NodeRef<'_, Flm>) -> bool {
1613        self.block_containers.last().is_some_and(|set| set.contains(&node.id().index()))
1614    }
1615
1616    /// One block of a run (or a container of blocks), marked; nothing past
1617    /// the depth limit.
1618    fn block(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
1619        if !self.descend() {
1620            return None;
1621        }
1622        // A block standing inside a superscript or subscript span is not
1623        // raised or lowered with the span's text: it takes lines of its own.
1624        let script = self.script.take();
1625        let doc = self.block_at(node);
1626        self.script = script;
1627        self.ascend();
1628        doc
1629    }
1630
1631    /// One block of a run at the level already opened: the element's own
1632    /// layout, marked; a node that is not a presentation node contributes its
1633    /// children as a run of blocks.
1634    fn block_at(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
1635        if !is_presentation(node) {
1636            let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
1637            return self.block_run(&children);
1638        }
1639        let name = element_of(node).name.clone();
1640        let doc = match name.as_str() {
1641            pres::PAR => {
1642                let body: Vec<NodeRef<'_, Flm>> =
1643                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
1644                let toks = self.inline_run(node, &body);
1645                self.fill(toks)?
1646            }
1647            pres::BLOCK_HEADING => self.heading(node)?,
1648            pres::BLOCK => {
1649                let body: Vec<NodeRef<'_, Flm>> =
1650                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
1651                self.block_run_of(Some(node), &body)?
1652            }
1653            pres::LIST => self.list(node)?,
1654            pres::CELLS => self.cells(node)?,
1655            pres::LINES => self.lines(node)?,
1656            pres::VERBATIM => self.verbatim_block(node)?,
1657            pres::SUBTREE => self.subtree(node)?,
1658            pres::UNKNOWN => self.unknown_environment(node)?,
1659            RULED => self.ruled(node)?,
1660            _ => {
1661                let toks = self.inline_tokens(node);
1662                return self.fill(toks);
1663            }
1664        };
1665        Some(self.marked(node, doc))
1666    }
1667
1668    /// The address a `flm.pres.link` prints after its content, `<address>`,
1669    /// where the options ask for it: never for a link inside the document (a
1670    /// target beginning with `#`), and, for a link whose content already shows
1671    /// its address, only when
1672    /// [`link_addresses_when_shown`](TextRenderOptions::link_addresses_when_shown)
1673    /// is on. `None` where nothing is printed.
1674    fn printed_address(&self, node: &NodeRef<'_, Flm>) -> Option<String> {
1675        let payload = payload_of::<LinkPayload>(node)?;
1676        let printed = self.link_addresses
1677            && (!payload.shows_target || self.link_addresses_when_shown)
1678            && !payload.href.starts_with('#');
1679        printed.then(|| format!("<{}>", one_line(&payload.href)))
1680    }
1681
1682    /// A `flm.pres.block-heading`: the heading text with a rule under it at
1683    /// depths 0 and 1 below the root heading level
1684    /// ([`TextRenderOptions::root_heading_level`], counted from 0 by
1685    /// [`heading_depth`]; a heading above the root is reported and written at
1686    /// depth 0), and `depth + 1` `#` characters in front of it below that — three
1687    /// for a heading two levels below the root. The rule is drawn by the layout
1688    /// engine ([`DocBuf::ruled`]), as wide as the widest line the title prints,
1689    /// with the characters [`heading_rules`](TextRenderOptions::heading_rules)
1690    /// chooses.
1691    fn heading(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
1692        let level = payload_of::<HeadingPayload>(node)
1693            .map_or(self.options.root_heading_level, |payload| payload.level);
1694        let depth = match heading_depth(level, self.options.root_heading_level) {
1695            Ok(depth) => depth,
1696            Err(above) => {
1697                self.diags.push(Diagnostic::error(above, node.span().clone()));
1698                0
1699            }
1700        };
1701        let body: Vec<NodeRef<'_, Flm>> =
1702            node.body().map(|b| b.iter().collect()).unwrap_or_default();
1703        let toks = self.inline_run(node, &body);
1704        let text = self.fill(toks);
1705        // The title carries the heading's style mark, and the rule under it or
1706        // the `#` prefix in front of it a style mark of its own; the prefix is
1707        // inside the title's mark, the rule outside it.
1708        match self.options.heading_rules.rule(depth) {
1709            Some(rule) => {
1710                let text = text?;
1711                let title = self.styled(TextStyle::Heading { depth }, text);
1712                let mark = self.mark_id(MarkFor::Style(TextStyle::HeadingRule { depth }));
1713                Some(self.buf.ruled(title, rule, false, true, Some(mark)))
1714            }
1715            None => {
1716                let prefix = format!("{} ", "#".repeat(usize::from(depth) + 1));
1717                let prefix = self.buf.text(&prefix);
1718                let prefix = self.styled(TextStyle::HeadingRule { depth }, prefix);
1719                let title = match text {
1720                    Some(text) => self.buf.concat(&[prefix, text]),
1721                    None => prefix,
1722                };
1723                Some(self.styled(TextStyle::Heading { depth }, title))
1724            }
1725        }
1726    }
1727
1728    /// A [`flm.pres.text.ruled`](RULED) node: its body as a run of blocks,
1729    /// set by the layout engine ([`DocBuf::ruled`]) between the rule lines its
1730    /// payload asks for, drawn with the character of a heading at the root
1731    /// level ([`heading_rules`](TextRenderOptions::heading_rules)), each rule
1732    /// line under the style mark [`Rule`](TextStyle::Rule). Nothing when the
1733    /// body prints nothing.
1734    fn ruled(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
1735        let payload = payload_of::<RuledPayload>(node).copied().unwrap_or_default();
1736        let body: Vec<NodeRef<'_, Flm>> =
1737            node.body().map(|b| b.iter().collect()).unwrap_or_default();
1738        let content = self.block_run_of(Some(node), &body)?;
1739        let mark = self.mark_id(MarkFor::Style(TextStyle::Rule));
1740        // Depth 0 always has a rule character; `=` is the ASCII one.
1741        let rule = self.options.heading_rules.rule(0).unwrap_or('=');
1742        Some(self.buf.ruled(content, rule, payload.above, payload.below, Some(mark)))
1743    }
1744
1745    /// The content of a [`flm.pres.text.flush-right`](FLUSH_RIGHT) node,
1746    /// `content`, set by the layout engine at the right edge of its line
1747    /// ([`DocBuf::flush_right`], with the gap [`FLUSH_RIGHT_GAP`]). Content
1748    /// that prints on more than one line when printed alone cannot be set
1749    /// there: it is reported as `flm.text.flush-right-lines`
1750    /// ([`FlushRightLines`]) and returned as it is, to stand where the node
1751    /// stands.
1752    fn flush_right(&mut self, node: &NodeRef<'_, Flm>, content: DocId) -> DocId {
1753        let alone = print(&self.buf, content, &Profile::new(None));
1754        let lines = alone.strip_suffix('\n').unwrap_or(&alone).split('\n').count();
1755        if lines > 1 {
1756            self.diags.push(Diagnostic::error(FlushRightLines { lines }, node.span().clone()));
1757            return content;
1758        }
1759        self.buf.flush_right(content, FLUSH_RIGHT_GAP)
1760    }
1761
1762    /// A `flm.pres.list`: one entry per label/item pair, every item's blocks
1763    /// hanging at one column, the width of the widest label plus one, or at
1764    /// the margin when every label is empty.
1765    fn list(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
1766        let entries = list_entries(node);
1767        if entries.is_empty() {
1768            return None;
1769        }
1770        let root = self.options.root_heading_level;
1771        let labels: Vec<Flat> = entries.iter().map(|(label, _)| label_text(label.iter(), root)).collect();
1772        // A column is kept for the labels only where some label is written:
1773        // a list whose labels are all empty hangs its items at the margin.
1774        let column = match labels.iter().map(|label| display_width(&label.text)).max() {
1775            None | Some(0) => 0,
1776            Some(widest) => widest + 1,
1777        };
1778        let mut parts: Vec<DocId> = Vec::new();
1779        for ((_, item), label) in entries.iter().zip(labels) {
1780            if !parts.is_empty() {
1781                let separator = self.buf.blocksep(1);
1782                parts.push(separator);
1783            }
1784            let items: Vec<NodeRef<'_, Flm>> = item.iter().collect();
1785            match self.block_run(&items) {
1786                Some(body) => {
1787                    let width = display_width(&label.text);
1788                    let padding = " ".repeat(column.saturating_sub(width) as usize);
1789                    let label = self.flat_atom(label.around("", &padding));
1790                    let hung = self.buf.align(body);
1791                    parts.push(self.buf.concat(&[label, hung]));
1792                }
1793                // An empty item prints its label alone: padding it would end
1794                // the line in whitespace.
1795                None => parts.push(self.flat_atom(label)),
1796            }
1797        }
1798        Some(self.buf.concat(&parts))
1799    }
1800
1801    /// A `flm.pres.cells`: one table of the layout engine, built from the
1802    /// payload's grid ([`CellsPayload::grid`]): one column per column, one
1803    /// row per row, each cell's content as a run of blocks at its top-left
1804    /// position in the cell's own alignment, and an empty document at every
1805    /// other position (covered by a span, or empty). The leading rows of
1806    /// column headers are the engine's header rows, with its rule under them.
1807    /// The table is drawn as [`TextRenderOptions::table_frame`] says, and the
1808    /// characters the engine draws for it get the style mark
1809    /// [`TableBorder`](TextStyle::TableBorder).
1810    /// Row headers, rules and custom styles are not shown in plain text.
1811    fn cells(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
1812        let (payload, contents) = cells_of(node)?;
1813        let contents: Vec<Option<DocId>> = contents
1814            .iter()
1815            .map(|content| {
1816                let nodes: Vec<NodeRef<'_, Flm>> =
1817                    content.map(|slice| slice.iter().collect()).unwrap_or_default();
1818                self.block_run(&nodes)
1819            })
1820            .collect();
1821        let empty = self.buf.concat(&[]);
1822        let grid = payload.grid();
1823        let rows: Vec<Vec<TableCell>> = grid
1824            .iter()
1825            .map(|row| {
1826                row.iter()
1827                    .map(|position| match *position {
1828                        GridPosition::TopLeft(index) => TableCell {
1829                            doc: contents[index].unwrap_or(empty),
1830                            align: payload.cells[index].align.map(col_align),
1831                        },
1832                        GridPosition::Covered(_) | GridPosition::Empty => TableCell::new(empty),
1833                    })
1834                    .collect()
1835            })
1836            .collect();
1837        let row_refs: Vec<&[TableCell]> = rows.iter().map(Vec::as_slice).collect();
1838        let cols = vec![ColSpec::left(); payload.cols as usize];
1839        let header_rows = header_rows(payload, &grid);
1840        let frame = match self.options.table_frame {
1841            TableFrame::None => layout::TableFrame::Gutter,
1842            TableFrame::Box => layout::TableFrame::Box,
1843        };
1844        let border = self.mark_id(MarkFor::Style(TextStyle::TableBorder));
1845        Some(self.buf.table(&cols, &row_refs, header_rows, frame, Some(border)))
1846    }
1847
1848    /// A `flm.pres.lines`: one printed line per `flm.pres.line` child,
1849    /// indented by that line's left indentation.
1850    fn lines(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
1851        let body: Vec<NodeRef<'_, Flm>> =
1852            node.body().map(|b| b.iter().collect()).unwrap_or_default();
1853        let mut parts: Vec<DocId> = Vec::new();
1854        for line in &body {
1855            if is_inert(line) {
1856                continue;
1857            }
1858            let content: Vec<NodeRef<'_, Flm>> = if is_element(line, pres::LINE) {
1859                line.body().map(|b| b.iter().collect()).unwrap_or_default()
1860            } else {
1861                vec![*line]
1862            };
1863            let indent = payload_of::<LinePayload>(line)
1864                .map_or(0, |payload| self.options.columns(&payload.indent_left));
1865            // The layout engine indents by at most `u16::MAX` columns.
1866            let indent = u16::try_from(indent).unwrap_or(u16::MAX);
1867            let toks = self.inline_run(line, &content);
1868            let filled = self.fill(toks).unwrap_or_else(|| self.buf.text(""));
1869            let indented = if indent > 0 { self.buf.nest(indent, filled) } else { filled };
1870            let marked =
1871                if is_element(line, pres::LINE) { self.marked(line, indented) } else { indented };
1872            if !parts.is_empty() {
1873                let br = self.buf.hardline();
1874                parts.push(br);
1875            }
1876            parts.push(marked);
1877        }
1878        if parts.is_empty() {
1879            return None;
1880        }
1881        Some(self.buf.concat(&parts))
1882    }
1883
1884    /// The text of verbatim content: text nodes as they are, the children of
1885    /// a group substituted into it without the group's braces (see the module
1886    /// documentation), anything else as its source spelling.
1887    fn verbatim_text(&mut self, nodes: &[NodeRef<'_, Flm>]) -> String {
1888        let mut out = String::new();
1889        for node in nodes {
1890            match node.kind() {
1891                NodeKind::Chars { .. } => out.push_str(node.chars().unwrap_or("")),
1892                NodeKind::Group(_) if node.group_type() == Some(FlmGroupType::Content) => {
1893                    if self.descend() {
1894                        let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
1895                        out.push_str(&self.verbatim_text(&children));
1896                        self.ascend();
1897                    }
1898                }
1899                _ => out.push_str(&recompose_source(&[*node])),
1900            }
1901        }
1902        out
1903    }
1904
1905    /// A `flm.pres.verbatim` printed as a block: its content byte for byte,
1906    /// indented like its surroundings.
1907    fn verbatim_block(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
1908        let body: Vec<NodeRef<'_, Flm>> =
1909            node.body().map(|b| b.iter().collect()).unwrap_or_default();
1910        let text = self.verbatim_text(&body);
1911        if text.is_empty() {
1912            return None;
1913        }
1914        let raw = self.buf.raw(&text, RawPolicy::Indented);
1915        Some(self.styled(TextStyle::Verbatim, raw))
1916    }
1917
1918    /// The body of a math node written out: its nodes as their source, with
1919    /// each text node among them ([`flm.pres.math-text`](pres::MATH_TEXT))
1920    /// written as the command it was written with, around its content on one
1921    /// line, and nothing at all for one with no content (a link target, which
1922    /// shows nothing).
1923    ///
1924    /// A text node of this kind is one of the direct nodes of the body, where
1925    /// the rule that puts text inside mathematics stages (builds) it. Such a
1926    /// node reached anywhere else is printed by this emitter's ordinary inline
1927    /// path, which writes its content without the command: outside a formula,
1928    /// the command means nothing this backend can print.
1929    ///
1930    /// The content is flattened into one line of text here, so a construct
1931    /// inside it contributes its text alone: mathematics inside it loses its
1932    /// delimiters on this path. No rule of the standard features stages that
1933    /// nesting on this backend, and a backend that renders formulas reads the
1934    /// content's nodes rather than this string.
1935    fn math_body(&self, body: &[NodeRef<'_, Flm>]) -> String {
1936        let mut out = String::new();
1937        let mut source: Vec<NodeRef<'_, Flm>> = Vec::new();
1938        for node in body {
1939            if !is_element(node, pres::MATH_TEXT) {
1940                source.push(*node);
1941                continue;
1942            }
1943            out.push_str(&recompose_source(&source));
1944            source.clear();
1945            let content: Vec<NodeRef<'_, Flm>> =
1946                node.body().map(|b| b.iter().collect()).unwrap_or_default();
1947            let content = normalized(&plain_text(content.iter().copied()));
1948            if content.is_empty() {
1949                continue;
1950            }
1951            match payload_of::<MathTextPayload>(node).and_then(|p| p.command.as_deref()) {
1952                Some(command) => out.push_str(&format!("\\{command}{{{content}}}")),
1953                None => out.push_str(&content),
1954            }
1955        }
1956        out.push_str(&recompose_source(&source));
1957        out
1958    }
1959
1960    /// The source of a math node, with its delimiters.
1961    fn math_text(&self, node: &NodeRef<'_, Flm>) -> (MathDisplay, String) {
1962        let body: Vec<NodeRef<'_, Flm>> =
1963            node.body().map(|b| b.iter().collect()).unwrap_or_default();
1964        let source = self.math_body(&body);
1965        let payload = payload_of::<MathPassthroughPayload>(node);
1966        let display = payload.map_or(MathDisplay::Inline, |payload| payload.display);
1967        let text = match (display, payload.and_then(|payload| payload.env.as_deref())) {
1968            (_, Some(env)) => format!("\\begin{{{env}}}{source}\\end{{{env}}}"),
1969            (MathDisplay::Inline, None) => format!("\\({source}\\)"),
1970            (MathDisplay::Display, None) => format!("\\[{source}\\]"),
1971        };
1972        (display, text)
1973    }
1974
1975    /// An unattributed environment: `\begin{name}` on a line of its own, the
1976    /// lowered body as a run of blocks, then `\end{name}` on a line of its own.
1977    /// What the author wrote is document content and is printed as such; the
1978    /// output does not say that the environment is unattributed (declared by
1979    /// no feature), which the run's diagnostics report instead.
1980    fn unknown_environment(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
1981        let name = payload_of::<UnknownPayload>(node)
1982            .map_or_else(String::new, |payload| one_line(&payload.spelling));
1983        let begin = self.buf.text(&format!("\\begin{{{name}}}"));
1984        let body: Vec<NodeRef<'_, Flm>> =
1985            node.body().map(|b| b.iter().collect()).unwrap_or_default();
1986        let content = self.block_run(&body);
1987        let end = self.buf.text(&format!("\\end{{{name}}}"));
1988        let mut parts = vec![begin];
1989        if let Some(content) = content {
1990            let br = self.buf.hardline();
1991            parts.push(br);
1992            parts.push(content);
1993        }
1994        let br = self.buf.hardline();
1995        parts.push(br);
1996        parts.push(end);
1997        Some(self.buf.concat(&parts))
1998    }
1999
2000    /// A `flm.pres.subtree`: the placed tree's own blocks, printed here.
2001    /// Nothing, with a diagnostic, inside a piece, or when that tree is being
2002    /// printed already or has no lowered form.
2003    fn subtree(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
2004        let payload = payload_of::<SubtreePayload>(node)?;
2005        let id = payload.tree;
2006        if let Some(piece) = &self.piece {
2007            self.diags.push(Diagnostic::error(
2008                PiecePlacement { piece: piece.to_string(), tree: id.to_string() },
2009                node.span().clone(),
2010            ));
2011            return None;
2012        }
2013        if self.placing.contains(&id) {
2014            self.diags.push(Diagnostic::error(
2015                SubtreeCycle { tree: id.to_string() },
2016                node.span().clone(),
2017            ));
2018            return None;
2019        }
2020        let Some(lowered) = self.trees.get(id) else {
2021            self.diags.push(Diagnostic::error(
2022                MissingSubtree { tree: id.to_string() },
2023                node.span().clone(),
2024            ));
2025            return None;
2026        };
2027        let tree = Arc::clone(&lowered.tree);
2028        self.tree_doc(id, &tree)
2029    }
2030
2031    // --- inline context ---------------------------------------------------------------------
2032
2033    /// A token stream as filled prose: gaps become spaces that break
2034    /// independently of each other (leading, trailing and repeated gaps
2035    /// collapse), a tie a non-breaking space (leading and trailing ties are
2036    /// dropped, and a tie next to a gap replaces it, so that what it joins
2037    /// stays together), and a [`Tok::Block`] takes lines of its own.
2038    /// `None` when nothing is printed.
2039    fn fill(&mut self, toks: Vec<Tok>) -> Option<DocId> {
2040        let mut parts: Vec<DocId> = Vec::new();
2041        let mut pending_gap = false;
2042        let mut pending_tie = false;
2043        let mut after_block = false;
2044        for tok in toks {
2045            match tok {
2046                Tok::Gap => pending_gap = !parts.is_empty(),
2047                Tok::Tie => pending_tie = !parts.is_empty() && !after_block,
2048                Tok::Atom(doc) => {
2049                    if after_block {
2050                        let br = self.buf.hardline();
2051                        parts.push(br);
2052                    } else if pending_tie {
2053                        let tie = self.buf.text("\u{a0}");
2054                        parts.push(tie);
2055                    } else if pending_gap {
2056                        let line = self.buf.line();
2057                        let separator = self.buf.group(line);
2058                        parts.push(separator);
2059                    }
2060                    pending_gap = false;
2061                    pending_tie = false;
2062                    after_block = false;
2063                    parts.push(doc);
2064                }
2065                Tok::Block(doc) => {
2066                    if !parts.is_empty() {
2067                        let br = self.buf.hardline();
2068                        parts.push(br);
2069                    }
2070                    pending_gap = false;
2071                    pending_tie = false;
2072                    after_block = true;
2073                    parts.push(doc);
2074                }
2075            }
2076        }
2077        if parts.is_empty() {
2078            return None;
2079        }
2080        Some(self.buf.concat(&parts))
2081    }
2082
2083    /// The inline run of `carrier`: its content, with the decorations moved
2084    /// out of it printed at their decoration marks.
2085    fn inline_run(&mut self, carrier: &NodeRef<'_, Flm>, nodes: &[NodeRef<'_, Flm>]) -> Vec<Tok> {
2086        let mut toks = Vec::new();
2087        for node in nodes {
2088            if is_element(node, pres::DECO_MARK) {
2089                toks.extend(self.decoration(carrier, node));
2090            } else {
2091                toks.extend(self.inline_tokens(node));
2092            }
2093        }
2094        toks
2095    }
2096
2097    /// A decoration moved into an attached slot, at the position of its
2098    /// decoration mark.
2099    fn decoration(&mut self, carrier: &NodeRef<'_, Flm>, mark: &NodeRef<'_, Flm>) -> Vec<Tok> {
2100        match decoration_at(carrier, mark) {
2101            Some(deco) => self.deco_tokens(&deco),
2102            None => Vec::new(),
2103        }
2104    }
2105
2106    /// A decoration as tokens: its content flattened to text, shaped as its
2107    /// element asks ([`deco_shape`]) and surrounded by the breakable spaces
2108    /// that shape asks for. A decoration whose content holds no text
2109    /// ([`holds_text`]) contributes nothing.
2110    ///
2111    /// Every decoration is printed through this function, so a decoration the
2112    /// driver moved into an attached slot and one reached where no mark
2113    /// stands for it are printed alike.
2114    ///
2115    /// Whether a run-in decoration takes a stop is decided from its content
2116    /// tree, by the two tests every backend shares ([`holds_text`] and
2117    /// [`ends_in_sentence_punctuation`]), and never from the text this emitter
2118    /// has flattened it to.
2119    fn deco_tokens(&mut self, deco: &NodeRef<'_, Flm>) -> Vec<Tok> {
2120        let Some((text, before, after)) = self.deco_text(deco) else { return Vec::new() };
2121        let atom = self.flat_atom(text);
2122        let marked = self.marked(deco, atom);
2123        let mut toks = Vec::new();
2124        match before {
2125            Before::Nothing => {}
2126            Before::Gap => toks.push(Tok::Gap),
2127            Before::Tie => toks.push(Tok::Tie),
2128        }
2129        toks.push(Tok::Atom(marked));
2130        if after {
2131            toks.push(Tok::Gap);
2132        }
2133        toks
2134    }
2135
2136    /// What [`deco_tokens`](Self::deco_tokens) sets for the decoration
2137    /// `deco`: its text, what goes before it and whether a breakable space
2138    /// goes after it ([`deco_shape`]); `None` for a decoration whose content
2139    /// holds no text ([`holds_text`]).
2140    fn deco_text(&self, deco: &NodeRef<'_, Flm>) -> Option<(Flat, Before, bool)> {
2141        let body: Vec<NodeRef<'_, Flm>> =
2142            deco.body().map(|b| b.iter().collect()).unwrap_or_default();
2143        if !holds_text(body.iter().copied()) {
2144            return None;
2145        }
2146        let plain = label_text(body.iter().copied(), self.options.root_heading_level);
2147        let element = element_of(deco).name.as_str();
2148        let stop = if element == pres::DECO_RUNIN
2149            && !ends_in_sentence_punctuation(body.iter().copied())
2150        {
2151            self.run_in_stop
2152        } else {
2153            ""
2154        };
2155        Some(deco_shape(element, plain, stop))
2156    }
2157
2158    /// One node of an inline run, as tokens; none past the depth limit.
2159    fn inline_tokens(&mut self, node: &NodeRef<'_, Flm>) -> Vec<Tok> {
2160        if !self.descend() {
2161            return Vec::new();
2162        }
2163        let toks = self.inline_tokens_at(node);
2164        self.ascend();
2165        toks
2166    }
2167
2168    /// One node of an inline run at the level already opened: text split into
2169    /// words and gaps, a presentation element as its own atom or block,
2170    /// anything else as its children.
2171    fn inline_tokens_at(&mut self, node: &NodeRef<'_, Flm>) -> Vec<Tok> {
2172        if let Some(text) = node.chars() {
2173            let mut toks = Vec::new();
2174            if text.starts_with(is_breakable_space) {
2175                toks.push(Tok::Gap);
2176            }
2177            for word in text.split(is_breakable_space).filter(|word| !word.is_empty()) {
2178                let word = match self.script {
2179                    Some(script) => Cow::Owned(script.write(word)),
2180                    None => Cow::Borrowed(word),
2181                };
2182                let atom = self.buf.text(&word);
2183                toks.push(Tok::Atom(atom));
2184                toks.push(Tok::Gap);
2185            }
2186            if !text.ends_with(is_breakable_space) && !text.is_empty() {
2187                toks.pop();
2188            }
2189            return toks;
2190        }
2191        if is_inert(node) {
2192            return if is_element(node, structural::PARBREAK) {
2193                vec![Tok::Gap]
2194            } else {
2195                Vec::new()
2196            };
2197        }
2198        if !is_presentation(node) {
2199            let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
2200            return self.inline_run(node, &children);
2201        }
2202        let name = element_of(node).name.clone();
2203        let doc = match name.as_str() {
2204            pres::SPAN | pres::RUNIN_HEADING => {
2205                let body: Vec<NodeRef<'_, Flm>> =
2206                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
2207                // A superscript or subscript span writes the text of its
2208                // content through the forms of its style, nested content
2209                // included, so that a note's mark, a link inside a superscript
2210                // span, is raised too; a nested span of the other style writes
2211                // its own text its own way.
2212                let outer = self.script;
2213                if name.as_str() == pres::SPAN {
2214                    let style = payload_of::<SpanPayload>(node).and_then(|payload| payload.style);
2215                    if let Some(script) = Script::of(style) {
2216                        self.script = Some(script);
2217                    }
2218                }
2219                let toks = self.inline_run(node, &body);
2220                self.script = outer;
2221                match self.fill(toks) {
2222                    Some(doc) => self.styled_as(node, doc),
2223                    None => return Vec::new(),
2224                }
2225            }
2226            pres::LINK => {
2227                let body: Vec<NodeRef<'_, Flm>> =
2228                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
2229                let toks = self.inline_run(node, &body);
2230                // The style mark covers the content, never the address
2231                // printed after it.
2232                let content = self.fill(toks).map(|content| self.styled_as(node, content));
2233                match (content, self.printed_address(node)) {
2234                    (Some(content), Some(address)) => {
2235                        let tail = self.buf.text(&format!(" {address}"));
2236                        self.buf.concat(&[content, tail])
2237                    }
2238                    (Some(content), None) => content,
2239                    (None, Some(address)) => self.buf.text(&address),
2240                    (None, None) => return Vec::new(),
2241                }
2242            }
2243            pres::MATH_PASSTHROUGH => {
2244                let (display, text) = self.math_text(node);
2245                match display {
2246                    MathDisplay::Inline => self.buf.text(&normalized(&text)),
2247                    MathDisplay::Display => {
2248                        let raw = self.buf.raw(&text, RawPolicy::Indented);
2249                        let nested = self.buf.nest(2, raw);
2250                        let marked = self.marked(node, nested);
2251                        return vec![Tok::Block(marked)];
2252                    }
2253                }
2254            }
2255            pres::VERBATIM => {
2256                let body: Vec<NodeRef<'_, Flm>> =
2257                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
2258                let text = self.verbatim_text(&body);
2259                if text.is_empty() {
2260                    return Vec::new();
2261                }
2262                let block = payload_of::<VerbatimPayload>(node)
2263                    .is_some_and(|payload| payload.display == VerbatimDisplay::Block);
2264                if block || text.contains(['\n', '\t']) {
2265                    let raw = self.buf.raw(&text, RawPolicy::Indented);
2266                    let styled = self.styled(TextStyle::Verbatim, raw);
2267                    let marked = self.marked(node, styled);
2268                    return vec![Tok::Block(marked)];
2269                }
2270                let atom = self.buf.text(&text);
2271                self.styled(TextStyle::Verbatim, atom)
2272            }
2273            pres::IMAGE => {
2274                let label = payload_of::<ImagePayload>(node)
2275                    .map(|payload| {
2276                        let shown = payload.alt.as_deref().filter(|alt| !alt.trim().is_empty());
2277                        format!("[image: {}]", one_line(shown.unwrap_or(&payload.src)))
2278                    })
2279                    .unwrap_or_else(|| String::from("[image]"));
2280                self.buf.text(&label)
2281            }
2282            pres::UNSUPPORTED => {
2283                let element = payload_of::<UnsupportedPayload>(node)
2284                    .map_or_else(|| String::from("?"), |payload| payload.element.to_string());
2285                let text = format!("[unsupported: {element}]");
2286                self.buf.text(&text)
2287            }
2288            pres::DROPPED => {
2289                let detail = payload_of::<DroppedPayload>(node)
2290                    .map_or_else(|| String::from("?"), |payload| one_line(&payload.detail));
2291                let text = format!("[dropped: {detail}]");
2292                self.buf.text(&text)
2293            }
2294            // An unattributed macro, inline: its source spelling. The
2295            // environment kind is a block of a run and falls to the arm below.
2296            pres::UNKNOWN if !is_run_block(node) => {
2297                let text = payload_of::<UnknownPayload>(node)
2298                    .map_or_else(String::new, |payload| one_line(&payload.spelling));
2299                if text.is_empty() {
2300                    return Vec::new();
2301                }
2302                self.buf.text(&text)
2303            }
2304            FLUSH_RIGHT => {
2305                let body: Vec<NodeRef<'_, Flm>> =
2306                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
2307                let toks = self.inline_run(node, &body);
2308                let Some(content) = self.fill(toks) else { return Vec::new() };
2309                self.flush_right(node, content)
2310            }
2311            pres::DECO_MARK => return Vec::new(),
2312            pres::DECO_RUNIN | pres::DECO_FINAL | pres::DECO_MARGIN => {
2313                // A decoration met in a run with no mark standing for it: it was
2314                // never hoisted, because the run it stands in is not the content
2315                // of a presentation node — an inline-layout fragment has no
2316                // paragraph to attach it to. It is set with the same idiom as a
2317                // hoisted one, so that one document reads alike under either
2318                // layout.
2319                return self.deco_tokens(node);
2320            }
2321            // A block of a run inside inline content takes lines of its own,
2322            // with no blank line beside it.
2323            _ if is_run_block(node) => {
2324                return match self.block(node) {
2325                    Some(doc) => vec![Tok::Block(doc)],
2326                    None => Vec::new(),
2327                };
2328            }
2329            _ => {
2330                let body: Vec<NodeRef<'_, Flm>> =
2331                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
2332                let toks = self.inline_run(node, &body);
2333                match self.fill(toks) {
2334                    Some(doc) => doc,
2335                    None => return Vec::new(),
2336                }
2337            }
2338        };
2339        let marked = self.marked(node, doc);
2340        vec![Tok::Atom(marked)]
2341    }
2342}