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