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