Skip to main content

flm_core/stdlib/backends/html/
emit.rs

1//! The HTML emitter: writes the HTML of one lowered tree through the
2//! [HTML sink](super::sink).
3//!
4//! An emitter is a backend's emit stage: it walks the lowered trees and writes
5//! the output's bytes into a table, from which the backend's final stage makes
6//! the artifact set (see [backends, lowering, and
7//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)).
8//! On this backend, [`emit_tree`] writes one tree; the emit stage
9//! ([`HtmlEmitStage`](super::stages::HtmlEmitStage)) calls it once per
10//! document tree, and the stage `flm.html.emit-pieces` once per
11//! [piece](crate::core::piece::Piece) the render places. It
12//! returns an [`EmittedTree`]: the tree's HTML in segments, the identifiers of
13//! the style and script definitions the tree requires, and the diagnostics
14//! reported along the way.
15//!
16//! # What is written for each element
17//!
18//! The tag, the classes and the attributes of every presentation element come
19//! from that element's row of the [conventions table](super::conventions), the
20//! HTML contract written down as data: the emitter reads the row and never
21//! spells a class or an attribute name of its own. The row also gives the
22//! style definition the element needs, which the emitter **requires** (records
23//! as a requirement of the tree) when it writes the element. The [rendering
24//! guide](crate::guide::rendering#the-html-contract) prints the table.
25//!
26//! A **paragraph** is a `<p>`, except a paragraph that holds **flow
27//! content**: an element this emitter writes with a tag HTML does not allow
28//! inside a `<p>`, such as the `<div>` of a block, a list or a table, which a
29//! displayed item may hold. That paragraph is a `<div>` carrying
30//! `role="paragraph"`, with the same class and the same `id`. The emitter
31//! decides for each paragraph, from the paragraph's lowered content, so no
32//! element has to know of HTML's rule.
33//!
34//! A **paragraph with nothing to show** (its content empty, or only spaces,
35//! source comments and paragraph breaks) is not written at all: the text
36//! backend prints nothing for one, and an empty `<p>` would only add space on
37//! the page. An element inside it, even an empty one, counts as something to
38//! show. A paragraph carrying an anchor, which a link can lead to, is written
39//! even when it is empty.
40//!
41//! Beyond the rows, these elements are written with more than one tag:
42//!
43//! - a **list** writes `<li>` per entry, with a rich label as a
44//!   `<span class="flm-pres-list-label">` at its start; a description list
45//!   (`<dl>`) writes the label as a `<dt>` carrying the same class and the
46//!   entry as a `<dd>`, because those are the only children a `<dl>` may have.
47//!   An entry's anchor is the `id` of its `<li>`, or of its `<dt>`;
48//! - a **table of cells** writes a `<tr>` per row of its grid and, in it, a
49//!   `<td>` (a `<th>` carrying `scope` for a header cell) per position that no
50//!   span covers: a cell at its top-left position, with `colspan` and
51//!   `rowspan` where it spans, its alignment, its rules and its custom styles
52//!   as `data-flm-…` attributes and its content as blocks; an empty `<td>`
53//!   where no cell is placed;
54//! - **verbatim content** as a block is `<pre><code>…</code></pre>`, with the
55//!   class and the attributes on the `<pre>` and the content written as text,
56//!   character for character;
57//! - an **unattributed macro** (one no feature declares) is a `<span>` around
58//!   the text the author wrote; an **unattributed environment** is a `<div>`
59//!   holding a `\begin{…}` line, the lowered body, and an `\end{…}` line, each
60//!   line a `<span class="flm-pres-unknown-marker">`;
61//! - a [**decoration**](crate::guide::concepts_overview#decorations-roles-and-kinds)
62//!   of every kind is a `<span>` written at the position of its decoration mark,
63//!   in the flow of the text. A margin decoration is one too, which the core
64//!   stylesheet (`flm.html.style.core`) sets beside the text, because a mark can be inside a paragraph
65//!   and an `<aside>` inside a `<p>` is not valid HTML;
66//! - a **link inside another link's content** is a `<span>` carrying the
67//!   link's classes and kind but no `href`, role or accessible name, because
68//!   an `<a>` inside an `<a>` is not valid HTML; the outer link is the one a
69//!   reader follows. Nothing is reported, since a document may legitimately
70//!   nest links this way (a term link inside the text of an `\href`).
71//!
72//! # Mathematics
73//!
74//! Passthrough mathematics (a formula whose source the
75//! [`math-passthrough`](crate::math_passthrough) feature
76//! carries unread, as a `flm.pres.math-passthrough` node) is not translated
77//! into HTML: it is handed, as the LaTeX the author wrote, to a **formula
78//! renderer**, a script in the reader's browser that reads
79//! LaTeX out of the page and typesets it. FLM does not inspect what a formula
80//! says ([`mod@super::mathjax`] states what that means for a host). Every
81//! formula, inline or displayed, is a `<span>` carrying the class, the display
82//! (`data-flm-display`) and the environment's name; the stylesheet
83//! of passthrough mathematics (`flm.html.style.math-passthrough`) gives a
84//! displayed formula the appearance of a block. One tag serves both
85//! because a displayed formula can be inside a paragraph, and HTML does not
86//! allow a block element there. The emitter writes the delimiters (`\(…\)`,
87//! `\[…\]` or `\begin{…}…\end{…}`), and the document's own source between
88//! them as text. It requires the script definition
89//! [`flm.html.mathjax`](super::conventions::SCRIPT_MATHJAX) at the first
90//! passthrough formula it writes in a tree; a page that does not carry that
91//! script shows
92//! the LaTeX as characters.
93//!
94//! **Content inside a formula** (the text of `\text{…}`, a link, a point a
95//! reference can lead to) is a `flm.pres.math-text` node among the formula's
96//! source. The emitter writes it as HTML inside the formula, through the
97//! formula renderer's `<tex-html>` element:
98//! `<tex-html><span class="flm-pres-math--text" …>…</span></tex-html>`.
99//! The renderer searches the whole formula for its closing delimiter and for
100//! that element, so the emitter breaks up any such sequence in the text it
101//! writes inside a formula; an attribute value holding one is left out and
102//! reported as [`RefusedInMath`].
103//!
104//! The repair of the text is about the `<tex-html>` element, not about who
105//! staged it: the text written inside a `flm.pres.html.tag` construct whose
106//! tag is `tex-html` (which a rule stages to put HTML inside a formula it
107//! writes itself, as a processing feature's rule does) is repaired too, for
108//! every closing delimiter (`\)`, `\]`, `\end{…}`) and the two spellings of
109//! the tag, since the emitter does not know which formula the rule wrote
110//! around it.
111//!
112//! # The trust guarantee
113//!
114//! Every byte goes through the [sink](super::HtmlSink): document text through
115//! its text entry point, every attribute value through its attribute entry
116//! points, each escaped where it is written. This module builds no HTML by
117//! formatting strings and writes no unescaped byte.
118//!
119//! Two kinds of value are checked before they are written, because escaping
120//! does not make them safe:
121//!
122//! - **an address** (a link's `href`, an image's `src` and the candidates of
123//!   its `srcset`) must pass the [address policy](super::check_address), under
124//!   the render option [`HtmlAllowedUrlSchemes`]. A refused
125//!   address is not written and is reported as the Error
126//!   `flm.html.refused-address` ([`AddressRefused`]); the link keeps its text
127//!   and the image its alternative text, because content is never dropped.
128//! - **a tag or attribute name** of a [construct node](super::construct),
129//!   which a lowering rule wrote, must pass the [name check](super::names). A
130//!   node whose name fails it is written as the unsupported stand-in (an empty
131//!   `<span class="flm-pres-unsupported">`) and
132//!   reported as `flm.html.invalid-name` ([`InvalidName`]).
133//!
134//! A third check applies to the two names a rule writes into a node of a
135//! presentation element: a **role**, written as one class, and a **kind**, written
136//! as one token of `data-flm-kind` (see [decorations, roles and
137//! kinds](crate::guide::concepts_overview#decorations-roles-and-kinds)). Both
138//! attributes separate their tokens by whitespace, so a name holding
139//! whitespace would be read as several; such a name is left out (that one
140//! class, that one token) and reported as `flm.html.invalid-name`, and the rest
141//! of the node is written as usual.
142//!
143//! A construct node is outside the HTML contract and outside the address
144//! policy: a lowering rule that stages an HTML tag node (builds it into the
145//! lowered tree; see [`Lowerer`](crate::core::lowering::Lowerer)) is
146//! responsible for the attributes it writes.
147//!
148//! # Trees placed in other trees
149//!
150//! A `flm.pres.subtree` node
151//! ([`SUBTREE`](crate::stdlib::backends::pres::SUBTREE), [`SubtreePayload`])
152//! places another document tree at its position. This emitter sees one tree
153//! only, so it ends the segment it is writing and
154//! records the placed tree ([`HtmlSegment::Tree`]); the regions stage, which
155//! sees every tree, writes the placed tree's HTML there.
156//!
157//! # Limits on nesting
158//!
159//! The walk recurses as deeply as the tree nests, so it must run on a worker
160//! thread, a thread created with at least
161//! [`WORKER_STACK_SIZE`](crate::lang::guard::WORKER_STACK_SIZE) bytes of stack
162//! ([`on_worker_thread`](crate::lang::guard::on_worker_thread); see [the
163//! recursion guard and worker
164//! threads](crate::guide::concepts_overview#the-recursion-guard-and-worker-threads)).
165//! [`emit_tree`] runs it on one. The walk also refuses a tree that nests deeper
166//! than [`DEPTH_LIMIT`], writing nothing for it and reporting
167//! `flm.html.nesting-too-deep` ([`NestingTooDeep`]).
168
169use std::collections::BTreeSet;
170use std::fmt;
171use std::ops::Range;
172use std::sync::Arc;
173
174use techy::core::node::{NodeKind, NodeRef, NodeTree};
175use techy::error::{Diagnostic, DiagnosticInfo};
176
177use crate::lang::guard;
178use crate::layout::is_breakable_space;
179use crate::lang::structural;
180use crate::lang::{Flm, FlmDiagnostics, FlmGroupType, FlmOrigin, FlmSpan, nowhere};
181use crate::model::addr::TreeId;
182use crate::model::element::element_of;
183use crate::model::names::Name;
184use crate::stdlib::backends::pres::{
185    self, BlockPayload, CellHeader, CellSpec, DroppedPayload, GridPosition, HeadingPayload,
186    ImageDisplay, ImagePayload, Length, LinePayload, LinkPayload, ListPayload, MathDisplay,
187    MathPassthroughPayload, MathTextPayload, ParPayload, SpanPayload, SpanStyle, SubtreePayload,
188    UnknownKind, UnknownPayload, UnsupportedPayload, VerbatimDisplay, VerbatimKind,
189    VerbatimPayload, cells_of,
190    decoration_at, ends_in_sentence_punctuation, heading_depth, holds_text, is_presentation,
191    list_entries, payload_of, recompose_source,
192};
193
194use super::address::{AddressUse, HtmlAllowedUrlSchemes, check_address};
195use super::construct::{HtmlTagPayload, TagBody};
196use super::conventions::{
197    Convention, LIST_LABEL_CLASS, PARAGRAPH_FLOW_TAG, PARAGRAPH_ROLE, SCRIPT_MATHJAX,
198    STYLE_ATTRIBUTE, UNKNOWN_MARKER_CLASS, Written, block_tag, css_length, css_ratio,
199    doc_role_value, row,
200};
201use super::escape::json_string_into;
202use super::feature::HtmlRenderOptions;
203use super::names::{class_of_element, class_of_role, data_attribute, is_valid_attribute_name,
204    is_valid_tag_name, is_valid_token, style_property};
205use super::sink::HtmlSink;
206use super::stages::{HtmlSegment, StageFailed};
207
208// --- conditions ---------------------------------------------------------------------------
209
210/// Condition `flm.html.invalid-name` (Error): a name the emitter would write
211/// into the page is not a valid name of its kind, and writing it unchanged
212/// could produce markup nobody asked for.
213///
214/// Four kinds of name are checked, and each has its own recovery:
215///
216/// - the **tag** or an **attribute** name a [construct node](super::construct)
217///   carries. Such a name is writable when it is an ASCII letter followed by
218///   ASCII letters, digits and `-` (an attribute name also `_`, `:` and `.`);
219///   anything else could end the tag early or begin something the rule did not
220///   write. Recovery: the node is written as the unsupported stand-in, an
221///   empty `<span class="flm-pres-unsupported">` naming the element.
222/// - a **role** or a **kind** a presentation node's payload carries, which is
223///   written as one class or as one token of `data-flm-kind`. Such a name is
224///   writable when it is one token — not empty and holding no whitespace
225///   ([`is_valid_token`]), since both of those attributes separate their
226///   tokens by whitespace. Recovery: that one class or that one token is left
227///   out (and when no kind is left, the `data-flm-kind` attribute is not
228///   written at all), while everything else about the node is written as
229///   usual. The condition's `recovery` field says which of those happened.
230/// - a **tag** a host maps a heading kind to, in
231///   [`HtmlRenderOptions::heading_tags`]. Recovery: the heading is written with
232///   the tag of its level counted from the root heading level, `<h1>` to
233///   `<h6>`.
234/// - the name of a **custom style** a cell of a table of cells carries, which
235///   is written as the attribute `data-flm-style-<name>` on the cell. Such a
236///   name is writable when the whole attribute name is, as for a construct
237///   node's attribute above. Recovery: that one attribute is left out, and
238///   the cell is written otherwise as usual.
239///
240/// None of these names is document text: the feature whose lowering rule
241/// staged the node wrote it, or the host gave it in its render options, so this
242/// condition reports a mistake in a feature or a host rather than in a
243/// document. It is reported at the node's position.
244#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
245#[diagnostic(
246    id = "flm.html.invalid-name",
247    message = "the {what} name `{name}` cannot be written into the HTML page: a tag name must be \
248               an ASCII letter followed by ASCII letters, digits and `-`, an attribute name may \
249               also contain `_`, `:` and `.`, and a role or a kind must be one word, not empty \
250               and without whitespace"
251)]
252pub struct InvalidName {
253    /// The kind of name that was refused: `tag`, `attribute`, `role` or
254    /// `kind`.
255    pub what: String,
256    /// The name, as the payload or the render options gave it.
257    pub name: String,
258    /// What the emitter wrote instead, in words (data for a reader of the
259    /// diagnostic; the message does not include it).
260    pub recovery: String,
261}
262
263/// Condition `flm.html.refused-address` (Error): a link's or an image's address
264/// has a scheme that the [address policy](super::check_address) does not allow
265/// under the render option [`HtmlAllowedUrlSchemes`], such as `javascript`.
266///
267/// Reported at the link's or the image's position. Recovery: the address is
268/// not written. The link keeps its text and the image its alternative text, so
269/// the content stays and only the address is lost.
270#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
271#[diagnostic(
272    id = "flm.html.refused-address",
273    message = "the address `{address}` in the `{attribute}` attribute uses the scheme `{scheme}`, which is \
274               not allowed; the allowed addresses are {allowed}"
275)]
276pub struct AddressRefused {
277    /// The address as the link or image gives it.
278    pub address: String,
279    /// The scheme, in lower case and without its colon.
280    pub scheme: String,
281    /// The attribute the address would have been written in: `href`, `src` or
282    /// `srcset`.
283    pub attribute: String,
284    /// The addresses allowed under the value of [`HtmlAllowedUrlSchemes`] in
285    /// effect, in words, as the message gives them.
286    pub allowed: String,
287}
288
289/// Condition `flm.html.refused-in-math` (Error): an attribute value the
290/// emitter would write inside a formula contains a sequence that would break
291/// the formula.
292///
293/// Content inside a formula is written as HTML inside the formula's LaTeX
294/// ([the module documentation](self#mathematics)). The formula renderer
295/// searches all the characters of the formula, attribute values included, for
296/// the closing delimiter the emitter wrote and for its `<tex-html>` tag. Text
297/// holding one of those sequences is broken up with an empty element where it
298/// is written; an attribute value cannot be broken up that way, because an
299/// element written into it would reach the reader as characters.
300///
301/// Reported at the node's position, or at the formula's when the element
302/// belongs to no node of its own. Recovery: that one attribute is left out,
303/// and everything else about the element, its content above all, is written
304/// as usual.
305#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
306#[diagnostic(
307    id = "flm.html.refused-in-math",
308    message = "an attribute value inside a formula must not contain `{sequence}`, which the \
309               formula renderer would read as the end of the formula or as its own tag: the \
310               value of the `{attribute}` attribute contains it"
311)]
312pub struct RefusedInMath {
313    /// The attribute that was left out, by the name it would have been
314    /// written under: `id`, `class`, a `data-flm-…` attribute, or an attribute
315    /// a lowering rule asked for.
316    pub attribute: String,
317    /// The characters in the value that the formula renderer would read as
318    /// the end of the formula or as its own tag: the closing delimiter of the
319    /// surrounding formula (`\)`, `\]` or `\end{<env>}`), `<tex-html` or
320    /// `</tex-html`.
321    pub sequence: String,
322}
323
324/// Condition `flm.html.worker-thread-unavailable` (Error): the emitter could
325/// not run, because the calling thread is not a worker thread and the
326/// operating system refused to create one.
327///
328/// A worker thread is a thread created with at least
329/// [`WORKER_STACK_SIZE`](crate::lang::guard::WORKER_STACK_SIZE) bytes of stack
330/// ([`on_worker_thread`](crate::lang::guard::on_worker_thread)); the emitter
331/// needs one because the walk recurses as deeply as the tree nests. Reported at
332/// no position in a document. Recovery: nothing is written for the tree.
333// The emitter creates the worker thread itself rather than requiring the
334// caller to run it on one, so that a deeply nested document never crashes the
335// process. The refusal is the operating system's and cannot be provoked without
336// injecting a failure, so no test covers this arm.
337#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
338#[diagnostic(
339    id = "flm.html.worker-thread-unavailable",
340    message = "writing HTML needs a thread with a large stack, and the operating system \
341               refused to create one: {detail}"
342)]
343pub struct NoWorkerThread {
344    /// The operating system's error.
345    pub detail: String,
346}
347
348/// The emitter's per-level stack estimate: an upper bound on the stack one
349/// level of nesting of the walk uses, taken from the text emitter's
350/// measurement of the same shape of recursion and tripled, so that the limit
351/// holds in every build profile.
352const LEVEL_STACK_ESTIMATE: usize = 12 * 1024;
353
354/// The nesting depth past which the emitter refuses a tree and reports
355/// `flm.html.nesting-too-deep` ([`NestingTooDeep`]): the recursion guard's
356/// stack budget ([`STACK_BUDGET`](crate::lang::guard::STACK_BUDGET)) divided by
357/// the estimated stack use of one level, which is 4096 levels.
358///
359/// A tree that came from a parsed document never comes near it, since the
360/// parse refuses far shallower nesting. A lowered tree can, when its lowering
361/// rules add levels of their own.
362pub const DEPTH_LIMIT: usize = guard::STACK_BUDGET / LEVEL_STACK_ESTIMATE;
363
364/// Condition `flm.html.nesting-too-deep` (Error): a lowered tree nests deeper
365/// than the emitter's depth limit ([`DEPTH_LIMIT`]).
366///
367/// Every recursive tree walk in this library is bounded in this way, and each
368/// reports its own condition, so a diagnostic says which step ran out of room.
369/// Recovery: nothing is written for that tree, and one Error is reported at
370/// its root.
371#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
372#[diagnostic(
373    id = "flm.html.nesting-too-deep",
374    message = "the content nests too deeply to be written as HTML: {detail}"
375)]
376pub struct NestingTooDeep {
377    /// The limit that was exceeded, in words.
378    pub detail: String,
379}
380
381/// What a diagnostic shows in place of a position for a condition this backend
382/// reports without a position in any document: the label of the empty source
383/// that [`nowhere`](crate::lang::nowhere) spans.
384pub(crate) const NOWHERE_LABEL: &str = "html backend";
385
386// --- the entry point ----------------------------------------------------------------------
387
388/// The result of [`emit_tree`]: one tree's HTML, its requirements, where it
389/// places other trees, and the diagnostics reported.
390#[derive(Debug, Default)]
391pub struct EmittedTree {
392    /// The tree's HTML in order, as segments of bytes and placed trees. Empty
393    /// when nothing was written.
394    pub segments: Vec<HtmlSegment>,
395    /// The identifiers of the style and script definitions the tree's HTML
396    /// requires, as an ordered set.
397    pub requires: BTreeSet<Name>,
398    /// The position of each `flm.pres.subtree` node, one for each
399    /// [`HtmlSegment::Tree`] of `segments`, in the same order, so that a caller
400    /// reporting a placement can give its position.
401    pub placed_at: Vec<FlmSpan>,
402    /// The diagnostics reported, in order.
403    pub diags: FlmDiagnostics,
404}
405
406/// Writes one lowered tree as HTML under the render options `options` and the
407/// value `url_schemes` of the render option [`HtmlAllowedUrlSchemes`], and
408/// returns the HTML with the tree's requirements and diagnostics
409/// ([`EmittedTree`]).
410///
411/// The tree is a lowered tree of the HTML backend: every element in it is one
412/// the backend writes natively ([`native_elements`](super::native_elements));
413/// another element is reported as
414/// [`StageFailed`] and writes nothing. The walk
415/// recurses as deeply as the tree nests, so it must run on a worker thread:
416/// this function runs it on the calling thread when that thread is a worker
417/// thread, and on a new worker thread otherwise
418/// ([`on_worker_thread`](crate::lang::guard::on_worker_thread)).
419///
420/// A tree that cannot be written (no worker thread available, nesting deeper
421/// than [`DEPTH_LIMIT`]) comes back with no segments and an Error diagnostic
422/// ([`NoWorkerThread`], [`NestingTooDeep`]). The emit stages
423/// ([`HtmlEmitStage`](super::stages::HtmlEmitStage),
424/// [`HtmlEmitPiecesStage`](super::stages::HtmlEmitPiecesStage)) call it; a host
425/// may call it directly on a lowered tree.
426pub fn emit_tree(
427    tree: &Arc<NodeTree<Flm>>,
428    options: &HtmlRenderOptions,
429    url_schemes: &HtmlAllowedUrlSchemes,
430) -> EmittedTree {
431    match guard::on_worker_thread(|| emit_on_worker_thread(tree, options, url_schemes)) {
432        Ok(emitted) => emitted,
433        Err(error) => {
434            let mut diags = FlmDiagnostics::new();
435            diags.push(Diagnostic::error(
436                NoWorkerThread { detail: error.to_string() },
437                nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
438            ));
439            EmittedTree { diags, ..EmittedTree::default() }
440        }
441    }
442}
443
444/// The emission itself, once the caller is known to be on a worker thread.
445fn emit_on_worker_thread(
446    tree: &Arc<NodeTree<Flm>>,
447    options: &HtmlRenderOptions,
448    url_schemes: &HtmlAllowedUrlSchemes,
449) -> EmittedTree {
450    let mut emitter = Emitter {
451        sink: HtmlSink::new(),
452        options,
453        url_schemes,
454        placements: Vec::new(),
455        requires: BTreeSet::new(),
456        depth: 0,
457        refused: false,
458        math: None,
459        in_tex_html: false,
460        tex_html_constructs: 0,
461        construct_sequences: Arc::from(sequences_in_construct()),
462        piece: None,
463        links_open: 0,
464        diags: FlmDiagnostics::new(),
465    };
466    let root = tree.root();
467    let children: Vec<NodeRef<'_, Flm>> = root.children().iter().collect();
468    if root.is_list() {
469        emitter.run(None, &children);
470    } else {
471        emitter.run(None, &[root]);
472    }
473    let Emitter { sink, placements, requires, refused, mut diags, .. } = emitter;
474    let html = sink.finish();
475    if refused {
476        diags.push(Diagnostic::error(
477            NestingTooDeep {
478                detail: format!("more than {DEPTH_LIMIT} levels"),
479            },
480            root.span().clone(),
481        ));
482        return EmittedTree { diags, ..EmittedTree::default() };
483    }
484    let placed_at = placements.iter().map(|(_, _, span)| span.clone()).collect();
485    EmittedTree { segments: segments_of(html, &placements), requires, placed_at, diags }
486}
487
488/// The written HTML cut into segments at the byte offsets where a tree was
489/// placed, with the placed trees between the parts.
490///
491/// An empty part — two trees placed side by side, or one placed at the very
492/// beginning or the very end — contributes no segment, so a fragment never
493/// holds an empty string.
494fn segments_of(html: String, placements: &[(usize, TreeId, FlmSpan)]) -> Vec<HtmlSegment> {
495    let mut segments = Vec::new();
496    let mut at = 0usize;
497    for (offset, tree, _) in placements {
498        if *offset > at {
499            segments.push(HtmlSegment::Html(String::from(&html[at..*offset])));
500        }
501        segments.push(HtmlSegment::Tree(*tree));
502        at = *offset;
503    }
504    if at < html.len() {
505        segments.push(HtmlSegment::Html(String::from(&html[at..])));
506    }
507    segments
508}
509
510// --- mathematics: what the formula renderer reads, and the two repairs --------------------
511
512/// The tag of the mechanism by which HTML is put inside a formula:
513/// `tex-html`.
514///
515/// The formula renderer reads the HTML between a `<tex-html>` and its closing
516/// tag **out of the characters of the formula**, before any LaTeX is parsed.
517/// Escaping does not hide the tag from it: the renderer reads the text a
518/// browser built from the page, in which `&lt;` is already `<` again. So the
519/// emitter writes this tag itself, and keeps a document from writing it (see
520/// [`neutralized_source`]).
521const TEX_HTML: &str = "tex-html";
522
523/// The empty TeX group written into a document's own mathematics source where
524/// the tag of [`TEX_HTML`] would otherwise be: `{}`.
525///
526/// It takes no space, it typesets nothing, and — unlike a macro that would do
527/// the same — a document cannot redefine it.
528const EMPTY_GROUP: &str = "{}";
529
530/// A sequence of characters that must not reach the formula renderer's search
531/// whole, held as the two parts the repair is written between.
532///
533/// Three such sequences exist while a formula is being written: the closing
534/// delimiter of that formula ([`closing_delimiter`]), and the two spellings of
535/// the tag of [`TEX_HTML`], `<tex-html` and `</tex-html`. Where the repair
536/// is placed inside the sequence does not matter to the renderer — any break
537/// stops the search from matching — so it is chosen to fall at the sequence's
538/// own joint: after the backslash of `\)` and `\]`, after the `\end` of
539/// `\end{align}`, after the `<` of a tag.
540///
541/// Inside a `tex-html` construct tag a rule staged, every closing delimiter is
542/// broken, since the emitter does not know the formula around it
543/// ([`sequences_in_construct`]).
544#[derive(Debug, Clone, PartialEq, Eq)]
545struct Sequence {
546    /// The characters, unbroken.
547    text: String,
548    /// The byte offset inside `text` at which the repair is written.
549    break_at: usize,
550}
551
552impl Sequence {
553    /// The sequence `before` followed by `after`, broken between the two.
554    fn new(before: &str, after: &str) -> Sequence {
555        Sequence { text: format!("{before}{after}"), break_at: before.len() }
556    }
557}
558
559/// The two spellings of the tag of [`TEX_HTML`] the formula renderer searches
560/// for: the opening `<tex-html` and the closing `</tex-html`, each broken
561/// after its `<`.
562fn tex_html_sequences() -> Vec<Sequence> {
563    vec![Sequence::new("<", TEX_HTML), Sequence::new("<", &format!("/{TEX_HTML}"))]
564}
565
566/// The LaTeX the emitter writes **before** a formula's own source: `\(` for
567/// inline mathematics, `\[` for displayed mathematics, and `\begin{<env>}`
568/// for a formula written in a mathematics environment.
569fn opening_delimiter(display: MathDisplay, env: Option<&str>) -> String {
570    match (display, env) {
571        (_, Some(env)) => format!("\\begin{{{env}}}"),
572        (MathDisplay::Inline, None) => String::from("\\("),
573        (MathDisplay::Display, None) => String::from("\\["),
574    }
575}
576
577/// The LaTeX the emitter writes **after** a formula's own source, as the
578/// sequence that must not reach the formula renderer's search whole from
579/// inside the formula: `\)`, `\]` or `\end{<env>}`.
580fn closing_delimiter(display: MathDisplay, env: Option<&str>) -> Sequence {
581    match (display, env) {
582        (_, Some(env)) => Sequence::new("\\end", &format!("{{{env}}}")),
583        (MathDisplay::Inline, None) => Sequence::new("\\", ")"),
584        (MathDisplay::Display, None) => Sequence::new("\\", "]"),
585    }
586}
587
588/// Every sequence that must not reach the formula renderer's search whole out
589/// of the HTML written inside a formula whose closing delimiter is `closing`:
590/// that delimiter, then the two tag spellings.
591fn sequences_in_math(closing: &Sequence) -> Vec<Sequence> {
592    let mut sequences = vec![closing.clone()];
593    sequences.extend(tex_html_sequences());
594    sequences
595}
596
597/// Every sequence that must not reach the formula renderer's search whole out
598/// of the text written inside a `flm.pres.html.tag` construct whose tag is
599/// [`TEX_HTML`]: the three closing delimiters `\)`, `\]` and `\end{` (any
600/// environment's), then the two tag spellings.
601///
602/// The rule that staged the construct wrote the formula around it; the
603/// emitter does not know which delimiter closes it, so it breaks all three.
604fn sequences_in_construct() -> Vec<Sequence> {
605    let mut sequences = vec![Sequence::new("\\", ")"), Sequence::new("\\", "]"), Sequence::new("\\end", "{")];
606    sequences.extend(tex_html_sequences());
607    sequences
608}
609
610/// A document's own mathematics source with an [empty TeX group](EMPTY_GROUP)
611/// written into every `<tex-html` and `</tex-html` it holds, which keeps a
612/// document from reaching the mechanism that puts HTML inside a formula.
613///
614/// The reader sees the same characters: the group typesets nothing and carries
615/// the spacing the `<` had. It closes the case where a document's author typed
616/// the characters; an author who can define a macro inside mathematics can
617/// still build the tag out of parts, which no substitution over the source
618/// can catch; a host closes that case in the formula renderer's own
619/// configuration ([`super::mathjax`]).
620fn neutralized_source(source: &str) -> String {
621    let sequences = tex_html_sequences();
622    let mut out = String::with_capacity(source.len());
623    let mut at = 0;
624    while at < source.len() {
625        let rest = &source[at..];
626        match sequences.iter().find(|sequence| rest.starts_with(&sequence.text)) {
627            Some(sequence) => {
628                out.push_str(&sequence.text[..sequence.break_at]);
629                out.push_str(EMPTY_GROUP);
630                at += sequence.break_at;
631            }
632            None => {
633                let ch = rest.chars().next().expect("a character starts at a character boundary");
634                out.push(ch);
635                at += ch.len_utf8();
636            }
637        }
638    }
639    out
640}
641
642/// The byte offsets of `text` at which an empty element must be written so
643/// that none of `sequences` reaches the formula renderer's search whole, in
644/// ascending order.
645///
646/// This is the repair for text written **inside** the HTML of a `<tex-html>`,
647/// where the empty TeX group of [`neutralized_source`] would be shown to the
648/// reader as two characters: an empty element shows nothing and breaks the
649/// search just as well.
650fn break_points(text: &str, sequences: &[Sequence]) -> Vec<usize> {
651    let mut points = Vec::new();
652    let mut at = 0;
653    while at < text.len() {
654        let rest = &text[at..];
655        match sequences.iter().find(|sequence| rest.starts_with(&sequence.text)) {
656            Some(sequence) => {
657                at += sequence.break_at;
658                points.push(at);
659            }
660            None => {
661                at += rest
662                    .chars()
663                    .next()
664                    .map_or(1, |ch| ch.len_utf8());
665            }
666        }
667    }
668    points
669}
670
671/// The first of `sequences` that `value` holds; such a sequence makes an
672/// attribute value impossible to write inside the HTML of a `<tex-html>`.
673/// `None` when it holds none.
674///
675/// An attribute value cannot carry the repair of [`break_points`]: an
676/// attribute value is text, so an element written into it reaches the
677/// reader as its characters. Such an attribute is left out instead
678/// ([`RefusedInMath`]).
679fn refused_sequence(value: &str, sequences: &[Sequence]) -> Option<String> {
680    sequences
681        .iter()
682        .filter_map(|sequence| value.find(&sequence.text).map(|at| (at, sequence.text.clone())))
683        .min_by(|(left, _), (right, _)| left.cmp(right))
684        .map(|(_, text)| text)
685}
686
687/// An element left open inside the HTML written into a formula, held so
688/// that it can be written a second time.
689///
690/// A formula placed deeper inside that HTML than the content's own nodes —
691/// `\text{\emph{\(x\)}}` — is written by closing everything open inside the
692/// formula's HTML, writing the inner formula into the formula's own
693/// characters, and opening the same elements again
694/// ([`math_text`](Emitter::math_text) says why). This is what "the same
695/// elements" means: each one's tag, the classes and attributes it was written
696/// with, and whether it is block-level or preformatted.
697#[derive(Debug, Clone)]
698struct OpenInMath {
699    /// The tag the element was opened with.
700    tag: String,
701    /// Whether it was opened as a block-level element.
702    block: bool,
703    /// The classes written on it, empty when none were.
704    classes: Vec<String>,
705    /// The attributes written on it, without an `id` and without the
706    /// source-position attribute: each of those appears once — an identifier
707    /// once in a page, a node's position once on the node's own element — so
708    /// both stay on the element's first half.
709    attributes: Vec<(String, String)>,
710    /// Whether it was opened as preformatted content.
711    preformatted: bool,
712}
713
714/// One part of content being written as HTML inside a formula — one
715/// `<tex-html>` element — while it is being written.
716#[derive(Debug, Clone)]
717struct Piece {
718    /// The classes of the `<span>` the part is written as, which every part
719    /// of the same content carries.
720    classes: Vec<String>,
721    /// The elements open inside that `<span>`, outermost first.
722    open: Vec<OpenInMath>,
723}
724
725/// The formula the emitter is writing, while it is inside one.
726#[derive(Debug, Clone)]
727struct MathContext {
728    /// The sequences that must not reach the formula renderer's search whole
729    /// out of the HTML written inside this formula.
730    sequences: Arc<[Sequence]>,
731    /// The formula's position, which is the position a diagnostic about a
732    /// part of it carries when that part has no position of its own.
733    span: FlmSpan,
734}
735
736// --- the emitter ----------------------------------------------------------------------------
737
738/// The walk in progress.
739struct Emitter<'o> {
740    sink: HtmlSink,
741    options: &'o HtmlRenderOptions,
742    /// The schemes the page's links and images may have.
743    url_schemes: &'o HtmlAllowedUrlSchemes,
744    /// Where a tree was placed: the byte offset in what has been written, the
745    /// tree, and the placing node's span, in the order encountered.
746    placements: Vec<(usize, TreeId, FlmSpan)>,
747    /// The definitions the tree's HTML needs.
748    requires: BTreeSet<Name>,
749    /// The open levels of the walk.
750    depth: usize,
751    /// Whether the depth limit was hit anywhere in this tree.
752    refused: bool,
753    /// The formula being written, while the walk is inside one.
754    math: Option<MathContext>,
755    /// Whether the bytes being written now are inside a `<tex-html>`, which
756    /// is the HTML the emitter puts inside a formula.
757    in_tex_html: bool,
758    /// How many `flm.pres.html.tag` constructs whose tag is `tex-html` the
759    /// walk is inside: their text is repaired as the text inside a formula's
760    /// `<tex-html>` is ([`sequences_in_construct`]).
761    tex_html_constructs: usize,
762    /// The sequences of [`sequences_in_construct`], built once for the walk.
763    construct_sequences: Arc<[Sequence]>,
764    /// The part of content being written as HTML inside a formula, while the
765    /// walk is inside one and past its `<span>`.
766    piece: Option<Piece>,
767    /// How many links the walk is inside: a link reached inside another is
768    /// written without an address of its own ([`Emitter::link`]).
769    links_open: usize,
770    diags: FlmDiagnostics,
771}
772
773impl fmt::Debug for Emitter<'_> {
774    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775        f.debug_struct("Emitter")
776            .field("depth", &self.depth)
777            .field("placements", &self.placements.len())
778            .finish_non_exhaustive()
779    }
780}
781
782/// The children of a node's body slot, or none when it has no body.
783fn body<'t>(node: &NodeRef<'t, Flm>) -> Vec<NodeRef<'t, Flm>> {
784    node.body().map(|slice| slice.iter().collect()).unwrap_or_default()
785}
786
787/// Whether `node` is a node of the element `name`.
788fn is_element(node: &NodeRef<'_, Flm>, name: &str) -> bool {
789    element_of(node).name == name
790}
791
792/// Whether a paragraph's content shows nothing on the page, so that no `<p>`
793/// is written for it: every node of it is text made only of spaces a line may
794/// be broken at ([`is_breakable_space`]), a comment, a paragraph-break marker,
795/// or a group or container holding only such nodes — an empty content
796/// included. A presentation element — a span, a link, an image, a formula, a
797/// decoration's mark — counts as something shown, even with no text inside:
798/// it is written as an element, which a stylesheet may draw or a link may
799/// reach.
800///
801/// This is the criterion the text backend reaches for a paragraph it prints
802/// nothing for, stated over the tree: that backend decides while it lays the
803/// words out, and there an empty span also prints nothing, while on the page
804/// it is nevertheless an element. The walk is iterative, so a deep nesting of
805/// groups cannot exhaust the stack.
806fn shows_nothing(content: &[NodeRef<'_, Flm>]) -> bool {
807    let mut pending: Vec<NodeRef<'_, Flm>> = content.to_vec();
808    while let Some(node) = pending.pop() {
809        if let Some(text) = node.chars() {
810            if !text.chars().all(is_breakable_space) {
811                return false;
812            }
813        } else if node.is_comment() || is_element(&node, structural::PARBREAK) {
814            continue;
815        } else if is_presentation(&node) {
816            return false;
817        } else {
818            pending.extend(node.children().iter());
819        }
820    }
821    true
822}
823
824/// Whether a paragraph holds **flow content**, which HTML does not allow
825/// inside a `<p>`: whether a node the emitter writes with a flow-content tag
826/// ([`written_as_flow`]) stands anywhere in it.
827///
828/// The walk covers every slot of `paragraph`, its decorations included, which
829/// are written at their marks inside it, and goes on into every node written
830/// as phrasing content (a span, a link, a formula and the content written
831/// inside it), stopping at the first node written as flow content. Like
832/// [`shows_nothing`], it reads the lowered tree, never the bytes written, and
833/// is iterative, so a deep nesting of groups cannot exhaust the stack.
834fn holds_flow_content(paragraph: &NodeRef<'_, Flm>) -> bool {
835    let mut pending: Vec<NodeRef<'_, Flm>> = paragraph.children().iter().collect();
836    while let Some(node) = pending.pop() {
837        if node.chars().is_some() || node.is_comment() {
838            continue;
839        }
840        if written_as_flow(&node) {
841            return true;
842        }
843        pending.extend(node.children().iter());
844    }
845    false
846}
847
848/// The values a heading's attributes are written from, block or run in: the
849/// anchor, the kind's name, the level (1 where the payload is missing) and
850/// whether the heading is in the table of contents, by payload field.
851fn heading_values(payload: Option<&HeadingPayload>) -> Vec<(&'static str, String)> {
852    let mut values: Vec<(&'static str, String)> = Vec::new();
853    if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
854        values.push(("anchor", anchor));
855    }
856    if let Some(payload) = payload {
857        values.push(("name", payload.name.to_string()));
858    }
859    values.push(("level", payload.map_or(1, |payload| payload.level).to_string()));
860    if let Some(payload) = payload {
861        values.push(("in_toc", payload.in_toc.to_string()));
862    }
863    values
864}
865
866/// The tag a heading `depth` levels below the root heading level is written
867/// with ([`heading_depth`]): `<h1>` at the root, `<h2>` to `<h6>` below it,
868/// `<h6>` for every deeper one.
869fn heading_tag(depth: u8) -> &'static str {
870    match depth {
871        0 => "h1",
872        1 => "h2",
873        2 => "h3",
874        3 => "h4",
875        4 => "h5",
876        _ => "h6",
877    }
878}
879
880/// The tag a span of `style` is written with. A style HTML has an element for
881/// gets that element; every other style, and a span with no style at all, gets
882/// `<span>` and is told apart by `data-flm-style`.
883fn span_tag(style: Option<SpanStyle>) -> &'static str {
884    match style {
885        Some(SpanStyle::Emphasis) => "em",
886        Some(SpanStyle::Bold) => "strong",
887        Some(SpanStyle::Italic) => "i",
888        Some(SpanStyle::Monospace) => "code",
889        Some(SpanStyle::Underline) => "u",
890        Some(SpanStyle::Superscript) => "sup",
891        Some(SpanStyle::Subscript) => "sub",
892        Some(SpanStyle::SmallCaps) | Some(SpanStyle::UnresolvedReference) | None => "span",
893    }
894}
895
896/// The first structural kind token among a list's kinds —
897/// [`LIST_NUMBERED`](pres::LIST_NUMBERED),
898/// [`LIST_UNNUMBERED`](pres::LIST_UNNUMBERED) or
899/// [`LIST_TERMS`](pres::LIST_TERMS) — and the tag it asks for: `<ol>`, `<ul>`
900/// or `<dl>`. A list whose kinds hold none of them is written `<ul>`.
901///
902/// The tag is chosen by what the list is, never by the name of the
903/// environment that produced it, so that a list environment a host adds is
904/// written as its structure says.
905fn list_tag(kinds: &[Name]) -> &'static str {
906    for kind in kinds {
907        match kind.as_str() {
908            pres::LIST_NUMBERED => return "ol",
909            pres::LIST_UNNUMBERED => return "ul",
910            pres::LIST_TERMS => return "dl",
911            _ => {}
912        }
913    }
914    "ul"
915}
916
917/// Whether the emitter writes `node` with a tag of **flow content**: a tag at
918/// whose start an HTML parser closes an open `<p>`, so that a `<p>` cannot
919/// hold it ([`holds_flow_content`]).
920///
921/// These are the emitter's own tag choices, element by element, kept beside
922/// the functions that make them:
923///
924/// - a paragraph (`<p>`, or a `<div>`), a block (every tag of [`block_tag`]),
925///   a block heading (a tag of [`heading_tag`], or the one a render option
926///   maps its kind to), a list (every tag of [`list_tag`]), a table of cells
927///   (`<table>`), a run of lines and each of its lines (`<div>`);
928/// - verbatim content as a block (`<pre>`) and an unattributed environment
929///   (`<div>`), but not their inline forms (`<code>`, `<span>`);
930/// - a placed tree, which the regions stage writes in the node's place after
931///   this emitter is done, so that what it holds is not known here;
932/// - an HTML tag construct node whose tag is one of [`CLOSES_A_PARAGRAPH`],
933///   the rule that staged it having chosen the tag.
934///
935/// Every other node is written as phrasing content (a `<span>` or the tag of
936/// a span's style, a link's `<a>`, an image's `<img>`, a formula's `<span>`,
937/// displayed or not) or as nothing of its own. A construct node's own
938/// `block` field is not read: it asks for line breaks around the tag, which a
939/// tag of phrasing content may want too (MathML's `<math display="block">`).
940fn written_as_flow(node: &NodeRef<'_, Flm>) -> bool {
941    match element_of(node).name.as_str() {
942        pres::PAR
943        | pres::BLOCK
944        | pres::BLOCK_HEADING
945        | pres::LIST
946        | pres::CELLS
947        | pres::LINES
948        | pres::LINE
949        | pres::SUBTREE => true,
950        pres::VERBATIM => payload_of::<VerbatimPayload>(node)
951            .is_some_and(|payload| payload.display == VerbatimDisplay::Block),
952        pres::UNKNOWN => payload_of::<UnknownPayload>(node)
953            .is_some_and(|payload| payload.kind == UnknownKind::Environment),
954        super::construct::TAG => payload_of::<HtmlTagPayload>(node).is_some_and(|payload| {
955            CLOSES_A_PARAGRAPH.iter().any(|tag| tag.eq_ignore_ascii_case(&payload.tag))
956        }),
957        _ => false,
958    }
959}
960
961/// The start tags at which an HTML parser closes an open `<p>`: the flow
962/// content a `<p>` cannot hold, as the HTML standard's parsing rules for the
963/// body of a page list it. An HTML tag construct node with one of these tags
964/// is written as flow content ([`written_as_flow`]).
965const CLOSES_A_PARAGRAPH: [&str; 41] = [
966    "address", "article", "aside", "blockquote", "center", "dd", "details", "dialog", "dir",
967    "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3",
968    "h4", "h5", "h6", "header", "hgroup", "hr", "li", "listing", "main", "menu", "nav", "ol", "p",
969    "plaintext", "pre", "search", "section", "summary", "table", "ul", "xmp",
970];
971
972/// The attributes of `row` for the values present, in the order the contract
973/// fixes: the element's own attributes in the row's order, then the `style`
974/// attribute holding the custom properties of the length fields and the
975/// ratios in the row's order, then the `data-flm-…` attributes in the row's order.
976///
977/// `values` holds the text of the fields the row writes as attributes, and
978/// `lengths` the value of the fields it writes as custom properties
979/// ([`Written::Style`]). This is the only writer of those properties: it
980/// spells each length as CSS ([`css_length`]) and writes nothing for a zero
981/// length, the stylesheet's fallback being zero, so an element whose lengths
982/// are all zero carries no `style` attribute. It writes the ratio of two of
983/// those lengths the same way ([`Written::Ratio`], [`css_ratio`]) where both
984/// are set and it has one.
985///
986/// A row lists the field that becomes `id` first, so `id` comes first among
987/// the element's own attributes, as the order requires.
988fn ordered_attributes(
989    convention: &Convention,
990    values: &[(&'static str, String)],
991    lengths: &[(&'static str, &Length)],
992) -> Vec<(String, String)> {
993    let mut own: Vec<(String, String)> = Vec::new();
994    let mut properties: Vec<String> = Vec::new();
995    let mut data: Vec<(String, String)> = Vec::new();
996    for field in convention.fields {
997        let length_of =
998            |wanted: &str| lengths.iter().find(|(name, _)| *name == wanted).map(|(_, length)| *length);
999        match field.written {
1000            Written::Style => {
1001                if let Some(length) = length_of(field.field).filter(|length| !length.is_zero()) {
1002                    properties
1003                        .push(format!("{}: {}", style_property(field.field), css_length(length)));
1004                }
1005                continue;
1006            }
1007            Written::Ratio(first, second) => {
1008                if let Some(ratio) = length_of(first)
1009                    .zip(length_of(second))
1010                    .and_then(|(first, second)| css_ratio(first, second))
1011                {
1012                    properties.push(format!("{}: {ratio}", style_property(field.field)));
1013                }
1014                continue;
1015            }
1016            _ => {}
1017        }
1018        let Some(value) = values.iter().find(|(name, _)| *name == field.field) else { continue };
1019        match field.written {
1020            Written::Own(attribute) => own.push((String::from(attribute), value.1.clone())),
1021            Written::Data(stem) => data.push((data_attribute(stem), value.1.clone())),
1022            Written::Style
1023            | Written::Ratio(..)
1024            | Written::RoleClass
1025            | Written::BlockClass
1026            | Written::Entry(_)
1027            | Written::EntryData(_)
1028            | Written::Dropped(_) => {}
1029        }
1030    }
1031    if !properties.is_empty() {
1032        own.push((String::from(STYLE_ATTRIBUTE), properties.join("; ")));
1033    }
1034    own.extend(data);
1035    own
1036}
1037
1038/// The attribute `row` writes its field `field` under on the element of each
1039/// entry of a list or each cell of a table of cells; `None` where the row
1040/// writes that field nowhere there.
1041fn entry_attribute(convention: &Convention, field: &str) -> Option<String> {
1042    convention.field(field).and_then(|field| field.entry_attribute())
1043}
1044
1045/// Where a lowered node is located in a source a host can name, by following the
1046/// chain of sources back from the node's own span: the source's canonical path
1047/// and the byte range in it.
1048///
1049/// A lowering rule stages its nodes on a source the library made for the
1050/// occasion, which points back at the node the rule fired at; walking those
1051/// back-references leads to the document. `None` when the chain reaches no
1052/// source with a canonical path — content the library made that stands for
1053/// nothing a document holds, or a fragment a host parsed without naming it.
1054fn source_position(span: &FlmSpan) -> Option<(String, Range<usize>)> {
1055    let mut span = span.clone();
1056    loop {
1057        if let Some(path) = span.source().origin().canonical_path() {
1058            return Some((String::from(path), span.range()));
1059        }
1060        let triggered = span.source().provenance().triggered_at()?.clone();
1061        span = triggered;
1062    }
1063}
1064
1065/// The attribute that says where an element is located in its source.
1066///
1067/// It is the only attribute of this backend whose value is JSON, so it is the
1068/// only one written through [`TagBuilder::attr_json`](super::TagBuilder::attr_json),
1069/// in single quotation marks. The name is spelled out here because every
1070/// element written is checked against it; a unit test holds it to
1071/// [`data_attribute`], the function that derives it.
1072const SOURCE_SPAN_ATTRIBUTE: &str = "data-flm-source-span";
1073
1074/// The value of the attribute that says where an element is located in its
1075/// source: a JSON array of three items — the source's name as a JSON
1076/// string, the first byte of the range, and the byte just past its end.
1077///
1078/// The value is JSON so that a script reading it needs no parsing of its own,
1079/// and the sink writes it between single quotation marks, so the raw page
1080/// shows it as JSON.
1081fn source_span_value(source: &str, range: &Range<usize>) -> String {
1082    let mut value = String::from("[");
1083    json_string_into(&mut value, source);
1084    value.push(',');
1085    value.push_str(&range.start.to_string());
1086    value.push(',');
1087    value.push_str(&range.end.to_string());
1088    value.push(']');
1089    value
1090}
1091
1092/// The rendering model of one cell of a table of cells: what the emitter
1093/// writes for it, filled from the cell's entry of the payload
1094/// ([`Emitter::cell_rendering`]) and then written ([`Emitter::cell`]).
1095///
1096/// The only place where a cell's facts become HTML, so that how a cell is written
1097/// can be changed in one place.
1098// A seam that could be put behind a trait a host implements, to let a host
1099// change how a cell is written; nothing of it is public.
1100#[derive(Debug, Clone, PartialEq, Eq)]
1101struct CellRendering {
1102    /// `td`, or `th` for a header cell.
1103    tag: &'static str,
1104    /// The `scope` of a header cell: `col` for a column header, `row` for a
1105    /// row header.
1106    scope: Option<&'static str>,
1107    /// The number of columns the cell spans, where it is not one.
1108    colspan: Option<u32>,
1109    /// The number of rows the cell spans, where it is not one.
1110    rowspan: Option<u32>,
1111    /// The cell's other attributes, in the row's order: its alignment, the
1112    /// edges it has a rule at, one attribute per custom style it carries.
1113    attributes: Vec<(String, String)>,
1114}
1115
1116impl CellRendering {
1117    /// An empty position of the grid: an empty `<td>`.
1118    fn empty() -> CellRendering {
1119        CellRendering { tag: "td", scope: None, colspan: None, rowspan: None, attributes: Vec::new() }
1120    }
1121}
1122
1123impl<'o> Emitter<'o> {
1124    /// Opens one level of the walk; `false`, with the refusal recorded, past
1125    /// the depth limit.
1126    fn descend(&mut self) -> bool {
1127        if self.depth >= DEPTH_LIMIT {
1128            self.refused = true;
1129            return false;
1130        }
1131        self.depth += 1;
1132        true
1133    }
1134
1135    /// Closes one level of the walk.
1136    fn ascend(&mut self) {
1137        self.depth -= 1;
1138    }
1139
1140    /// Records that the tree's HTML requires the definition `identifier`.
1141    fn require(&mut self, identifier: &str) {
1142        self.requires.insert(Name::from(identifier));
1143    }
1144
1145    /// Reports an internal invariant broken at `node`: an element this backend
1146    /// neither claims nor expects reached the emitter.
1147    fn unexpected(&mut self, node: &NodeRef<'_, Flm>) {
1148        self.diags.push(Diagnostic::error(
1149            StageFailed {
1150                stage: String::from(super::stages::EMIT_STAGE),
1151                detail: format!(
1152                    "the element `{}` reached the HTML emitter, which cannot write it",
1153                    element_of(node).name
1154                ),
1155            },
1156            node.span().clone(),
1157        ));
1158    }
1159
1160    // --- writing one element ---------------------------------------------------------------
1161
1162    /// Opens an element for `node`: its classes, the attributes the row asks
1163    /// for, and — under the option that asks for them — where the node is
1164    /// located in its source.
1165    fn open(
1166        &mut self,
1167        node: Option<&NodeRef<'_, Flm>>,
1168        tag: &str,
1169        block: bool,
1170        classes: &[String],
1171        attributes: Vec<(String, String)>,
1172        preformatted: bool,
1173    ) {
1174        let attributes = self.with_source_span(node, attributes);
1175        let attributes = self.writable_in_math(node, attributes);
1176        let with_class = !classes.is_empty() && self.class_writable_in_math(node, classes);
1177        let classes: Vec<String> = if with_class { classes.to_vec() } else { Vec::new() };
1178        self.write_open(OpenInMath {
1179            tag: String::from(tag),
1180            block,
1181            classes,
1182            attributes,
1183            preformatted,
1184        });
1185    }
1186
1187    /// Opens `element` on the sink and, inside the HTML written into a
1188    /// formula, records it as open there.
1189    ///
1190    /// Every element the emitter opens goes through here, so that a formula
1191    /// placed deeper inside that HTML can close what is open and open it
1192    /// again ([`math_text`](Emitter::math_text)). The element is written
1193    /// exactly as it is given: the checks an element's attributes and classes
1194    /// pass ([`writable_in_math`](Emitter::writable_in_math)) are the caller's,
1195    /// and are not made a second time when the same element is opened again.
1196    fn write_open(&mut self, element: OpenInMath) {
1197        let mut builder = if element.block {
1198            self.sink.open_block(&element.tag)
1199        } else {
1200            self.sink.open_inline(&element.tag)
1201        };
1202        if !element.classes.is_empty() {
1203            builder = builder.class(&element.classes);
1204        }
1205        // The one attribute whose value is JSON is picked out by its name.
1206        // Both branches escape, each for the quotation mark it writes between,
1207        // so a name that did not match would still reach the page as a valid
1208        // attribute; the spelling decides how the value looks, not whether it
1209        // is safe.
1210        for (name, value) in &element.attributes {
1211            builder = if name == SOURCE_SPAN_ATTRIBUTE {
1212                builder.attr_json(name, value)
1213            } else {
1214                builder.attr(name, value)
1215            };
1216        }
1217        if element.preformatted {
1218            builder = builder.preformatted();
1219        }
1220        builder.finish();
1221        if self.in_tex_html {
1222            if let Some(piece) = self.piece.as_mut() {
1223                // An identifier may stand once in a page, so the second half
1224                // of an element written around a formula carries none; the
1225                // source position stands once per node too, on the element's
1226                // first half, so it goes the same way.
1227                let mut element = element;
1228                element
1229                    .attributes
1230                    .retain(|(name, _)| name != "id" && name != SOURCE_SPAN_ATTRIBUTE);
1231                piece.open.push(element);
1232            }
1233        }
1234    }
1235
1236    /// Closes an element opened through [`open`](Emitter::open) or
1237    /// [`write_open`](Emitter::write_open).
1238    ///
1239    /// Inside the HTML written into a formula this is also what takes the
1240    /// element off the list of those open there, so the two must stay
1241    /// paired: an element opened through those two is closed through this one
1242    /// and through no other. A debug assertion holds the pair together —
1243    /// the element taken off the list must be the one the sink is about to
1244    /// close — so that an arm closing an element inside a formula by another
1245    /// route fails a test run instead of quietly reopening the wrong element
1246    /// around a deeper formula.
1247    fn close(&mut self) {
1248        if self.in_tex_html {
1249            if let Some(piece) = self.piece.as_mut() {
1250                let popped = piece.open.pop();
1251                debug_assert_eq!(
1252                    popped.as_ref().map(|element| element.tag.as_str()),
1253                    self.sink.open_tag(),
1254                    "an element inside a formula was opened or closed \
1255                     without going through the emitter's own pair"
1256                );
1257            }
1258        }
1259        self.sink.close();
1260    }
1261
1262    /// `attributes` with the source-position attribute added when the option
1263    /// asks for it and `node` is located in a source a host can name.
1264    ///
1265    /// Every element written for a presentation node carries it, inline or
1266    /// block alike; an element that stands for no node of its own is written
1267    /// with `node` as `None` and carries none.
1268    fn with_source_span(
1269        &self,
1270        node: Option<&NodeRef<'_, Flm>>,
1271        attributes: Vec<(String, String)>,
1272    ) -> Vec<(String, String)> {
1273        let mut attributes = attributes;
1274        if self.options.source_spans {
1275            if let Some((source, range)) = node.and_then(|node| source_position(node.span())) {
1276                attributes.push((
1277                    String::from(SOURCE_SPAN_ATTRIBUTE),
1278                    source_span_value(&source, &range),
1279                ));
1280            }
1281        }
1282        attributes
1283    }
1284
1285    /// Writes an element that has no content and is never closed (`<img>`).
1286    fn void(
1287        &mut self,
1288        node: Option<&NodeRef<'_, Flm>>,
1289        tag: &str,
1290        classes: &[String],
1291        attributes: Vec<(String, String)>,
1292    ) {
1293        let attributes = self.with_source_span(node, attributes);
1294        let attributes = self.writable_in_math(node, attributes);
1295        let with_class = !classes.is_empty() && self.class_writable_in_math(node, classes);
1296        let mut builder = self.sink.void_inline(tag);
1297        if with_class {
1298            builder = builder.class(classes);
1299        }
1300        // The one attribute whose value is JSON is picked out by its name,
1301        // exactly as [`write_open`](Emitter::write_open) picks it out.
1302        for (name, value) in &attributes {
1303            builder = if name == SOURCE_SPAN_ATTRIBUTE {
1304                builder.attr_json(name, value)
1305            } else {
1306                builder.attr(name, value)
1307            };
1308        }
1309        builder.finish();
1310    }
1311
1312    // --- writing inside a formula -----------------------------------------------------------
1313
1314    /// `attributes` with every value left out that cannot be written where
1315    /// this element is being written, which is only ever inside the HTML of a
1316    /// `<tex-html>`; each one left out is reported.
1317    ///
1318    /// Outside a formula every attribute is writable and the list comes back
1319    /// as it went in.
1320    fn writable_in_math(
1321        &mut self,
1322        node: Option<&NodeRef<'_, Flm>>,
1323        attributes: Vec<(String, String)>,
1324    ) -> Vec<(String, String)> {
1325        if !self.in_tex_html {
1326            return attributes;
1327        }
1328        let Some(sequences) = self.math.as_ref().map(|math| Arc::clone(&math.sequences)) else {
1329            return attributes;
1330        };
1331        let mut written = Vec::with_capacity(attributes.len());
1332        for (name, value) in attributes {
1333            match refused_sequence(&value, &sequences) {
1334                Some(sequence) => self.refused_in_math(node, &name, &sequence),
1335                None => written.push((name, value)),
1336            }
1337        }
1338        written
1339    }
1340
1341    /// Whether the `class` attribute built from `classes` may be written
1342    /// where this element is being written, reporting it when it may not.
1343    ///
1344    /// A class is derived from an element's name or from a role's, and a role
1345    /// is a name a lowering rule wrote, so a class holding one of the
1346    /// sequences is a mistake in a feature rather than in a document. The
1347    /// whole attribute is left out, as any other refused one is.
1348    fn class_writable_in_math(
1349        &mut self,
1350        node: Option<&NodeRef<'_, Flm>>,
1351        classes: &[String],
1352    ) -> bool {
1353        if !self.in_tex_html {
1354            return true;
1355        }
1356        let attribute = vec![(String::from("class"), classes.join(" "))];
1357        !self.writable_in_math(node, attribute).is_empty()
1358    }
1359
1360    /// Reports [`RefusedInMath`] at `node`, or at the formula being written
1361    /// when the refused element belongs to no node of its own.
1362    ///
1363    /// The severity is an Error: what the page shows is not what the document
1364    /// asked for, even though the element and its content are kept, which is
1365    /// how this backend reports every refusal of something a document asked
1366    /// for.
1367    fn refused_in_math(
1368        &mut self,
1369        node: Option<&NodeRef<'_, Flm>>,
1370        attribute: &str,
1371        sequence: &str,
1372    ) {
1373        let span = match node {
1374            Some(node) => node.span().clone(),
1375            None => match self.math.as_ref() {
1376                Some(math) => math.span.clone(),
1377                None => nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
1378            },
1379        };
1380        self.diags.push(Diagnostic::error(
1381            RefusedInMath {
1382                attribute: String::from(attribute),
1383                sequence: String::from(sequence),
1384            },
1385            span,
1386        ));
1387    }
1388
1389    /// Writes document text through the sink, repaired where it is written inside
1390    /// the HTML of a `<tex-html>`, the emitter's own inside a passthrough
1391    /// formula or a `tex-html` construct a rule staged: an empty
1392    /// `<span></span>` is written wherever a sequence would otherwise end the
1393    /// formula early ([`break_points`]).
1394    fn write_text(&mut self, text: &str) {
1395        let in_math = match (self.in_tex_html, self.math.as_ref()) {
1396            (true, Some(math)) => Some(Arc::clone(&math.sequences)),
1397            _ => None,
1398        };
1399        let in_construct = (self.tex_html_constructs > 0).then(|| Arc::clone(&self.construct_sequences));
1400        // The set that applies, shared where only one does; the two merged,
1401        // the formula's first, where both do.
1402        let sequences: Arc<[Sequence]> = match (in_math, in_construct) {
1403            (None, None) => {
1404                self.sink.text(text);
1405                return;
1406            }
1407            (Some(sequences), None) | (None, Some(sequences)) => sequences,
1408            (Some(math), Some(construct)) => math.iter().chain(construct.iter()).cloned().collect(),
1409        };
1410        let mut at = 0;
1411        for point in break_points(text, &sequences) {
1412            self.sink.text(&text[at..point]);
1413            // The empty element written into a sequence is syntax of the
1414            // repair, not an element of the page's structure: it opens and
1415            // closes here, so it never stands open and is never recorded
1416            // among the elements a deeper formula closes and opens again.
1417            self.sink.open_inline("span").finish();
1418            self.sink.close();
1419            at = point;
1420        }
1421        self.sink.text(&text[at..]);
1422    }
1423
1424    /// Writes characters into the formula itself — a delimiter the emitter
1425    /// chose, or a document's own mathematics source — with the tag that puts
1426    /// HTML inside a formula neutralized ([`neutralized_source`]).
1427    fn write_math_source(&mut self, source: &str) {
1428        let neutralized = neutralized_source(source);
1429        self.sink.text(&neutralized);
1430    }
1431
1432    /// The classes of a node: the element's own, then the role's when the row
1433    /// says the payload carries one and the payload does.
1434    ///
1435    /// A role that is not one token is left out and reported: the `class`
1436    /// attribute separates its classes by whitespace, so a role holding
1437    /// whitespace would add classes that represent nothing.
1438    fn classes(
1439        &mut self,
1440        node: &NodeRef<'_, Flm>,
1441        convention: &Convention,
1442        role: Option<&Name>,
1443    ) -> Vec<String> {
1444        let mut classes = vec![class_of_element(convention.element)];
1445        if convention.has_role() {
1446            if let Some(role) = role {
1447                if is_valid_token(role.as_str()) {
1448                    classes.push(class_of_role(role.as_str()));
1449                } else {
1450                    self.refused_name(
1451                        node,
1452                        "role",
1453                        role.as_str(),
1454                        "the class the role would have added was left out",
1455                    );
1456                }
1457            }
1458        }
1459        classes
1460    }
1461
1462    /// The names of `kinds` as the whitespace-separated token list a
1463    /// `data-flm-kind` attribute holds; `None` when nothing is left to write,
1464    /// in which case the caller writes no attribute at all.
1465    ///
1466    /// A name that is not one token is left out and reported, for the reason a
1467    /// role is ([`classes`](Emitter::classes)). The same walk serves a payload
1468    /// holding a list of kinds and one holding a single kind, which are written
1469    /// under the same attribute; a payload holding a single kind therefore
1470    /// loses the whole attribute when that one name is refused, and the report
1471    /// says so.
1472    fn kind_tokens(&mut self, node: &NodeRef<'_, Flm>, kinds: &[Name]) -> Option<String> {
1473        let mut tokens: Vec<&str> = Vec::new();
1474        let mut refused: Vec<&str> = Vec::new();
1475        for kind in kinds {
1476            if is_valid_token(kind.as_str()) {
1477                tokens.push(kind.as_str());
1478            } else {
1479                refused.push(kind.as_str());
1480            }
1481        }
1482        let written = (!tokens.is_empty()).then(|| tokens.join(" "));
1483        // What a refusal costs depends on what is left: the attribute holds
1484        // the names that passed, and is not written at all when none did.
1485        let recovery = if written.is_some() {
1486            "the token was left out of the `data-flm-kind` attribute"
1487        } else {
1488            "the `data-flm-kind` attribute was not written"
1489        };
1490        for name in refused {
1491            self.refused_name(node, "kind", name, recovery);
1492        }
1493        written
1494    }
1495
1496    /// Reports `flm.html.invalid-name` for a name the emitter would have
1497    /// written at `node` and could not.
1498    fn refused_name(
1499        &mut self,
1500        node: &NodeRef<'_, Flm>,
1501        what: &str,
1502        name: &str,
1503        recovery: &str,
1504    ) {
1505        self.diags.push(Diagnostic::error(
1506            InvalidName {
1507                what: String::from(what),
1508                name: String::from(name),
1509                recovery: String::from(recovery),
1510            },
1511            node.span().clone(),
1512        ));
1513    }
1514
1515    // --- the walk ---------------------------------------------------------------------------
1516
1517    /// A run of sibling nodes, in order.
1518    ///
1519    /// `carrier` is the presentation node whose content run this is, which is
1520    /// what a decoration mark resolves its decoration against.
1521    fn run(&mut self, carrier: Option<&NodeRef<'_, Flm>>, nodes: &[NodeRef<'_, Flm>]) {
1522        for node in nodes {
1523            if !self.descend() {
1524                return;
1525            }
1526            self.node(carrier, node);
1527            self.ascend();
1528        }
1529    }
1530
1531    /// One node.
1532    fn node(&mut self, carrier: Option<&NodeRef<'_, Flm>>, node: &NodeRef<'_, Flm>) {
1533        if let Some(text) = node.chars() {
1534            self.write_text(text);
1535            return;
1536        }
1537        if node.is_comment() {
1538            // A comment is dropped: an HTML comment would let document text
1539            // close it, and nothing in the page shows it.
1540            return;
1541        }
1542        if is_element(node, structural::PARBREAK) {
1543            // A paragraph break separates blocks, and block-level elements
1544            // separate themselves: nothing is written for it.
1545            return;
1546        }
1547        if !is_presentation(node) {
1548            // A group, a container, a text node's wrapper: its children, and
1549            // nothing of its own.
1550            let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
1551            self.run(Some(node), &children);
1552            return;
1553        }
1554        let name = element_of(node).name.clone();
1555        if name == super::construct::TAG {
1556            self.construct(node);
1557            return;
1558        }
1559        let Some(convention) = row(name.as_str()) else {
1560            self.unexpected(node);
1561            return;
1562        };
1563        match name.as_str() {
1564            pres::PAR => self.par(node, convention),
1565            pres::BLOCK => self.block(node, convention),
1566            pres::BLOCK_HEADING => self.heading(node, convention),
1567            pres::RUNIN_HEADING => self.runin_heading(node, convention),
1568            pres::SPAN => self.span(node, convention),
1569            pres::LIST => self.list(node, convention),
1570            pres::CELLS => self.cells(node, convention),
1571            pres::LINES => self.lines(node, convention),
1572            pres::LINE => self.line(node, convention),
1573            pres::VERBATIM => self.verbatim(node, convention),
1574            pres::MATH_PASSTHROUGH => self.math_passthrough(node, convention),
1575            pres::MATH_TEXT => self.math_text(node, convention),
1576            pres::LINK => self.link(node, convention),
1577            pres::IMAGE => self.image(node, convention),
1578            pres::UNSUPPORTED => self.unsupported(node),
1579            pres::DROPPED => self.dropped(node, convention),
1580            pres::UNKNOWN => self.unknown(node, convention),
1581            pres::DECO_RUNIN | pres::DECO_FINAL | pres::DECO_MARGIN => {
1582                self.decoration(node, convention)
1583            }
1584            pres::DECO_MARK => self.deco_mark(carrier, node),
1585            pres::SUBTREE => self.subtree(node),
1586            _ => self.unexpected(node),
1587        }
1588    }
1589
1590    /// A `flm.pres.par`: a `<p>` around its content, or a `<div>` carrying
1591    /// `role="paragraph"` when the paragraph holds flow content
1592    /// ([`holds_flow_content`]); nothing at all for a paragraph that carries
1593    /// no anchor and whose content shows nothing ([`shows_nothing`]).
1594    fn par(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
1595        let payload = payload_of::<ParPayload>(node);
1596        let anchor = payload.and_then(|payload| payload.anchor.clone());
1597        let content = body(node);
1598        if anchor.is_none() && shows_nothing(&content) {
1599            return;
1600        }
1601        self.require_style(convention);
1602        let mut values: Vec<(&'static str, String)> = Vec::new();
1603        if let Some(anchor) = anchor {
1604            values.push(("anchor", anchor));
1605        }
1606        let classes = self.classes(node, convention, None);
1607        let mut attributes = ordered_attributes(convention, &values, &[]);
1608        // HTML allows only phrasing content inside a `<p>`: a parser closes an
1609        // open `<p>` at the start tag of a `<div>`, a `<ul>`, a `<table>`, a
1610        // `<pre>`, a heading or another `<p>`, wherever that tag is nested, and
1611        // the rest of the paragraph then stands outside it. A paragraph may
1612        // nevertheless hold flow content: a displayed item may hold anything,
1613        // its own rule laying its content out, and nothing in the tree says
1614        // what is shown inside it. This is a limitation of HTML alone, so it is
1615        // met here, per paragraph, and no element has to know of it: the
1616        // paragraph is a `<div>` when it holds flow content and a `<p>`
1617        // everywhere else. The class and the anchor are the same either way,
1618        // and the HTML contract does not promise the tag; the accessibility
1619        // role says of the `<div>` what the `<p>` would have said. A `<div>`
1620        // for every paragraph would give up the `<p>` wherever HTML allows
1621        // one, which is every paragraph the standard features write; a
1622        // paragraph split into several `<p>` around the flow content would
1623        // give a paragraph two shapes, and need a mark on each part saying
1624        // which paragraph it continues; and a check or a report of flow
1625        // content inside a paragraph would forbid what a displayed item may
1626        // hold.
1627        let flow = holds_flow_content(node);
1628        if flow {
1629            // The row writes `id` alone, so the role follows it, among the
1630            // element's own attributes.
1631            attributes.push((String::from("role"), String::from(PARAGRAPH_ROLE)));
1632        }
1633        let tag = if flow { PARAGRAPH_FLOW_TAG } else { "p" };
1634        self.open(Some(node), tag, true, &classes, attributes, false);
1635        self.run(Some(node), &content);
1636        self.close();
1637    }
1638
1639    /// A `flm.pres.block`: the tag its role maps to ([`block_tag`], a `<div>`
1640    /// for every role the table does not name) with the role's class, around
1641    /// its blocks.
1642    fn block(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
1643        self.require_style(convention);
1644        let payload = payload_of::<BlockPayload>(node);
1645        let mut values: Vec<(&'static str, String)> = Vec::new();
1646        if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
1647            values.push(("anchor", anchor));
1648        }
1649        if let Some(role) = payload.and_then(|payload| payload.doc_role) {
1650            values.push(("doc_role", doc_role_value(role)));
1651        }
1652        let kinds = payload.map(|payload| payload.kinds.clone()).unwrap_or_default();
1653        if let Some(kinds) = self.kind_tokens(node, &kinds) {
1654            values.push(("kinds", kinds));
1655        }
1656        let role = payload.and_then(|payload| payload.role.as_ref());
1657        let tag = block_tag(role.map(Name::as_str));
1658        let classes = self.classes(node, convention, role);
1659        self.open(
1660            Some(node),
1661            tag,
1662            true,
1663            &classes,
1664            ordered_attributes(convention, &values, &[]),
1665            false,
1666        );
1667        let content = body(node);
1668        self.run(Some(node), &content);
1669        self.close();
1670    }
1671
1672    /// A `flm.pres.block-heading`: the tag the render options map the
1673    /// heading kind to ([`HtmlRenderOptions::heading_tags`]), else `<h1>` to
1674    /// `<h6>` by its level counted from the root heading level
1675    /// ([`HtmlRenderOptions::root_heading_level`]), with the kind's name, the
1676    /// true level and whether the heading is in the table of contents in
1677    /// `data-flm-heading`, `data-flm-level` and `data-flm-toc` regardless of
1678    /// the tag. A heading above the root is reported regardless of its tag, and one
1679    /// with no mapped tag is written `<h1>`.
1680    fn heading(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
1681        self.require_style(convention);
1682        let payload = payload_of::<HeadingPayload>(node);
1683        let level = payload.map_or(self.options.root_heading_level, |payload| payload.level);
1684        let values = heading_values(payload);
1685        let depth = match heading_depth(level, self.options.root_heading_level) {
1686            Ok(depth) => depth,
1687            Err(above) => {
1688                self.diags.push(Diagnostic::error(above, node.span().clone()));
1689                0
1690            }
1691        };
1692        // A mapped tag is the host's text, so it is checked before it is
1693        // written; one that is not writable falls back to the level's tag.
1694        let mapped = payload.and_then(|payload| self.options.heading_tags.get(&payload.name));
1695        let tag = match mapped {
1696            Some(tag) if is_valid_tag_name(tag) => tag.clone(),
1697            Some(tag) => {
1698                self.diags.push(Diagnostic::error(
1699                    InvalidName {
1700                        what: String::from("tag"),
1701                        name: tag.clone(),
1702                        recovery: String::from("the heading was written with the tag of its level"),
1703                    },
1704                    node.span().clone(),
1705                ));
1706                heading_tag(depth).to_string()
1707            }
1708            None => heading_tag(depth).to_string(),
1709        };
1710        let classes = self.classes(node, convention, None);
1711        self.open(
1712            Some(node),
1713            &tag,
1714            true,
1715            &classes,
1716            ordered_attributes(convention, &values, &[]),
1717            false,
1718        );
1719        let content = body(node);
1720        self.run(Some(node), &content);
1721        self.close();
1722    }
1723
1724    /// A `flm.pres.runin-heading`: a `<span>` carrying the same attributes
1725    /// as a block heading — the anchor as `id`, then `data-flm-heading`,
1726    /// `data-flm-level` and `data-flm-toc` — around the title. The run-in
1727    /// decoration it is in writes the stop after it.
1728    fn runin_heading(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
1729        self.require_style(convention);
1730        let values = heading_values(payload_of::<HeadingPayload>(node));
1731        let classes = self.classes(node, convention, None);
1732        self.open(
1733            Some(node),
1734            "span",
1735            false,
1736            &classes,
1737            ordered_attributes(convention, &values, &[]),
1738            false,
1739        );
1740        let content = body(node);
1741        self.run(Some(node), &content);
1742        self.close();
1743    }
1744
1745    /// A `flm.pres.span`: the element HTML has for its style, or a `<span>`.
1746    fn span(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
1747        self.require_style(convention);
1748        let payload = payload_of::<SpanPayload>(node);
1749        let style = payload.and_then(|payload| payload.style);
1750        let mut values: Vec<(&'static str, String)> = Vec::new();
1751        if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
1752            values.push(("anchor", anchor));
1753        }
1754        if let Some(role) = payload.and_then(|payload| payload.doc_role) {
1755            values.push(("doc_role", doc_role_value(role)));
1756        }
1757        if let Some(style) = style {
1758            values.push(("style", String::from(style.as_str())));
1759        }
1760        let kinds = payload.map(|payload| payload.kinds.clone()).unwrap_or_default();
1761        if let Some(kinds) = self.kind_tokens(node, &kinds) {
1762            values.push(("kinds", kinds));
1763        }
1764        let classes = self.classes(node, convention, payload.and_then(|payload| payload.role.as_ref()));
1765        self.open(
1766            Some(node),
1767            span_tag(style),
1768            false,
1769            &classes,
1770            ordered_attributes(convention, &values, &[]),
1771            false,
1772        );
1773        let content = body(node);
1774        self.run(Some(node), &content);
1775        self.close();
1776    }
1777
1778    /// A `flm.pres.list`: `<ol>`, `<ul>` or `<dl>` by kind, one entry each,
1779    /// each entry's element carrying that entry's anchor as its identifier
1780    /// and that entry's level, when it has one.
1781    fn list(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
1782        self.require_style(convention);
1783        let payload = payload_of::<ListPayload>(node);
1784        let kinds: Vec<Name> = payload.map(|payload| payload.kinds.clone()).unwrap_or_default();
1785        let entry_anchors: Vec<Option<String>> =
1786            payload.map(|payload| payload.entry_anchors.clone()).unwrap_or_default();
1787        let entry_levels: Vec<Option<u32>> =
1788            payload.map(|payload| payload.entry_levels.clone()).unwrap_or_default();
1789        let tag = list_tag(&kinds);
1790        let mut values: Vec<(&'static str, String)> = Vec::new();
1791        if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
1792            values.push(("anchor", anchor));
1793        }
1794        if let Some(tokens) = self.kind_tokens(node, &kinds) {
1795            values.push(("kinds", tokens));
1796        }
1797        let classes = self.classes(node, convention, None);
1798        self.open(Some(node), tag, true, &classes, ordered_attributes(convention, &values, &[]), false);
1799        // A description list's only valid children are `<dt>` and `<dd>`, so a
1800        // label is a `<dt>` carrying the class a rich label carries elsewhere.
1801        let description = tag == "dl";
1802        for (index, (label, item)) in list_entries(node).into_iter().enumerate() {
1803            let label: Vec<NodeRef<'_, Flm>> = label.iter().collect();
1804            let item: Vec<NodeRef<'_, Flm>> = item.iter().collect();
1805            let label_class = [String::from(LIST_LABEL_CLASS)];
1806            // An entry's anchor is the identifier of the element that begins
1807            // the entry: its `<li>`, or a description list's `<dt>`, which is
1808            // what a link to the entry lands on. Its level is written on the
1809            // same element.
1810            let mut attributes: Vec<(String, String)> = Vec::new();
1811            if let (Some(attribute), Some(Some(anchor))) =
1812                (entry_attribute(convention, "entry_anchors"), entry_anchors.get(index))
1813            {
1814                attributes.push((attribute, anchor.clone()));
1815            }
1816            if let (Some(attribute), Some(Some(level))) =
1817                (entry_attribute(convention, "entry_levels"), entry_levels.get(index))
1818            {
1819                attributes.push((attribute, level.to_string()));
1820            }
1821            if description {
1822                self.open(None, "dt", true, &label_class, attributes, false);
1823                self.run(Some(node), &label);
1824                self.close();
1825                self.open(None, "dd", true, &[], Vec::new(), false);
1826                self.run(Some(node), &item);
1827                self.close();
1828            } else {
1829                self.open(None, "li", true, &[], attributes, false);
1830                if !label.is_empty() {
1831                    self.open(None, "span", false, &label_class, Vec::new(), false);
1832                    self.run(Some(node), &label);
1833                    self.close();
1834                }
1835                self.run(Some(node), &item);
1836                self.close();
1837            }
1838        }
1839        self.close();
1840    }
1841
1842    /// A `flm.pres.cells`: a `<table>` holding one `<tr>` per row of the
1843    /// grid ([`CellsPayload::grid`](pres::CellsPayload::grid)), and in it one
1844    /// element per position no span covers: a cell at its top-left position,
1845    /// written from its rendering model ([`CellRendering`]) around its `cell`
1846    /// slot's blocks, and an empty `<td>` where no cell is placed. Nothing is
1847    /// written for a position a span covers; the spanning cell's `colspan` and
1848    /// `rowspan` account for it.
1849    ///
1850    /// The table carries the element's class and nothing of the grid: its
1851    /// size is its shape. No `<thead>` or `<tbody>` is written, HTML implying
1852    /// the body. A node carrying no payload is an empty table.
1853    fn cells(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
1854        self.require_style(convention);
1855        let classes = self.classes(node, convention, None);
1856        self.open(Some(node), "table", true, &classes, Vec::new(), false);
1857        if let Some((payload, contents)) = cells_of(node) {
1858            for row in payload.grid() {
1859                self.open(None, "tr", true, &[], Vec::new(), false);
1860                for position in row {
1861                    match position {
1862                        GridPosition::Empty => {
1863                            self.cell(node, convention, &CellRendering::empty(), &[]);
1864                        }
1865                        GridPosition::TopLeft(index) => {
1866                            let rendering = self.cell_rendering(node, convention, &payload.cells[index]);
1867                            let content: Vec<NodeRef<'_, Flm>> = contents
1868                                .get(index)
1869                                .and_then(|slice| slice.as_ref())
1870                                .map(|slice| slice.iter().collect())
1871                                .unwrap_or_default();
1872                            self.cell(node, convention, &rendering, &content);
1873                        }
1874                        GridPosition::Covered(_) => {}
1875                    }
1876                }
1877                self.close();
1878            }
1879        }
1880        self.close();
1881    }
1882
1883    /// The rendering model of the cell `spec` of the table `node`: its tag,
1884    /// its `scope`, its spans and its facts as the attributes the row writes
1885    /// on each cell ([`Written::EntryData`]).
1886    ///
1887    /// A custom style whose name cannot end an attribute name is left out and
1888    /// reported as `flm.html.invalid-name`, as a role or a kind is
1889    /// ([`classes`](Emitter::classes)).
1890    fn cell_rendering(
1891        &mut self,
1892        node: &NodeRef<'_, Flm>,
1893        convention: &Convention,
1894        spec: &CellSpec,
1895    ) -> CellRendering {
1896        let mut attributes: Vec<(String, String)> = Vec::new();
1897        if let (Some(attribute), Some(align)) = (entry_attribute(convention, "align"), spec.align) {
1898            attributes.push((attribute, String::from(align.as_str())));
1899        }
1900        if let Some(attribute) = entry_attribute(convention, "rules").filter(|_| !spec.rules.is_empty()) {
1901            let edges: Vec<&str> = spec.rules.iter().map(|edge| edge.as_str()).collect();
1902            attributes.push((attribute, edges.join(" ")));
1903        }
1904        if let Some(family) = entry_attribute(convention, "styles") {
1905            for style in &spec.styles {
1906                let attribute = format!("{family}{style}");
1907                if is_valid_attribute_name(&attribute) {
1908                    attributes.push((attribute, String::new()));
1909                } else {
1910                    self.refused_name(
1911                        node,
1912                        "attribute",
1913                        &attribute,
1914                        "the attribute of the custom style was left out",
1915                    );
1916                }
1917            }
1918        }
1919        CellRendering {
1920            tag: if spec.header.is_some() { "th" } else { "td" },
1921            scope: spec.header.map(|header| match header {
1922                CellHeader::Column => "col",
1923                CellHeader::Row => "row",
1924            }),
1925            colspan: (spec.col_span != 1).then_some(spec.col_span),
1926            rowspan: (spec.row_span != 1).then_some(spec.row_span),
1927            attributes,
1928        }
1929    }
1930
1931    /// Writes one cell of the table `node` from its rendering model, around
1932    /// `content`: the element's own attributes in the row's order, then the
1933    /// `data-flm-…` ones.
1934    fn cell(
1935        &mut self,
1936        node: &NodeRef<'_, Flm>,
1937        convention: &Convention,
1938        rendering: &CellRendering,
1939        content: &[NodeRef<'_, Flm>],
1940    ) {
1941        let mut attributes: Vec<(String, String)> = Vec::new();
1942        for field in convention.fields {
1943            let value = match field.field {
1944                "row_span" => rendering.rowspan.map(|span| span.to_string()),
1945                "col_span" => rendering.colspan.map(|span| span.to_string()),
1946                "header" => rendering.scope.map(String::from),
1947                _ => None,
1948            };
1949            if let (Some(attribute), Some(value)) = (field.entry_attribute(), value) {
1950                attributes.push((attribute, value));
1951            }
1952        }
1953        attributes.extend(rendering.attributes.iter().cloned());
1954        self.open(None, rendering.tag, true, &[], attributes, false);
1955        self.run(Some(node), content);
1956        self.close();
1957    }
1958
1959    /// A `flm.pres.lines`: a `<div>` holding one `<div>` per line.
1960    fn lines(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
1961        self.require_style(convention);
1962        let classes = self.classes(node, convention, None);
1963        self.open(Some(node), "div", true, &classes, Vec::new(), false);
1964        let content = body(node);
1965        self.run(Some(node), &content);
1966        self.close();
1967    }
1968
1969    /// A `flm.pres.line`: one `<div>` carrying its alignment, and its
1970    /// indentation from the left and from the right as the custom properties
1971    /// of its `style` attribute, a zero indentation writing nothing
1972    /// ([`ordered_attributes`]).
1973    fn line(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
1974        self.require_style(convention);
1975        let payload = payload_of::<LinePayload>(node);
1976        let mut values: Vec<(&'static str, String)> = Vec::new();
1977        let mut lengths: Vec<(&'static str, &Length)> = Vec::new();
1978        if let Some(payload) = payload {
1979            lengths.push(("indent_left", &payload.indent_left));
1980            lengths.push(("indent_right", &payload.indent_right));
1981            values.push(("align", String::from(payload.align.as_str())));
1982        }
1983        let classes = self.classes(node, convention, None);
1984        self.open(
1985            Some(node),
1986            "div",
1987            true,
1988            &classes,
1989            ordered_attributes(convention, &values, &lengths),
1990            false,
1991        );
1992        let content = body(node);
1993        self.run(Some(node), &content);
1994        self.close();
1995    }
1996
1997    /// The characters of a run of verbatim nodes: text runs unchanged, an
1998    /// interpolated content group's children without its braces, and anything
1999    /// else as its source spelling.
2000    ///
2001    /// Inside a verbatim region a document parse never produces a group, since
2002    /// `{` is an ordinary character there; a content group found in one is
2003    /// therefore the wrapper of an argument a template substituted, and its
2004    /// braces are syntax of the invocation rather than content.
2005    fn verbatim_text(&mut self, nodes: &[NodeRef<'_, Flm>]) -> String {
2006        let mut out = String::new();
2007        for node in nodes {
2008            match node.kind() {
2009                NodeKind::Chars { .. } => out.push_str(node.chars().unwrap_or("")),
2010                NodeKind::Group(_) if node.group_type() == Some(FlmGroupType::Content) => {
2011                    if self.descend() {
2012                        let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
2013                        let text = self.verbatim_text(&children);
2014                        out.push_str(&text);
2015                        self.ascend();
2016                    }
2017                }
2018                _ => out.push_str(&recompose_source(&[*node])),
2019            }
2020        }
2021        out
2022    }
2023
2024    /// A `flm.pres.verbatim`: code is `<code>` inline and `<pre><code>` as a
2025    /// block; plain characters and an identifier are not code, and are
2026    /// `<span>` inline and `<div>` as a block
2027    /// ([`TagRule::VerbatimKindAndDisplay`](super::conventions::TagRule::VerbatimKindAndDisplay)).
2028    fn verbatim(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
2029        let payload = payload_of::<VerbatimPayload>(node);
2030        let block =
2031            payload.is_some_and(|payload| payload.display == VerbatimDisplay::Block);
2032        let code = payload.is_some_and(|payload| payload.kind == VerbatimKind::Code);
2033        self.require_style(convention);
2034        let mut values: Vec<(&'static str, String)> = Vec::new();
2035        if let Some(payload) = payload {
2036            values.push(("kind", String::from(payload.kind.as_str())));
2037            values.push(("display", String::from(payload.display.as_str())));
2038            if let Some(lang) = payload.lang.as_deref() {
2039                values.push(("lang", String::from(lang)));
2040            }
2041        }
2042        let classes = self.classes(node, convention, None);
2043        let attributes = ordered_attributes(convention, &values, &[]);
2044        let content = self.verbatim_text(&body(node));
2045        let tag = match (code, block) {
2046            (true, true) => "pre",
2047            (true, false) => "code",
2048            (false, true) => "div",
2049            (false, false) => "span",
2050        };
2051        self.open(Some(node), tag, block, &classes, attributes, block);
2052        if code && block {
2053            self.open(None, "code", false, &[], Vec::new(), false);
2054        }
2055        self.write_text(&content);
2056        if code && block {
2057            self.close();
2058        }
2059        self.close();
2060    }
2061
2062    /// A `flm.pres.math-passthrough`: one formula of passthrough mathematics,
2063    /// written whole as the LaTeX a formula renderer in the reader's browser
2064    /// reads.
2065    ///
2066    /// The element is a `<span>` for every formula, inline and displayed
2067    /// alike, carrying the class, the display (`data-flm-display`, which tells
2068    /// the two apart) and the environment's name, and no identifier of its
2069    /// own. A displayed formula is opened as block-level, so that line breaks
2070    /// surround it; the default stylesheet gives it the appearance of a block.
2071    /// A `<div>` is not written because a displayed formula stands inside its
2072    /// paragraph, among the paragraph's text, and HTML does not allow a block
2073    /// element inside a `<p>`: written as a `<span>`, the formula leaves its
2074    /// paragraph a `<p>` ([`holds_flow_content`]). The element holds the
2075    /// delimiters the emitter chose and the formula's own source between them,
2076    /// written as text, with the content inside the formula written as HTML at
2077    /// its position ([`math_text`](Emitter::math_text)).
2078    ///
2079    /// A formula reached **inside the HTML written into another formula** is
2080    /// never written there, because the renderer does not read the HTML it
2081    /// inserts a second time; its source goes into the surrounding formula
2082    /// instead ([`math_text`](Emitter::math_text) describes how).
2083    fn math_passthrough(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
2084        if self.math.is_some() {
2085            self.formula_deeper_in_a_piece(node);
2086            return;
2087        }
2088        let payload = payload_of::<MathPassthroughPayload>(node);
2089        let display = payload.map_or(MathDisplay::Inline, |payload| payload.display);
2090        let env: Option<String> = payload.and_then(|payload| payload.env.clone());
2091        let block = display == MathDisplay::Display;
2092        self.require_style(convention);
2093        // The one definition the emitter requires that no row names: the
2094        // script that reads the LaTeX written here.
2095        self.require(SCRIPT_MATHJAX);
2096        let mut values: Vec<(&'static str, String)> =
2097            vec![("display", String::from(display.as_str()))];
2098        if let Some(env) = &env {
2099            values.push(("env", env.clone()));
2100        }
2101        let classes = self.classes(node, convention, payload.and_then(|payload| payload.role.as_ref()));
2102        // The tag is a `<span>` for a displayed formula too, although the
2103        // element is opened as block-level: see the rustdoc above.
2104        self.open(
2105            Some(node),
2106            "span",
2107            block,
2108            &classes,
2109            ordered_attributes(convention, &values, &[]),
2110            false,
2111        );
2112        let closing = closing_delimiter(display, env.as_deref());
2113        self.math = Some(MathContext {
2114            sequences: Arc::from(sequences_in_math(&closing)),
2115            span: node.span().clone(),
2116        });
2117        let opening = opening_delimiter(display, env.as_deref());
2118        self.write_math_source(&opening);
2119        self.math_stream(node);
2120        let closing = closing.text.clone();
2121        self.write_math_source(&closing);
2122        self.math = None;
2123        self.close();
2124    }
2125
2126    /// The nodes of a formula's body, in order: the source unchanged, written
2127    /// as text, and each `flm.pres.math-text` node among it written as HTML at
2128    /// its position.
2129    ///
2130    /// A formula nested in content inside a formula is written the same way:
2131    /// its source alone, into the formula around it, with no delimiters of its
2132    /// own, since its characters are already inside mathematics.
2133    fn math_stream(&mut self, node: &NodeRef<'_, Flm>) {
2134        let body = body(node);
2135        let mut source: Vec<NodeRef<'_, Flm>> = Vec::new();
2136        for child in &body {
2137            if !is_element(child, pres::MATH_TEXT) {
2138                source.push(*child);
2139                continue;
2140            }
2141            let text = recompose_source(&source);
2142            self.write_math_source(&text);
2143            source.clear();
2144            if !self.descend() {
2145                return;
2146            }
2147            if let Some(convention) = row(pres::MATH_TEXT) {
2148                self.math_text(child, convention);
2149            }
2150            self.ascend();
2151        }
2152        let text = recompose_source(&source);
2153        self.write_math_source(&text);
2154    }
2155
2156    /// A `flm.pres.math-text`: content inside a formula, written as HTML
2157    /// inside the formula's LaTeX.
2158    ///
2159    /// Inside a formula the content is written as
2160    /// `<tex-html><span class="flm-pres-math--text">…</span></tex-html>`. The
2161    /// `<tex-html>` element is the renderer's way of putting HTML inside a
2162    /// formula, and the renderer takes exactly one element out of it, so the
2163    /// attributes are on the `<span>` inside and never on the `<tex-html>`
2164    /// itself. A node with an anchor and no content is that same `<span>`,
2165    /// empty: a point in the formula that a link can lead to, which marks the
2166    /// start of an equation line. The
2167    /// [stylesheet](super::conventions::STYLE_MATH_PASSTHROUGH) keeps an empty one at zero
2168    /// size.
2169    ///
2170    /// A formula among the content's own nodes **splits** the content: the
2171    /// part being written (one `<tex-html>`) is closed, the inner formula's
2172    /// source goes into the surrounding formula with no delimiters of its own,
2173    /// and what follows it opens a new part. The identifier, the command and
2174    /// the node's source position are on the first part only, since each
2175    /// appears once per node; the class is on each part.
2176    ///
2177    /// A formula deeper inside the content (inside a styled span inside it, as
2178    /// `\text{\emph{\(x\)}}` gives) is handled by closing and opening again
2179    /// ([`formula_deeper_in_a_piece`](Emitter::formula_deeper_in_a_piece)).
2180    /// Nothing is lost and nothing is reported.
2181    ///
2182    /// Outside a formula (a hand-built tree, or a rule that staged the node
2183    /// elsewhere), the node is the `<span>` alone, and its content is ordinary
2184    /// content.
2185    fn math_text(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
2186        self.require_style(convention);
2187        let payload = payload_of::<MathTextPayload>(node);
2188        let content = body(node);
2189        if self.math.is_none() {
2190            let values = self.math_text_values(payload);
2191            let classes = self.classes(node, convention, None);
2192            self.open(
2193                Some(node),
2194                "span",
2195                false,
2196                &classes,
2197                ordered_attributes(convention, &values, &[]),
2198                false,
2199            );
2200            self.run(Some(node), &content);
2201            self.close();
2202            return;
2203        }
2204        // Content standing where a line's tag stands is written between a
2205        // pair of dollar signs, which is this backend's own: the formula's
2206        // source carries the content at that place, and the dollar signs are
2207        // what this backend writes around it there. Every other position is
2208        // written without them. They stand once around the whole node, not
2209        // around each piece, so that a formula inside the content keeps the
2210        // one pair it stands in.
2211        let at_tag = payload.is_some_and(|payload| payload.at_tag);
2212        if at_tag {
2213            self.write_math_source("$");
2214        }
2215        let mut written = false;
2216        let mut piece: Vec<NodeRef<'_, Flm>> = Vec::new();
2217        for child in &content {
2218            if !is_element(child, pres::MATH_PASSTHROUGH) {
2219                piece.push(*child);
2220                continue;
2221            }
2222            if !written || !piece.is_empty() {
2223                self.tex_html(node, convention, payload, !written, &piece);
2224                written = true;
2225            }
2226            piece.clear();
2227            if self.descend() {
2228                self.math_stream(child);
2229                self.ascend();
2230            }
2231        }
2232        if !written || !piece.is_empty() {
2233            self.tex_html(node, convention, payload, !written, &piece);
2234        }
2235        if at_tag {
2236            self.write_math_source("$");
2237        }
2238    }
2239
2240    /// The attributes a `flm.pres.math-text` node's payload asks for: the
2241    /// anchor as the identifier, and the command it was written in.
2242    fn math_text_values(
2243        &self,
2244        payload: Option<&MathTextPayload>,
2245    ) -> Vec<(&'static str, String)> {
2246        let mut values: Vec<(&'static str, String)> = Vec::new();
2247        if let Some(anchor) = payload.and_then(|payload| payload.anchor.clone()) {
2248            values.push(("anchor", anchor));
2249        }
2250        if let Some(command) = payload.and_then(|payload| payload.command.clone()) {
2251            values.push(("command", command));
2252        }
2253        values
2254    }
2255
2256    /// One part of a `flm.pres.math-text` node's content, written as HTML
2257    /// inside the formula: a `<tex-html>` holding one `<span>` holding
2258    /// `content`.
2259    ///
2260    /// `first` says that this is the node's first part, the one that carries
2261    /// the identifier, the command and the node's source position: each of
2262    /// those appears once per node, and the later parts carry the class alone.
2263    /// Only the first part is therefore written for the node itself; a later
2264    /// part is written for no node of its own, so a class refused inside the
2265    /// formula is reported there at the surrounding formula, the first part
2266    /// having already reported it at the node.
2267    fn tex_html(
2268        &mut self,
2269        node: &NodeRef<'_, Flm>,
2270        convention: &Convention,
2271        payload: Option<&MathTextPayload>,
2272        first: bool,
2273        content: &[NodeRef<'_, Flm>],
2274    ) {
2275        let values = if first { self.math_text_values(payload) } else { Vec::new() };
2276        let classes = self.classes(node, convention, None);
2277        // The piece this one stands inside, when a formula inside this
2278        // content holds content of its own: each `<tex-html>` keeps its own
2279        // list of what is open in it.
2280        let outer = self.piece.take();
2281        let was_in_tex_html = self.in_tex_html;
2282        self.sink.open_inline(TEX_HTML).finish();
2283        self.in_tex_html = true;
2284        self.open(
2285            first.then_some(node),
2286            "span",
2287            false,
2288            &classes,
2289            ordered_attributes(convention, &values, &[]),
2290            false,
2291        );
2292        self.piece = Some(Piece { classes, open: Vec::new() });
2293        self.run(Some(node), content);
2294        self.piece = None;
2295        self.sink.close();
2296        self.in_tex_html = was_in_tex_html;
2297        self.sink.close();
2298        self.piece = outer;
2299    }
2300
2301    /// A formula placed deeper inside the HTML of a part (one `<tex-html>`)
2302    /// than the content's own nodes, written by closing what is open and
2303    /// opening it again.
2304    ///
2305    /// The renderer never reads the HTML it inserts a second time, so a
2306    /// formula written inside that HTML would reach the reader as characters;
2307    /// its source must go into the surrounding formula's own characters. Where
2308    /// the formula is among the content's own nodes, that is a boundary
2309    /// between parts ([`math_text`](Emitter::math_text)); deeper, every element
2310    /// open inside the part (a styled span, a link, a tag a lowering rule
2311    /// staged) is closed first and opened again afterwards, so that the content
2312    /// around the formula keeps the elements it had. Each one is written again
2313    /// with the classes and attributes it carried, without its identifier and
2314    /// without its source position: an identifier may appear once in a page
2315    /// and a node's position once on the node's own element, so both stay on
2316    /// the element's first half. The part is opened again as a later part,
2317    /// carrying the class alone.
2318    fn formula_deeper_in_a_piece(&mut self, node: &NodeRef<'_, Flm>) {
2319        let Some(piece) = self.piece.take() else {
2320            // A formula inside a formula stands, by construction, inside a
2321            // piece: nothing else writes HTML into a formula.
2322            self.unexpected(node);
2323            return;
2324        };
2325        for _ in &piece.open {
2326            self.sink.close();
2327        }
2328        self.sink.close();
2329        self.in_tex_html = false;
2330        self.sink.close();
2331        self.math_stream(node);
2332        self.sink.open_inline(TEX_HTML).finish();
2333        self.in_tex_html = true;
2334        self.write_open(OpenInMath {
2335            tag: String::from("span"),
2336            block: false,
2337            classes: piece.classes.clone(),
2338            attributes: Vec::new(),
2339            preformatted: false,
2340        });
2341        self.piece = Some(Piece { classes: piece.classes, open: Vec::new() });
2342        for element in piece.open {
2343            self.write_open(element);
2344        }
2345    }
2346
2347    /// A `flm.pres.link`: an `<a>` whose address passed the policy.
2348    ///
2349    /// A link may be inside the content of another link: a term link in the
2350    /// text of an `\href`, a `\ref` in the text of a `\hyperref`, an xnote's
2351    /// mark in a heading's title that a reference shows. HTML does not allow
2352    /// an `<a>` inside another (a browser closes the outer one early), so the
2353    /// inner link is written as a `<span>` carrying the same classes
2354    /// and kind, and no address, document role or accessible name, since it
2355    /// leads nowhere; the outer one, which the author wrote around the whole
2356    /// text, is the one a reader follows. Its content is written as usual.
2357    /// Nothing is reported: this is the page's way of writing such a link.
2358    fn link(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
2359        self.require_style(convention);
2360        let nested = self.links_open > 0;
2361        let payload = payload_of::<LinkPayload>(node);
2362        let mut values: Vec<(&'static str, String)> = Vec::new();
2363        if let Some(payload) = payload {
2364            if !nested {
2365                match check_address(&payload.href, AddressUse::Link, self.url_schemes) {
2366                    Ok(()) => values.push(("href", payload.href.clone())),
2367                    Err(refused) => self.diags.push(Diagnostic::error(
2368                        AddressRefused {
2369                            address: payload.href.clone(),
2370                            scheme: refused.scheme,
2371                            attribute: String::from("href"),
2372                            allowed: self.url_schemes.allowed_addresses(),
2373                        },
2374                        node.span().clone(),
2375                    )),
2376                }
2377                if let Some(role) = payload.doc_role {
2378                    values.push(("doc_role", doc_role_value(role)));
2379                }
2380                if let Some(label) = &payload.label {
2381                    values.push(("label", label.clone()));
2382                }
2383            }
2384            // A link's kind is a single name written under the same attribute
2385            // a list of kinds is written under, so it passes the same check.
2386            if let Some(kind) = self.kind_tokens(node, std::slice::from_ref(&payload.kind)) {
2387                values.push(("kind", kind));
2388            }
2389        }
2390        let classes = self.classes(node, convention, None);
2391        self.open(
2392            Some(node),
2393            if nested { "span" } else { "a" },
2394            false,
2395            &classes,
2396            ordered_attributes(convention, &values, &[]),
2397            false,
2398        );
2399        let content = body(node);
2400        self.links_open += 1;
2401        self.run(Some(node), &content);
2402        self.links_open -= 1;
2403        self.close();
2404    }
2405
2406    /// A `flm.pres.image`: an `<img>` whose sources passed the policy; a
2407    /// block image carries the class of a block before its own
2408    /// ([`Written::BlockClass`]).
2409    fn image(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
2410        self.require_style(convention);
2411        let payload = payload_of::<ImagePayload>(node);
2412        let mut values: Vec<(&'static str, String)> = Vec::new();
2413        if let Some(payload) = payload {
2414            if let Some(anchor) = payload.anchor.clone() {
2415                values.push(("anchor", anchor));
2416            }
2417            match check_address(&payload.src, AddressUse::Image, self.url_schemes) {
2418                Ok(()) => values.push(("src", payload.src.clone())),
2419                Err(refused) => self.diags.push(Diagnostic::error(
2420                    AddressRefused {
2421                        address: payload.src.clone(),
2422                        scheme: refused.scheme,
2423                        attribute: String::from("src"),
2424                        allowed: self.url_schemes.allowed_addresses(),
2425                    },
2426                    node.span().clone(),
2427                )),
2428            }
2429            if let Some(alt) = payload.alt.clone() {
2430                values.push(("alt", alt));
2431            }
2432            let mut candidates: Vec<String> = Vec::new();
2433            for candidate in &payload.srcset {
2434                match check_address(&candidate.src, AddressUse::Image, self.url_schemes) {
2435                    Ok(()) => candidates.push(
2436                        if candidate.descriptor.is_empty() {
2437                            candidate.src.clone()
2438                        } else {
2439                            format!("{} {}", candidate.src, candidate.descriptor)
2440                        },
2441                    ),
2442                    Err(refused) => self.diags.push(Diagnostic::error(
2443                        AddressRefused {
2444                            address: candidate.src.clone(),
2445                            scheme: refused.scheme,
2446                            attribute: String::from("srcset"),
2447                            allowed: self.url_schemes.allowed_addresses(),
2448                        },
2449                        node.span().clone(),
2450                    )),
2451                }
2452            }
2453            if !candidates.is_empty() {
2454                values.push(("srcset", candidates.join(", ")));
2455            }
2456        }
2457        let mut lengths: Vec<(&'static str, &Length)> = Vec::new();
2458        if let Some(payload) = payload {
2459            lengths.extend(payload.width.as_ref().map(|width| ("width", width)));
2460            lengths.extend(payload.height.as_ref().map(|height| ("height", height)));
2461        }
2462        let mut classes = self.classes(node, convention, None);
2463        if payload.is_some_and(|payload| payload.display == ImageDisplay::Block) {
2464            classes.insert(0, class_of_element(pres::BLOCK));
2465        }
2466        self.void(Some(node), "img", &classes, ordered_attributes(convention, &values, &lengths));
2467    }
2468
2469    /// A `flm.pres.unsupported`: an empty span naming the element, which the
2470    /// stylesheet shows as an error.
2471    fn unsupported(&mut self, node: &NodeRef<'_, Flm>) {
2472        let element = payload_of::<UnsupportedPayload>(node)
2473            .map_or_else(String::new, |payload| payload.element.to_string());
2474        self.stand_in(node, &element);
2475    }
2476
2477    /// A `flm.pres.dropped`: a `<span>` carrying the condition of the
2478    /// diagnostic reported for what was left out, and holding `dropped: `
2479    /// followed by the payload's detail as its text, so that the mark shows
2480    /// on a page without a stylesheet. The row's style definition shows it as
2481    /// an error.
2482    fn dropped(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
2483        self.require_style(convention);
2484        let payload = payload_of::<DroppedPayload>(node);
2485        let mut values: Vec<(&'static str, String)> = Vec::new();
2486        if let Some(payload) = payload {
2487            values.push(("condition", payload.condition.to_string()));
2488        }
2489        let classes = self.classes(node, convention, None);
2490        self.open(Some(node), "span", false, &classes, ordered_attributes(convention, &values, &[]), false);
2491        let detail = payload.map_or("", |payload| payload.detail.as_str());
2492        self.write_text(&format!("dropped: {detail}"));
2493        self.close();
2494    }
2495
2496    /// The stand-in for something this backend cannot write: an empty span
2497    /// naming the element.
2498    ///
2499    /// `node` is the node the stand-in is written for, and the stand-in is the
2500    /// one element written for it, so it carries that node's position in its
2501    /// source under the option that asks for positions. That holds of the node
2502    /// whose element this backend cannot write and of a staged tag the emitter
2503    /// refuses to write: in the second case no staged tag reaches the page at
2504    /// all, so what the page holds there is the emitter's own stand-in — carrying the
2505    /// emitter's own class and its own attribute — and not the tag the rule
2506    /// asked for.
2507    fn stand_in(&mut self, node: &NodeRef<'_, Flm>, element: &str) {
2508        let convention = row(pres::UNSUPPORTED).expect("the vocabulary has a row for every element");
2509        self.require_style(convention);
2510        let values = vec![("element", String::from(element))];
2511        // The stand-in stands for a node whose own row it is not, so it takes
2512        // the class of the element it is — and no role, which is why it does
2513        // not go through `classes`, the one place a role is checked.
2514        let classes = vec![class_of_element(convention.element)];
2515        self.open(
2516            Some(node),
2517            "span",
2518            false,
2519            &classes,
2520            ordered_attributes(convention, &values, &[]),
2521            false,
2522        );
2523        self.close();
2524    }
2525
2526    /// A `flm.pres.unknown`: what the author wrote, shown as the error it is.
2527    fn unknown(&mut self, node: &NodeRef<'_, Flm>, convention: &Convention) {
2528        let payload = payload_of::<UnknownPayload>(node);
2529        let kind = payload.map_or(UnknownKind::Macro, |payload| payload.kind);
2530        self.require_style(convention);
2531        let mut values: Vec<(&'static str, String)> = Vec::new();
2532        if let Some(payload) = payload {
2533            values.push(("kind", String::from(payload.kind.as_str())));
2534            values.push(("name", payload.name.clone()));
2535        }
2536        let classes = self.classes(node, convention, None);
2537        let attributes = ordered_attributes(convention, &values, &[]);
2538        let spelling = payload.map_or_else(String::new, |payload| payload.spelling.clone());
2539        match kind {
2540            UnknownKind::Macro => {
2541                self.open(Some(node), "span", false, &classes, attributes, false);
2542                self.write_text(&spelling);
2543                self.close();
2544            }
2545            UnknownKind::Environment => {
2546                self.open(Some(node), "div", true, &classes, attributes, false);
2547                self.marker(&format!("\\begin{{{spelling}}}"));
2548                let content = body(node);
2549                self.run(Some(node), &content);
2550                self.marker(&format!("\\end{{{spelling}}}"));
2551                self.close();
2552            }
2553        }
2554    }
2555
2556    /// One marker line of an unattributed environment.
2557    fn marker(&mut self, text: &str) {
2558        let classes = [String::from(UNKNOWN_MARKER_CLASS)];
2559        self.open(None, "span", true, &classes, Vec::new(), false);
2560        self.write_text(text);
2561        self.close();
2562    }
2563
2564    /// A decoration, written as a `<span>` at its position: at its decoration
2565    /// mark, or, in a tree no lowering driver built, where the decoration itself
2566    /// is in the run.
2567    ///
2568    /// A margin decoration is written like the other two kinds, inside the
2569    /// flow of the text at the position its mark keeps — inside a paragraph,
2570    /// inside a heading's title, at the start of the block that carries it —
2571    /// and the stylesheet sets it beside the text. It is a `<span>` because
2572    /// HTML allows a `<span>` at every one of those places, while an `<aside>`
2573    /// inside a `<p>` is not valid HTML.
2574    ///
2575    /// A run-in decoration — the title of a heading set at the start of the
2576    /// paragraph it introduces — takes a stop after its title, inside the same
2577    /// span: the render option
2578    /// [`HtmlRenderOptions::run_in_stop`], written as ordinary escaped text,
2579    /// unless the option is empty, the title is blank ([`holds_text`]) or the
2580    /// title already ends in sentence punctuation
2581    /// ([`ends_in_sentence_punctuation`]). Both tests are the shared ones over
2582    /// the content tree, which this emitter still holds when it reaches the
2583    /// decoration; nothing here reads back what was written.
2584    fn decoration(
2585        &mut self,
2586        node: &NodeRef<'_, Flm>,
2587        convention: &Convention,
2588    ) {
2589        self.require_style(convention);
2590        let classes = self.classes(node, convention, None);
2591        self.open(Some(node), "span", false, &classes, Vec::new(), false);
2592        let content = body(node);
2593        self.run(Some(node), &content);
2594        if is_element(node, pres::DECO_RUNIN)
2595            && !self.options.run_in_stop.is_empty()
2596            && holds_text(content.iter().copied())
2597            && !ends_in_sentence_punctuation(content.iter().copied())
2598        {
2599            let stop = self.options.run_in_stop.clone();
2600            self.write_text(&stop);
2601        }
2602        self.close();
2603    }
2604
2605    /// A `flm.pres.deco-mark`: the decoration it stands for, at its position,
2606    /// regardless of its kind. A mark whose decoration cannot be resolved — a tree
2607    /// no lowering driver built — writes nothing.
2608    fn deco_mark(&mut self, carrier: Option<&NodeRef<'_, Flm>>, node: &NodeRef<'_, Flm>) {
2609        let Some(carrier) = carrier else { return };
2610        let Some(deco) = decoration_at(carrier, node) else { return };
2611        let Some(convention) = row(element_of(&deco).name.as_str()) else { return };
2612        self.decoration(&deco, convention);
2613    }
2614
2615    /// A `flm.pres.subtree`: the segment being written ends here, and the
2616    /// placed tree is recorded for the regions stage to write in its place.
2617    fn subtree(&mut self, node: &NodeRef<'_, Flm>) {
2618        let Some(payload) = payload_of::<SubtreePayload>(node) else { return };
2619        // A count of the bytes written, never the bytes: the sink stays
2620        // unreadable, and the count is what lets the page assembly write the
2621        // placed tree where it belongs.
2622        let at = self.sink.len();
2623        self.placements.push((at, payload.tree, node.span().clone()));
2624    }
2625
2626    /// A `flm.pres.html.tag`: the tag a lowering rule staged, written as its
2627    /// payload states it.
2628    ///
2629    /// The HTML contract does not apply to it (the emitter adds no class and
2630    /// no attribute of its own), and neither does the address policy: the rule
2631    /// that staged the tag is responsible for what it writes. The names are
2632    /// checked, because a name is written unchanged and one that is not
2633    /// writable would produce markup the rule did not ask for.
2634    ///
2635    /// Inside the HTML written into a formula the attribute *values* are
2636    /// checked as well, exactly as every other attribute written there is
2637    /// ([`writable_in_math`](Emitter::writable_in_math)): a value holding the
2638    /// closing delimiter of the surrounding formula would end that formula
2639    /// early, and only the emitter knows which delimiter it wrote. A body given
2640    /// as [`Markup`] is written unchanged, there as anywhere else: the code
2641    /// that staged the node created those bytes and is responsible for them
2642    /// ([`HtmlTagPayload`] says what that means inside a formula).
2643    ///
2644    /// The text of the children of a tag named `tex-html` is repaired as the
2645    /// text inside a formula's `<tex-html>` is ([`Emitter::write_text`],
2646    /// [`sequences_in_construct`]): MathJax reads that element's characters
2647    /// whoever staged it.
2648    fn construct(&mut self, node: &NodeRef<'_, Flm>) {
2649        let Some(payload) = payload_of::<HtmlTagPayload>(node) else {
2650            self.unexpected(node);
2651            return;
2652        };
2653        if !is_valid_tag_name(&payload.tag) {
2654            self.diags.push(Diagnostic::error(
2655                InvalidName {
2656                    what: String::from("tag"),
2657                    name: payload.tag.clone(),
2658                    recovery: String::from("the node was written as the unsupported stand-in"),
2659                },
2660                node.span().clone(),
2661            ));
2662            self.stand_in(node, super::construct::TAG);
2663            return;
2664        }
2665        for (name, _) in &payload.attributes {
2666            if !is_valid_attribute_name(name) {
2667                self.diags.push(Diagnostic::error(
2668                    InvalidName {
2669                        what: String::from("attribute"),
2670                        name: name.clone(),
2671                        recovery: String::from(
2672                            "the node was written as the unsupported stand-in",
2673                        ),
2674                    },
2675                    node.span().clone(),
2676                ));
2677                self.stand_in(node, super::construct::TAG);
2678                return;
2679            }
2680        }
2681        let attributes: Vec<(String, String)> = payload
2682            .attributes
2683            .iter()
2684            .map(|(name, value)| (name.clone(), value.clone()))
2685            .collect();
2686        let attributes = self.writable_in_math(Some(node), attributes);
2687        self.write_open(OpenInMath {
2688            tag: payload.tag.clone(),
2689            block: payload.block,
2690            classes: Vec::new(),
2691            attributes,
2692            preformatted: false,
2693        });
2694        match &payload.body {
2695            TagBody::Markup(markup) => self.sink.markup(markup),
2696            TagBody::Children => {
2697                let content = body(node);
2698                let tex_html = payload.tag == TEX_HTML;
2699                self.tex_html_constructs += usize::from(tex_html);
2700                self.run(Some(node), &content);
2701                self.tex_html_constructs -= usize::from(tex_html);
2702            }
2703        }
2704        self.close();
2705    }
2706
2707    /// Records the style definition the row gives as a requirement, when it
2708    /// gives one.
2709    fn require_style(&mut self, convention: &Convention) {
2710        if let Some(style) = convention.style {
2711            self.require(style);
2712        }
2713    }
2714}
2715
2716#[cfg(test)]
2717mod tests {
2718    use super::*;
2719
2720    /// The sequences that stand around inline mathematics: `\)` and the two
2721    /// tag spellings.
2722    fn inline_sequences() -> Vec<Sequence> {
2723        sequences_in_math(&closing_delimiter(MathDisplay::Inline, None))
2724    }
2725
2726    /// `text` with an empty element written at every break point, spelled the
2727    /// way the emitter writes it.
2728    fn broken(text: &str, sequences: &[Sequence]) -> String {
2729        let mut out = String::new();
2730        let mut at = 0;
2731        for point in break_points(text, sequences) {
2732            out.push_str(&text[at..point]);
2733            out.push_str("<span></span>");
2734            at = point;
2735        }
2736        out.push_str(&text[at..]);
2737        out
2738    }
2739
2740    #[test]
2741    fn the_style_writer_writes_nothing_for_a_zero_length() {
2742        let line = row(pres::LINE).expect("the line row");
2743        let zero = Length::tabs(0);
2744        let two = Length::tabs(2);
2745        let align = [("align", String::from("left"))];
2746        let attributes =
2747            ordered_attributes(line, &align, &[("indent_left", &zero), ("indent_right", &zero)]);
2748        assert!(attributes.iter().all(|(name, _)| name != STYLE_ATTRIBUTE), "{attributes:?}");
2749        let attributes =
2750            ordered_attributes(line, &align, &[("indent_left", &two), ("indent_right", &zero)]);
2751        assert_eq!(
2752            attributes.iter().find(|(name, _)| name == STYLE_ATTRIBUTE).map(|(_, value)| value.as_str()),
2753            Some("--flm-element-indent-left: calc(2 * var(--flm-tab))")
2754        );
2755    }
2756
2757    #[test]
2758    fn the_source_span_attribute_is_the_name_the_naming_function_derives() {
2759        assert_eq!(SOURCE_SPAN_ATTRIBUTE, data_attribute("source_span"));
2760        assert!(is_valid_attribute_name(SOURCE_SPAN_ATTRIBUTE));
2761    }
2762
2763    #[test]
2764    fn the_value_of_the_source_span_attribute_is_a_json_array_of_three_items() {
2765        assert_eq!(source_span_value("book/ch1.flm", &(0..8)), "[\"book/ch1.flm\",0,8]");
2766    }
2767
2768    #[test]
2769    fn the_delimiters_are_the_three_shapes_a_formula_is_written_in() {
2770        assert_eq!(opening_delimiter(MathDisplay::Inline, None), "\\(");
2771        assert_eq!(closing_delimiter(MathDisplay::Inline, None).text, "\\)");
2772        assert_eq!(opening_delimiter(MathDisplay::Display, None), "\\[");
2773        assert_eq!(closing_delimiter(MathDisplay::Display, None).text, "\\]");
2774        assert_eq!(
2775            opening_delimiter(MathDisplay::Display, Some("align")),
2776            "\\begin{align}"
2777        );
2778        assert_eq!(
2779            closing_delimiter(MathDisplay::Display, Some("align")).text,
2780            "\\end{align}"
2781        );
2782        // The environment's name decides the closing sequence, so a formula in
2783        // one environment is not cut short by another's end.
2784        assert_eq!(closing_delimiter(MathDisplay::Display, Some("gather")).text, "\\end{gather}");
2785    }
2786
2787    #[test]
2788    fn source_holding_the_tag_gets_an_empty_group_after_its_opening_angle() {
2789        assert_eq!(neutralized_source("a < b"), "a < b");
2790        assert_eq!(neutralized_source("x <tex-html> y"), "x <{}tex-html> y");
2791        assert_eq!(neutralized_source("x </tex-html> y"), "x <{}/tex-html> y");
2792        // Both spellings in one run, and the substitution of one never builds
2793        // the other.
2794        assert_eq!(
2795            neutralized_source("<tex-html><b>p</b></tex-html>"),
2796            "<{}tex-html><b>p</b><{}/tex-html>"
2797        );
2798        // A `<` that begins neither spelling is left alone, and so is a
2799        // spelling that is only begun.
2800        assert_eq!(neutralized_source("<tex-htm"), "<tex-htm");
2801        assert_eq!(neutralized_source("a < tex-html"), "a < tex-html");
2802    }
2803
2804    #[test]
2805    fn source_that_holds_no_tag_is_unchanged_whatever_it_holds() {
2806        for source in ["", "x^2 + y", "a \\le b", "\\text{if}", "α < β", "&\\\\"] {
2807            assert_eq!(neutralized_source(source), source, "{source}");
2808        }
2809    }
2810
2811    #[test]
2812    fn text_inside_the_html_breaks_the_closing_delimiter_and_the_two_tags() {
2813        let sequences = inline_sequences();
2814        assert_eq!(broken("write \\) here", &sequences), "write \\<span></span>) here");
2815        assert_eq!(
2816            broken("write <tex-html> here", &sequences),
2817            "write <<span></span>tex-html> here"
2818        );
2819        assert_eq!(
2820            broken("write </tex-html> here", &sequences),
2821            "write <<span></span>/tex-html> here"
2822        );
2823        // The delimiter of another formula is not this formula's end and is
2824        // left alone.
2825        assert_eq!(broken("write \\] here", &sequences), "write \\] here");
2826    }
2827
2828    #[test]
2829    fn the_environment_name_is_part_of_the_sequence_that_is_broken() {
2830        let sequences = sequences_in_math(&closing_delimiter(MathDisplay::Display, Some("align")));
2831        assert_eq!(
2832            broken("stop at \\end{align} here", &sequences),
2833            "stop at \\end<span></span>{align} here"
2834        );
2835        assert_eq!(broken("\\end{gather} is not this end", &sequences), "\\end{gather} is not this end");
2836    }
2837
2838    #[test]
2839    fn a_text_that_holds_no_sequence_is_written_as_it_stands() {
2840        let sequences = inline_sequences();
2841        for text in ["", "one half", "a < b", "\\alpha", "( ) \\ ]"] {
2842            assert_eq!(broken(text, &sequences), text, "{text}");
2843            assert!(break_points(text, &sequences).is_empty(), "{text}");
2844        }
2845    }
2846
2847    #[test]
2848    fn every_occurrence_of_a_sequence_is_broken_including_two_in_a_row() {
2849        let sequences = inline_sequences();
2850        assert_eq!(broken("\\)\\)", &sequences), "\\<span></span>)\\<span></span>)");
2851        assert_eq!(break_points("\\)\\)", &sequences), vec![1, 3]);
2852        // A backslash before the sequence does not hide it: the renderer
2853        // searches the characters and would find the delimiter at the second
2854        // backslash.
2855        assert_eq!(broken("\\\\)", &sequences), "\\\\<span></span>)");
2856    }
2857
2858    #[test]
2859    fn an_attribute_value_is_refused_for_the_first_sequence_it_holds() {
2860        let sequences = inline_sequences();
2861        assert_eq!(refused_sequence("eq:one", &sequences), None);
2862        assert_eq!(refused_sequence("eq:\\)one", &sequences).as_deref(), Some("\\)"));
2863        assert_eq!(
2864            refused_sequence("a </tex-html> b", &sequences).as_deref(),
2865            Some("</tex-html")
2866        );
2867        // The earliest occurrence names the refusal, whichever sequence it is.
2868        assert_eq!(
2869            refused_sequence("<tex-html \\)", &sequences).as_deref(),
2870            Some("<tex-html")
2871        );
2872        assert_eq!(
2873            refused_sequence("\\) <tex-html", &sequences).as_deref(),
2874            Some("\\)")
2875        );
2876    }
2877
2878    #[test]
2879    fn a_break_point_falls_at_the_sequences_own_joint() {
2880        // The three shapes of a closing delimiter, and the two tag spellings,
2881        // each broken where the sequence joins: this is what the goldens hold.
2882        assert_eq!(closing_delimiter(MathDisplay::Inline, None).break_at, 1);
2883        assert_eq!(closing_delimiter(MathDisplay::Display, None).break_at, 1);
2884        assert_eq!(closing_delimiter(MathDisplay::Display, Some("align")).break_at, 4);
2885        for sequence in tex_html_sequences() {
2886            assert_eq!(sequence.break_at, 1, "{}", sequence.text);
2887        }
2888    }
2889}