Skip to main content

leaf_core/
wysiwyg.rs

1//! The WYSIWYG view: render the document with its markup *resolved*, not shown —
2//! headings and code tagged with a typographic role (a frontend sizes or colours
3//! them; see [`crate::style`]), `**bold**` as real bold, `# ` / `**` / `` ` ``
4//! delimiters hidden — while keeping every visible glyph tied back to the source
5//! byte it came from.
6//!
7//! That back-reference (`Glyph::src`) is what lets a caret still work: the caret
8//! stays a source offset (shared with the source view), but the [`VisualMap`]
9//! converts between an offset and a screen `(row, col)`, so cursor drawing,
10//! mouse clicks, and vertical motion all operate in *visible* space.
11//!
12//! Left and Right instead walk the map's caret *stops* in document order. On
13//! ordinary prose that's the same journey — the stops are laid out left to right
14//! — and it steps over the hidden delimiters either way. They part company only
15//! in a table, where the text is arranged in two dimensions and a cell wrapped
16//! within its column continues *below* rather than to the right. Following the
17//! document is what a caret means there.
18//!
19//! Text is walked from the AST (`str` nodes carry exact spans, and their text is
20//! the verbatim source slice), so a Markdown and a Djot file that parse alike
21//! render — and map — identically.
22
23use std::cell::{Cell, RefCell};
24use std::collections::HashMap;
25use std::ops::Range;
26use std::sync::OnceLock;
27
28use twig::{Alignment, ContainerOrigin, DirectiveForm, Editor, FlatNode, Kind, QueryMatch};
29use unicode_segmentation::UnicodeSegmentation;
30use unicode_width::UnicodeWidthStr;
31
32use crate::style::{
33    Align, Baseline, FaceId, FaceRef, FaceTable, FontSize, LineHeight, MarkColor, Role, Style,
34    TextColor, Token,
35};
36
37/// One rendered character plus the source byte offset it originates from.
38/// Synthetic glyphs (a list bullet, a quote gutter) point at their block's
39/// start, so clicking one lands the caret at the start of that block.
40#[derive(Clone)]
41pub struct Glyph {
42    pub ch: char,
43    pub style: Style,
44    pub src: usize,
45    /// Whether the caret may *rest* on this glyph. Decoration — a table border
46    /// or a cell's alignment padding — is visible but isn't text, so the caret
47    /// steps over it instead of into it. It also can't be a stop even in
48    /// principle: a run of decoration shares one `src`, and a caret can only
49    /// move by changing offset, so resting on it would pin horizontal motion.
50    /// A click still maps through `src`, which is why decoration points at the
51    /// text it decorates.
52    ///
53    /// Real text is a stop once per *grapheme cluster*, on the glyph that opens
54    /// it: the continuation glyphs of an emoji or an accented letter are drawn,
55    /// but standing between them is standing inside a character.
56    pub stop: bool,
57}
58
59/// One visual line. `end_src` is the source offset a caret sits at when placed
60/// at the line's end (past its last glyph) — the anchor for end-of-line and
61/// click-past-content.
62///
63/// `Clone` so a block's rows can be cached and re-emitted at a shifted offset
64/// across an edit — see [`BlockCache`].
65#[derive(Clone)]
66pub struct VRow {
67    pub glyphs: Vec<Glyph>,
68    pub end_src: usize,
69    /// A row that is drawn but holds no caret: a table's `├───┼───┤` rules, and
70    /// the blank gap a block boundary is spelled with. Vertical motion steps
71    /// over it, `pos_of_offset` never resolves onto it, and its stops (it has
72    /// none) and `end_src` stay out of the map's stop table.
73    ///
74    /// Emptiness isn't the test — an empty paragraph is a blank row too, and a
75    /// real caret stop. The test is whether the row is somewhere text can go.
76    pub decoration: bool,
77    /// This row is one line of a fenced or indented code block. Set on every row
78    /// the `"code_block"` arm emits — including its blank lines, which carry no
79    /// glyph to tell them apart otherwise. A frontend draws its own chrome (a
80    /// border and a tinted background) around each maximal run of these, and
81    /// scrolls them horizontally instead of wrapping; see
82    /// [`VisualMap::code_blocks`]. Survives the row shuffling of [`BlockCache`]
83    /// reuse and [`build_spliced`] because it rides on the row, not on a
84    /// row-index span the way a table's picture does.
85    pub code: bool,
86    /// A fenced code block's info string (its language), carried on the *first*
87    /// row of the block so it survives row reuse the way [`code`](Self::code)
88    /// does. `None` on every other row, and on an indented block (which has no
89    /// fence to label). A frontend paints it as a small label on the block's box
90    /// and edits it through a prompt — see [`CodeBlockInfo::lang`]. It's a plain
91    /// display string, not a source slice, so it needs no offset shifting; the
92    /// label re-derives from twig on the next build.
93    pub code_lang: Option<String>,
94    /// This row belongs to a `:::name{.class}` directive container — twig's
95    /// generic fenced-div block, whose meaning is entirely up to the host app
96    /// (diaryx's `:::vis{.audience}` visibility blocks, say). Set on every row
97    /// the `"directive"` arm emits, the same way [`code`](Self::code) marks a
98    /// code block's rows, so a frontend can draw a tinted panel around each
99    /// maximal run of these.
100    pub directive: bool,
101    /// A directive container's space-joined attrs — dot-prefixed classes
102    /// (`.public .family` → `"public family"`) unioned with bare pandoc-style
103    /// words (`public family`, no leading dot — diaryx's other `:::vis{...}`
104    /// convention), carried on the block's *first* row only — the
105    /// [`code_lang`](Self::code_lang) pattern. `None` on every other row, and
106    /// when the directive carries no such attrs. A frontend paints it as a
107    /// small label on the block's panel; it's a plain display string, not a
108    /// source slice, so it rides row reuse untouched.
109    pub directive_label: Option<String>,
110    /// Set on the single placeholder row a block-level image renders to, carrying
111    /// the image's destination and alt text; `None` on every other row. The row's
112    /// glyphs are the default `🖼 alt` label (which a plain surface paints as-is);
113    /// an image-capable frontend reads this to paint the real picture instead,
114    /// skipping the row named by [`MediaInfo::rows_span`]. Like
115    /// [`code_lang`](Self::code_lang) it's plain display strings, not source
116    /// slices, so it rides row reuse and needs no offset shifting; the map's
117    /// [`media`](VisualMap::media) side-table is derived from it once the rows
118    /// are final, the same way [`code_blocks`](VisualMap::code_blocks) is.
119    pub media: Option<MediaMark>,
120    /// Set on the **first** row of a task list item, carrying whether its box is
121    /// ticked; `None` on every other row, including a plain `list_item`'s. The
122    /// row's glyphs already draw the box as `☐ `/`☑ ` in the marker's place, so a
123    /// plain surface needs nothing further; a GUI reads this to paint a real
124    /// checkbox widget and to know which way it is facing.
125    ///
126    /// A `bool` rather than a source span, for the reason
127    /// [`code_lang`](Self::code_lang) is a plain string: it rides [`BlockCache`]
128    /// reuse and [`build_spliced`] untouched, needing no offset shifting. To
129    /// *toggle* the box, a frontend maps its click to a source offset the way it
130    /// maps any other — the marker's glyphs carry the item's own `src` — and
131    /// hands that to [`crate::Doc::toggle_task_at`].
132    pub task: Option<bool>,
133    /// Set on the single placeholder row a **leaf** directive (`::name{…}`)
134    /// renders to, carrying its name and attributes; `None` on every other row.
135    /// The container form isn't this — it wraps real blocks and marks each of
136    /// them [`directive`](Self::directive) instead. Like [`media`](Self::media)
137    /// it's plain display strings, so it rides row reuse untouched, and the map's
138    /// [`directives`](VisualMap::directives) side-table is derived from it once
139    /// the rows are final.
140    pub leaf_directive: Option<DirectiveMark>,
141    /// The heading level (1–6) of the block this row belongs to, on every row a
142    /// `heading` emits (a long one wraps to several) and `None` everywhere else.
143    ///
144    /// A frontend that sizes a whole line — a proportional renderer giving the
145    /// row a bigger line box — needs the level *per row*, and the glyphs can't
146    /// always supply it: an empty heading (`# ` with nothing typed after it,
147    /// which is what the toolbar's H1 leaves on a blank line) has no glyph to
148    /// carry a [`Role::Heading`] at all, so a glyph scan called it body text and
149    /// the line drew at body height until the first character landed. Riding the
150    /// row says it once, for the empty case and the wrapped case alike.
151    ///
152    /// Per-*glyph* styling still comes from [`Role::Heading`] on the glyphs; this
153    /// is the row-level fact, and the two agree wherever a heading has content —
154    /// same `u8` level, clamped the same way [`heading_style`] clamps it.
155    pub heading: Option<u8>,
156    /// How this row's block is aligned across the measure — the author's
157    /// `class="center"`, on every row the block emits and `None` for the
158    /// theme's default, which is left.
159    ///
160    /// A *row* fact and not a glyph one for [`heading`](Self::heading)'s reason,
161    /// and more sharply: alignment is a property of the *line*, not of the
162    /// letters on it, so an empty paragraph the author has just centred has to
163    /// carry it with no glyph to hang it on. It rides the row like a plain
164    /// `Copy` flag, so [`BlockCache`] reuse and [`build_spliced`] carry it
165    /// untouched.
166    ///
167    /// Read from the paragraph's or heading's own attributes and from those of
168    /// every `div` around it, the nearest winning — so `<div class="center">`
169    /// around three paragraphs centres all three, which is what the author of
170    /// that HTML meant.
171    pub align: Option<Align>,
172    /// How far apart this row's block sets its lines, as a multiple of the
173    /// theme's own line height — the author's `data-line-height`, on every row
174    /// the block emits and `None` for the theme's spacing.
175    ///
176    /// A frontend that lays rows out in pixels scales the row's height by
177    /// [`LineHeight::as_f32`]; one that draws a row per terminal line ignores
178    /// it, the way it ignores a heading's size. Read at the same two levels
179    /// [`align`](Self::align) is, and one of the menu's three names or the
180    /// exact ratio the author asked for.
181    pub line_height: Option<LineHeight>,
182    /// What this row divides, on the blank rows a block boundary is *drawn* with
183    /// and `None` on every other row — including the navigable blank lines of
184    /// preserve-soft flow, which are somewhere text can go rather than a gap
185    /// between blocks. So `boundary.is_some()` is exactly "this row is a drawn
186    /// block boundary", the [`decoration`](Self::decoration) rows that come from
187    /// [`Builder::emit_separators_before`].
188    ///
189    /// It exists because a boundary's *height* is a frontend decision but its
190    /// *kind* is not. Typography spaces a boundary by what it separates — the
191    /// margin above a heading is wider than the one between two paragraphs, so
192    /// the heading groups with the text it introduces — and a frontend that has
193    /// only rows to look at has to re-derive the structure by sniffing glyph
194    /// roles. Three frontends sniffing separately is three chances to disagree
195    /// about the same document. Core already knows, having just walked the AST
196    /// to emit this row, so it says so once here and each frontend multiplies by
197    /// its own spacing.
198    pub boundary: Option<Boundary>,
199    /// The offsets on this row where an inline mark's *content* ends under a
200    /// hidden closing delimiter — the end of the `d` in `**bold**`, one byte
201    /// before the `**` that draws nothing. Each is a caret stop with no glyph
202    /// of its own: the caret standing there is drawn where the next glyph is,
203    /// but typing there extends the mark, where typing past the delimiter
204    /// leaves it. See [`VisualMap::mark_ends`] for the rule.
205    ///
206    /// Source offsets, so [`shift_row`] moves them with the glyphs; empty on
207    /// decoration rows and on every row no mark closes on.
208    pub mark_ends: Vec<usize>,
209    /// The formulas this row stands in for, in glyph order: one [`MathMark`]
210    /// per inline atom on the row, or the single block mark on the
211    /// placeholder row a display formula renders to. Empty on every other
212    /// row, and on the revealed line, where a formula is its TeX and no
213    /// picture stands for it.
214    ///
215    /// Plain strings and a glyph *index* rather than a source offset, for
216    /// [`media`](Self::media)'s reason: the mark rides [`BlockCache`] reuse and
217    /// [`build_spliced`] untouched, and the glyph it names carries the offset.
218    /// The map's [`math`](VisualMap::math) side-table is derived from these
219    /// once the rows are final.
220    pub math: Vec<MathMark>,
221}
222
223/// One formula a row stands in for — what a picture-capable frontend typesets
224/// and draws in place of the glyph or the rows that hold its spot. See
225/// [`VRow::math`] and, for the frontend's view of the same thing,
226/// [`MathInfo`].
227#[derive(Clone, Debug, PartialEq, Eq)]
228pub struct MathMark {
229    /// The TeX between the delimiters, verbatim — a display block's keeps its
230    /// newlines. What `leaf-math` typesets.
231    pub tex: String,
232    /// Display style (`$$…$$`) rather than text style (`$…$`). True for every
233    /// block mark, and for a `$$…$$` written inside a line of prose, which is
234    /// display style set inline.
235    pub display: bool,
236    /// The index into [`VRow::glyphs`] of the atom this mark stands behind —
237    /// the one [`Role::Math`] glyph an inline formula renders to. `None` for
238    /// a block mark, whose placeholder is the whole row.
239    pub glyph: Option<usize>,
240    /// How many rows a block formula reserves — the label row plus the blank
241    /// fillers under it, the [`MediaMark::rows`] recipe, and from the same
242    /// door: a terminal frontend that has typeset and measured the picture
243    /// reports its height through [`crate::Doc::set_math_rows`]. `1` for an
244    /// inline atom, which reserves nothing.
245    pub rows: usize,
246}
247
248/// What a drawn block boundary separates: the kinds of the blocks it falls
249/// between — the pair a frontend spaces by.
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
251pub struct Boundary {
252    pub above: BlockClass,
253    pub below: BlockClass,
254}
255
256/// The block kinds core tells apart when it walks a document — the vocabulary
257/// [`Boundary`] is spelled in. A statement about *structure*, not about how any
258/// of it should look: what a frontend does with "this gap sits above a heading"
259/// is entirely the frontend's.
260///
261/// `Class` rather than `Kind` because [`twig::BlockKind`] already means
262/// something else in this crate's public surface — the *command* vocabulary
263/// (`Paragraph | Heading(n)`) a toolbar passes to [`Doc::set_block`](crate::Doc::set_block).
264/// This is the reverse direction: what a block already *is*, read back off a
265/// rendered row.
266///
267/// [`BlockClass::Other`] is the honest answer for a node kind core doesn't
268/// separate out, so adding one here is additive for every frontend: nothing has
269/// to change until it wants to space that kind differently.
270#[derive(Clone, Copy, Debug, PartialEq, Eq)]
271pub enum BlockClass {
272    Paragraph,
273    Heading,
274    /// A whole list. Its *items* are [`BlockClass::ListItem`]; note that core
275    /// draws no boundary row between two items of one list, tight or loose, so
276    /// an item↔item pair never reaches a frontend.
277    List,
278    ListItem,
279    Quote,
280    Code,
281    Table,
282    /// A block-level image, video, or audio.
283    ///
284    /// Never reached through [`from_node_kind`](BlockClass::from_node_kind): a
285    /// block picture is not a node of its own — [`Builder::media_only`] promotes
286    /// the paragraph (or `<picture>`/`<video>` container) wrapping it — so the
287    /// walk only ever sees the wrapper's kind. [`label_media_boundaries`] reads
288    /// it back off the finished rows instead, after the fact.
289    Media,
290    /// A display formula on lines of its own — a paragraph holding nothing but
291    /// a `$$…$$`. Never reached through [`from_node_kind`](BlockClass::from_node_kind)
292    /// for [`Media`](BlockClass::Media)'s reason: the walk sees the wrapping
293    /// paragraph, and [`label_media_boundaries`] relabels the gaps around the
294    /// placeholder once the rows are final.
295    Math,
296    /// A `:::name{.class}` directive container.
297    Directive,
298    Rule,
299    Footnote,
300    Other,
301}
302
303impl BlockClass {
304    /// Classify a twig node kind — the same vocabulary [`Builder::block`]
305    /// matches on, so the two can't drift about what a block is. Both the
306    /// whole-arena walk (which has [`FlatNode`]s) and the incremental top-level
307    /// walk (which has only a query match's kind) reach it by this one door.
308    pub fn from_node_kind(kind: &Kind) -> BlockClass {
309        match kind {
310            Kind::Para => BlockClass::Paragraph,
311            Kind::Heading => BlockClass::Heading,
312            Kind::BulletList | Kind::OrderedList | Kind::TaskList => BlockClass::List,
313            Kind::ListItem | Kind::TaskListItem => BlockClass::ListItem,
314            Kind::BlockQuote => BlockClass::Quote,
315            Kind::CodeBlock => BlockClass::Code,
316            Kind::Table => BlockClass::Table,
317            Kind::Image => BlockClass::Media,
318            // twig 2.8 folded `div`/`span`/`directive`/`element` into one
319            // `container` kind, so a `:::note` panel and a promoted `<video>`
320            // arrive here indistinguishable — telling them apart needs the
321            // node's `origin`, and the incremental walk has only this kind.
322            // `Directive` is the right answer for the case that motivates the
323            // class (nothing else draws a tinted panel) and a harmless one for
324            // the rest: `BlockClass` is descriptive and core never branches on
325            // it. The one case where it was actively wrong — a promoted
326            // `<video>`, which would have been handed to a frontend as something
327            // to draw a fenced-div panel around — is corrected by
328            // [`label_media_boundaries`] once the rows are final, along the same
329            // door as a block image. Anything else that must be exact reads
330            // [`container_is_directive`] off a real node.
331            Kind::Container => BlockClass::Directive,
332            Kind::ThematicBreak => BlockClass::Rule,
333            Kind::Footnote => BlockClass::Footnote,
334            _ => BlockClass::Other,
335        }
336    }
337}
338
339/// The name and attributes a leaf directive's placeholder row carries, so a
340/// frontend that knows the host app's vocabulary can paint the real thing —
341/// an embedded page for diaryx's `::embed{src=…}`, a generated table of
342/// contents for a `::toc`, and the plain `⧉ name` label for one it doesn't
343/// know. The peer of [`MediaMark`], and plain strings for the same reason: they
344/// survive the row shuffling of [`BlockCache`] reuse and [`build_spliced`].
345#[derive(Clone, Debug, PartialEq, Eq)]
346pub struct DirectiveMark {
347    /// The directive's type — `embed`, `toc`, `vis` — with no leading colons.
348    /// Core is agnostic of what it means: the vocabulary is the host app's.
349    pub name: String,
350    /// Its `{…}` attributes as `(key, value)` pairs in source order. A bare
351    /// attribute (`{public}`) has a `None` value, the way twig reports it.
352    pub attrs: Vec<(String, Option<String>)>,
353    /// The directive's `[label]` text, flattened from its inline children, or
354    /// empty when it has none. Also what the placeholder label shows.
355    pub label: String,
356    /// How many visual rows this directive reserves — the label row plus blank
357    /// filler rows below it, so a frontend painting something real has the
358    /// vertical room. `1` is the bare placeholder, and the only value core
359    /// produces today: unlike an image (whose height a terminal frontend
360    /// measures and reports back), nothing has told core how tall an embed is.
361    /// A pixel-laid-out GUI sets its own height regardless.
362    pub rows: usize,
363}
364
365/// What a block-level media placeholder actually is, so a frontend knows which
366/// widget to build over the reserved rows: a raster, a movie player, or a
367/// transport with no picture at all. Core classifies and stops there — it opens
368/// nothing, so this is a statement about the *markup*, not about a file it has
369/// verified exists or can decode.
370#[derive(Clone, Copy, Debug, PartialEq, Eq)]
371pub enum MediaKind {
372    /// A `![](…)` / `<img>` / `<picture>` — a still picture.
373    Image,
374    /// An HTML `<video>`. Markdown and Djot spell no video of their own, so this
375    /// only ever arrives through `html_elements` promotion (or a `::video{…}`
376    /// directive a host app maps itself, which core reports as a directive).
377    Video,
378    /// An HTML `<audio>` — a transport with no picture, so a frontend gives it a
379    /// fixed control height rather than measuring an aspect ratio.
380    Audio,
381}
382
383/// Which of the two caret homes a block media has — see
384/// [`VisualMap::block_media_stop`].
385#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum MediaStop {
387    /// The stop in front of the picture. What is typed here belongs above it.
388    Before,
389    /// The stop just past it. What is typed here belongs below it.
390    After,
391}
392
393impl MediaKind {
394    /// The emoji a plain surface prefixes the placeholder label with — the
395    /// `🖼`/`🎬`/`🔊` that makes the row read as *a thing* rather than as text.
396    fn sigil(self) -> char {
397        match self {
398            MediaKind::Image => '🖼',
399            MediaKind::Video => '🎬',
400            MediaKind::Audio => '🔊',
401        }
402    }
403}
404
405/// The destination and label a block-level media placeholder row carries, so a
406/// capable frontend can resolve and paint the real thing. Plain strings (no
407/// source offsets), so they survive the row shuffling of [`BlockCache`] reuse
408/// and [`build_spliced`] untouched — see [`VRow::media`].
409#[derive(Clone, Debug, PartialEq, Eq)]
410pub struct MediaMark {
411    /// Whether this is a picture, a movie, or a sound — which widget the
412    /// frontend builds over the reserved rows.
413    pub kind: MediaKind,
414    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
415    /// the AST. A frontend resolves a relative path against the document's
416    /// directory itself; core holds no I/O.
417    ///
418    /// Empty is possible and legal for a `<video>`/`<audio>`, which may carry no
419    /// `src` of its own and name its candidates in child `<source>`s instead —
420    /// unlike an `<img>`, whose `src` *is* the picture. A frontend with an empty
421    /// destination takes its URL from [`sources`](MediaMark::sources).
422    pub destination: String,
423    /// A `<picture>`'s theme/media alternatives, in document order, when this
424    /// block image came from one; empty for a plain `![](…)` / bare `<img>`. Each
425    /// is a `<source>`'s media query + candidate URL(s); a frontend that knows its
426    /// theme picks the first whose media matches and falls back to [`destination`]
427    /// (the `<img>`). Core keeps them verbatim and picks nothing — it has no theme.
428    ///
429    /// [`destination`]: MediaMark::destination
430    pub sources: Vec<MediaSource>,
431    /// The media's alt text (its rendered inline children, flattened), or empty
432    /// when it has none. Also what the placeholder label shows. For a `<video>`/
433    /// `<audio>` this is the element's own text content — the "your browser does
434    /// not support…" fallback, which doubles as its accessible name.
435    pub alt: String,
436    /// A `<video poster="…">`'s still frame, verbatim, or empty when there is
437    /// none (and always empty for an image or audio). It is an *image*
438    /// destination, so a frontend already able to draw a picture can show it
439    /// before the movie loads — or in place of one it can't play at all.
440    pub poster: String,
441    /// How many visual rows this media reserves — the placeholder label row plus
442    /// the blank filler rows below it, so a frontend that paints a real raster has
443    /// the vertical room to draw it. `1` is the bare placeholder (a frontend that
444    /// can't draw pictures, or an image it couldn't resolve). A terminal frontend
445    /// asks for as many rows as the fitted picture is tall; the pixel-laid-out GUI
446    /// ignores this and sets its own row height, so it always leaves it `1`. The
447    /// count comes from the frontend (via [`crate::Doc::set_media_rows`]) because
448    /// core does no I/O and can't measure the image itself. See [`VRow::media`].
449    pub rows: usize,
450}
451
452/// One `<source>` under a `<picture>`, `<video>`, or `<audio>`: a candidate URL
453/// plus whichever of the two things HTML lets a `<source>` be chosen by — a
454/// media query (`<picture>`) or a MIME type (`<video>`/`<audio>`). Verbatim from
455/// the AST: core carries the alternatives and resolves none of them, having
456/// neither a theme nor a codec list to judge them by.
457///
458/// The two spellings are normalised onto one field. `<picture>` writes
459/// `srcset`, `<video>`/`<audio>` write `src`; both land in
460/// [`srcset`](MediaSource::srcset), since a frontend wants the URL either way
461/// and only `<picture>` ever uses the descriptor syntax.
462#[derive(Clone, Debug, PartialEq, Eq)]
463pub struct MediaSource {
464    /// The `<source media="…">` query, verbatim (`"(prefers-color-scheme: dark)"`),
465    /// or empty for a `<source>` with no `media` (an unconditional override, and
466    /// the norm for `<video>`/`<audio>`, which pick by codec rather than theme).
467    pub media: String,
468    /// The candidate URL(s): a `<picture>`'s `srcset` verbatim — one URL, or a
469    /// comma-separated candidate list with `1x`/`2x`/width descriptors — or a
470    /// `<video>`/`<audio>` `<source>`'s plain `src`. A frontend takes the first
471    /// URL token; the theme and codec cases both only ever need that.
472    pub srcset: String,
473    /// The `<source type="…">` MIME type (`"video/webm"`), verbatim, or empty
474    /// when the `<source>` declares none. How a `<video>`/`<audio>` frontend
475    /// picks a candidate it can actually decode; a `<picture>`'s sources
476    /// normally leave it empty and are chosen by [`media`](MediaSource::media).
477    pub mime: String,
478}
479
480/// The rendered document plus the offset⇄position mapping the caret rides on.
481#[derive(Clone, Default)]
482pub struct VisualMap {
483    /// The document's **default monospace rendering** — one [`VRow`] of glyphs
484    /// per visual line, tables spelled with box-drawing borders (`│ ─ ┌┬┐…`) and
485    /// cells padded to whole character-cell columns. Any monospace surface can
486    /// draw these verbatim, so a consumer gets a working view for free: the TUI
487    /// paints them as-is, and a five-line plain-text dump would too.
488    ///
489    /// It's a *default*, not the only truth. A frontend with its own geometry —
490    /// a proportional GUI — lays text out in its own units, and for a table
491    /// skips the box-drawn rows named by [`TableInfo::rows_span`] and draws from
492    /// the structural [`TableInfo`] instead. The box glyphs live here rather than
493    /// in a frontend precisely because they *are* a renderable default: unlike a
494    /// colour (a role each surface must map to its own palette — see
495    /// [`crate::style`]), `┌─┐` is finished text that needs no interpretation.
496    pub rows: Vec<VRow>,
497    /// The first source offset that is actually rendered — the caret floor for
498    /// the WYSIWYG view. Non-zero when a leading `metadata` block (YAML/TOML
499    /// frontmatter) is skipped: the frontmatter is preserved in the source and
500    /// editable in the source view, but hidden and unreachable here, so the
501    /// caret and selection can't wander into it (and copy won't grab it).
502    pub content_start: usize,
503    /// Every offset the caret may rest at, ascending and deduplicated: each
504    /// row's stop glyphs plus the row's own end (the "after the last character"
505    /// spot every line needs). Decoration contributes nothing.
506    ///
507    /// Left/Right read this instead of walking the grid, because the grid isn't
508    /// laid out in offset order: a table with wrapped cells puts column 1's
509    /// second line *below* column 2's first, so "the next stop rightward" and
510    /// "the next stop in the document" part ways. Following the document is what
511    /// a caret means — and on every row that *is* in order the two agree anyway,
512    /// so nothing else has to change.
513    stops: Vec<usize>,
514    /// The caret's second home at the end of every hidden inline mark: the
515    /// offset where the mark's content ends, one byte before its closing
516    /// delimiter — ascending and deduplicated, from every row's
517    /// [`VRow::mark_ends`].
518    ///
519    /// With delimiters hidden, `**bold** tail` draws one spot after the `d`
520    /// and the source has two offsets for it: the content end (inside the
521    /// mark, where typing extends the bold) and the byte past the `**` (where
522    /// typing leaves it). Only the second is a glyph's offset, so only it was
523    /// a stop, and a caret asked to rest at the first was snapped a whole
524    /// character back onto the `d` — a drag over `bold` came back one letter
525    /// short. The delete and backspace paths already settle the caret on the
526    /// content end as its natural home there
527    /// ([`crate::Doc::settle_inside_close_delims`]); this makes it one the
528    /// caret can be placed at and step onto too.
529    ///
530    /// Kept apart from [`stops`](Self::stops) rather than merged in, because
531    /// the two lists answer different questions. A stop with no glyph is
532    /// invisible to a walk that pairs stops with characters — a system text
533    /// input counting `position(from:offset:)` steps against the text it was
534    /// shown would drift a character at every mark — and to word motion, which
535    /// classifies a stop by the source byte under it (a `*`). So
536    /// [`stop_after`](Self::stop_after) and its kin walk the glyph stops alone,
537    /// and only the places a caret *rests* — snapping, resting checks, and
538    /// Left/Right — read both.
539    mark_ends: Vec<usize>,
540    /// Every table in the document, in order, described structurally rather than
541    /// drawn — see [`TableInfo`] for why both exist.
542    pub tables: Vec<TableInfo>,
543    /// Every fenced/indented code block, in order, as the range of [`rows`] it
544    /// occupies — a frontend draws one bordered, tinted box around each and
545    /// scrolls it horizontally rather than wrapping. Derived from the per-row
546    /// [`VRow::code`] flag once the rows are final (so it survives incremental
547    /// row reuse), the same way [`collect_stops`] derives the stop table.
548    ///
549    /// [`rows`]: VisualMap::rows
550    pub code_blocks: Vec<CodeBlockInfo>,
551    /// Every block-level image in the document, in order — one per placeholder
552    /// row a frontend replaces with a real picture. Derived from the per-row
553    /// [`VRow::media`] mark once the rows are final (so it survives incremental
554    /// row reuse), the same way [`code_blocks`](VisualMap::code_blocks) is
555    /// derived from [`VRow::code`].
556    pub media: Vec<MediaInfo>,
557    /// Every **leaf** directive in the document, in order — one per placeholder
558    /// row a frontend may replace with whatever the host app's vocabulary makes
559    /// of it. Derived from the per-row [`VRow::leaf_directive`] mark once the
560    /// rows are final, exactly as [`media`](VisualMap::media) is.
561    pub directives: Vec<DirectiveInfo>,
562    /// Every formula standing as a picture in this map, in row order — each
563    /// inline atom and each display block's placeholder. A frontend that
564    /// paints pictures typesets each one's TeX and draws it over the glyph or
565    /// the rows named. Derived from the per-row [`VRow::math`] marks once the
566    /// rows are final, exactly as [`media`](VisualMap::media) is.
567    ///
568    /// A formula on the revealed line is not here: there it is its own TeX,
569    /// drawn as code, and nothing stands in for it.
570    pub math: Vec<MathInfo>,
571    /// Every named font family this map's glyphs are set in, by the
572    /// [`FaceId`] they carry — the side table that lets [`Style`] stay `Copy`
573    /// while a family name stays a `String`.
574    ///
575    /// Not derived from the rows the way [`code_blocks`](Self::code_blocks) is,
576    /// because the name is not on the rows: it is interned as the walker meets
577    /// the attribute. So each of the three build paths assembles it from what
578    /// it actually walked — a fresh build from its own walk, a cached build
579    /// from each block's walk or the names its cache entry stored, a splice
580    /// from the previous map's table plus the one block it re-rendered. A
581    /// [`FaceId`] is derived from the name rather than being an index, which is
582    /// what makes those three agree glyph for glyph; see the type's note.
583    faces: FaceTable,
584    /// The visible text tabulated over the stops — see [`Spelling`]. Derived
585    /// on the first lookup that asks for it rather than by the build paths,
586    /// since a map that is only ever drawn never needs it, and a splice
587    /// would otherwise have to patch it the way it patches the stops.
588    spelling: OnceLock<Spelling>,
589}
590
591/// The visible text ([`VisualMap::visible_text`]) as a table over the stops:
592/// for stop `i`, the character the text spells it with — `None` for the
593/// `'\n'` of a stop that draws no glyph — and the UTF-16 length of the text
594/// before it. A UTF-16 index and a stop then find each other by binary
595/// search, where they used to find each other by walking every character of
596/// the document from the top: a frontend converts an `NSRange` end per
597/// selection change and per misspelled word, and each conversion was a whole
598/// document's work.
599///
600/// Built once per map and never maintained. The stops are private and fixed
601/// for the map's life; the rows only lend the character each stop draws, and
602/// a frontend that reshapes the rows after the build (the terminal inserts
603/// blank filler rows) neither changes those characters nor asks this.
604#[derive(Clone, Default)]
605struct Spelling {
606    /// Parallel to [`VisualMap::stops`].
607    chars: Vec<Option<char>>,
608    /// One longer than `chars`: `utf16[i]` is the UTF-16 length of the text
609    /// before stop `i`, and the last entry the length of the whole text.
610    utf16: Vec<usize>,
611}
612
613impl VisualMap {
614    pub fn num_rows(&self) -> usize {
615        self.rows.len()
616    }
617
618    /// The family name a glyph's [`FaceRef::Named`] stands for, or `None` for
619    /// an id from another map — which a frontend draws in the theme's body
620    /// face, as it draws a family it cannot resolve.
621    pub fn face_name(&self, id: FaceId) -> Option<&str> {
622        self.faces.name(id)
623    }
624
625    /// Every named family this map draws — how a frontend warms a font cache
626    /// before it lays a frame out. See [`faces`](Self::faces).
627    ///
628    /// [`faces`]: VisualMap::faces
629    pub fn faces(&self) -> &FaceTable {
630        &self.faces
631    }
632
633    /// The width of `row` in display columns — the rightmost column its caret
634    /// can occupy, and so what a goal column is clamped to on the way in.
635    pub fn row_width(&self, row: usize) -> usize {
636        self.rows.get(row).map_or(0, |r| r.width())
637    }
638
639    /// The screen `(row, col)` for a source offset — where to draw the caret:
640    /// the *nearest* stop at or past `off`. Snaps a hidden offset (inside a
641    /// delimiter) to the next visible glyph, and never resolves onto decoration
642    /// (a table border, a cell's padding), which is drawn but holds no caret.
643    ///
644    /// "Nearest" rather than "the first one found" because a table's wrapped
645    /// cells put rows slightly out of offset order: scanning top to bottom, the
646    /// second line of column 1 comes *after* the first line of column 2 but
647    /// holds smaller offsets. Where rows are in order the two rules agree.
648    ///
649    /// A soft wrap is the one place two rows want the same offset: the row above
650    /// ends where the row below opens, the space the wrap ate being drawn on the
651    /// row above and the offset past it being the row below's first character.
652    /// It resolves *downstream*, to the row that character is on — the row
653    /// above's last column is a phantom, a place the caret can be drawn but
654    /// never sent, and resolving upstream into it is what pinned Down at the
655    /// first wrap of a paragraph: it aimed at the row below's column 0, landed
656    /// on the offset it already had, and read that back as the row above's end.
657    ///
658    /// The walk is over the rows, not their text: a row before `off` is
659    /// dismissed by looking at where it opens and where it reaches — its first
660    /// stop and its last — rather than at every glyph between, so the cost of
661    /// a lookup mid-document is a few hundred rows' worth of two glyphs each,
662    /// and the one row that holds the answer is the only one read through.
663    /// It used to read every row through, and worse: the row's end candidate
664    /// was built eagerly, and building it measured the row's width, which
665    /// segments the row's whole text into grapheme clusters — so every row
666    /// before `off` paid a full cluster walk to learn it held nothing, and a
667    /// document of long paragraphs paid milliseconds per caret placement.
668    ///
669    /// Not a binary search, though the rows' opening stops ascend. A table's
670    /// wrapped cells put several rows before the one an offset opens on that
671    /// can still hold it, and `end_src` does not ascend across those rows at
672    /// all, so a search would need a prefix table over the rows — and
673    /// [`rows`](Self::rows) is public, reshaped by a frontend after the build
674    /// (the terminal inserts filler rows under a heading), which is exactly
675    /// what a table over it could not survive. The walk needs no table.
676    pub fn pos_of_offset(&self, off: usize) -> (usize, usize) {
677        // (src, row, the glyph — or `None` for the caret past the row's end)
678        let mut best: Option<(usize, usize, Option<usize>)> = None;
679        for (r, row) in self.rows.iter().enumerate() {
680            if row.decoration {
681                continue;
682            }
683            // A row's *first* stop never decreases from one row to the next —
684            // true even across a table's wrapped cells, since a cell's lines run
685            // downward. So once a row opens past the best found so far, no later
686            // row can beat it and the scan stays proportional to `off`.
687            let open = row
688                .glyphs
689                .iter()
690                .find(|g| g.stop)
691                .map_or(row.end_src, |g| g.src);
692            if best.is_some_and(|b| open > b.0) {
693                break;
694            }
695            // Offsets ascend *within* a row, so its last stop or its end is as
696            // far as it reaches: a row that reaches short of `off` has nothing
697            // to offer, and says so from its two ends.
698            let reach = row
699                .glyphs
700                .iter()
701                .rev()
702                .find(|g| g.stop)
703                .map_or(row.end_src, |g| g.src.max(row.end_src));
704            if reach < off {
705                continue;
706            }
707            // And so its first stop at or past `off` is the best it has.
708            let cand = row
709                .glyphs
710                .iter()
711                .enumerate()
712                .find(|(_, g)| g.stop && g.src >= off)
713                .map(|(i, g)| (g.src, r, Some(i)))
714                .or_else(|| (row.end_src >= off).then_some((row.end_src, r, None)));
715            // `<=`, so a tie goes to the later row: the only offset two rows
716            // both hold is a wrap boundary, and it belongs to the row below.
717            if let Some(c) = cand
718                && best.is_none_or(|b| c.0 <= b.0)
719            {
720                best = Some(c);
721            }
722        }
723        match best {
724            Some((_, r, Some(i))) => (r, self.rows[r].col_of_glyph(i)),
725            Some((_, r, None)) => (r, self.rows[r].width()),
726            None => {
727                let r = self.last_stop_row();
728                (r, self.row_width(r))
729            }
730        }
731    }
732
733    /// The rows a source range occupies, inclusive: `(first, last)`.
734    ///
735    /// A *different question* from [`pos_of_offset`](Self::pos_of_offset), which
736    /// is why it can't be spelled with two calls to it. That one answers "where
737    /// does the caret go", and for a caret its forward snap is right — an offset
738    /// inside a hidden delimiter has no column of its own, so the caret belongs
739    /// at the next visible glyph, wherever that turns out to be. This one asks
740    /// "which rows does this block cover", and there the snap is a trap: a
741    /// footnote whose body *ends* in a link (`[^2]: [title](url)`) has a last
742    /// byte inside the hidden destination, so `pos_of_offset(end - 1)` walked
743    /// clean off the note's row and landed on the next note's — and a peek
744    /// slicing `first..=last` out of the frame drew two notes where the reader
745    /// asked for one. Every block ending in a link, an image, or any trailing
746    /// hidden markup had the same fault; only a block ending in visible text
747    /// (which is what the tests happened to use) did not.
748    ///
749    /// `row.end_src` is no help either: it is where the *rendered* text of a row
750    /// ends, not how far into the source the block reaches, and redefining it
751    /// would move every end-of-line caret.
752    ///
753    /// So the last row is found by asking which rows *open* before the range
754    /// does, rather than by mapping its last byte: a row belongs to the range
755    /// when its first caret stop lies before `range.end`. Decoration is skipped
756    /// (a drawn gap between blocks is not part of either), and the answer is
757    /// never shorter than one row — a range whose every byte is hidden still
758    /// covers the row it started on.
759    pub fn row_range_for(&self, range: Range<usize>) -> (usize, usize) {
760        if self.rows.is_empty() {
761            return (0, 0);
762        }
763        let first = self.pos_of_offset(range.start).0;
764        let mut last = first;
765        for (r, row) in self.rows.iter().enumerate().skip(first) {
766            if row.decoration {
767                continue;
768            }
769            let open = row
770                .glyphs
771                .iter()
772                .find(|g| g.stop)
773                .map_or(row.end_src, |g| g.src);
774            if open >= range.end {
775                // A row's first stop never decreases from one row to the next —
776                // the invariant `pos_of_offset` breaks on, true even across a
777                // table's wrapped cells — so nothing below can be in range.
778                break;
779            }
780            last = r;
781        }
782        (first, last)
783    }
784
785    /// The source offset of the task checkbox drawn at `(row, col)`, or `None`
786    /// when that cell holds no box — the hit-test a frontend runs on a click
787    /// before treating it as a tick rather than a caret placement.
788    ///
789    /// Only the box's own cells answer. Clicking an item's *text* places the
790    /// caret like any other click, so the box is a target aimed at rather than
791    /// something tripped over while editing — which is also why this is a
792    /// separate question from [`offset_of_pos`](Self::offset_of_pos) instead of
793    /// a flag on the offset it returns.
794    pub fn task_box_at(&self, row: usize, col: usize) -> Option<usize> {
795        let r = self.rows.get(row)?;
796        self.task_box_at_glyph(row, r.glyph_at_col(col)?)
797    }
798
799    /// [`task_box_at`](Self::task_box_at) keyed by glyph index rather than
800    /// display column — for a frontend that shapes its own rows (the GUI) and so
801    /// resolves a click to a glyph before it ever has a column.
802    pub fn task_box_at_glyph(&self, row: usize, glyph: usize) -> Option<usize> {
803        let r = self.rows.get(row)?;
804        r.task?;
805        let g = r.glyphs.get(glyph)?;
806        (g.style.role == Role::ListMarker).then_some(g.src)
807    }
808
809    /// The source offset for a screen `(row, col)` — where a click or a
810    /// visual-space move lands the caret. Clicking decoration maps through its
811    /// `src`, which points at the text it decorates, so a click on a border or
812    /// on a cell's padding lands in that cell.
813    ///
814    /// The inverse of [`pos_of_offset`](Self::pos_of_offset), which it has to
815    /// agree with: `col` is a display column, and the one it names may be the
816    /// far cell of a wide glyph — [`VRow::glyph_at_col`] is where that lands.
817    pub fn offset_of_pos(&self, row: usize, col: usize) -> usize {
818        let Some(r) = self.rows.get(row) else {
819            // A click or drag below the last row — a short document with empty
820            // space under it, dragged into to extend a selection. Land on the
821            // document's last caret stop (its end), not offset 0: jumping the
822            // caret to the top is the wrong direction, and 0 isn't even a stop
823            // when the document opens on hidden frontmatter or a `# ` marker, so
824            // returning it would leave the caret where it draws in one place and
825            // types in another (`move_to` would then clamp it onto the unhomeable
826            // frontmatter floor). `None` only for a document with no stops at all
827            // (empty), where the caret has nowhere to be but 0.
828            return self.stops.last().copied().unwrap_or(0);
829        };
830        match r.glyph_at_col(col).and_then(|i| r.glyphs.get(i)) {
831            // A glyph that holds no caret is clickable, but where it points
832            // isn't always somewhere the caret can be: the blank gap between two
833            // paragraphs stands at an offset that belongs to neither of them,
834            // and the tail of a grapheme cluster stands inside a character.
835            // Land on the nearest real stop instead of handing back an offset
836            // that looks like the gap but types into the paragraph above.
837            Some(g) if !g.stop => self.nearest_stop(g.src),
838            Some(g) => g.src,
839            // A row's end is a stop by construction — unless the row is
840            // decoration, which contributes none.
841            None if r.decoration => self.nearest_stop(r.end_src),
842            None => r.end_src,
843        }
844    }
845
846    /// Which of a block media's two caret homes `off` is, or `None` for every
847    /// other offset in the document.
848    ///
849    /// [`block_media`](Builder::block_media) gives a block-level image, video, or
850    /// audio exactly two stops — one in front of it and one just past it — and
851    /// nothing inside the markup. Both are ordinary offsets to everything else in
852    /// core, but they are the two places where inserting text would *dissolve the
853    /// picture*: `![](p.png)` with anything typed against it is no longer a block
854    /// image but a paragraph with an inline one, and the frontend that was
855    /// painting a photo there paints a text run instead. A caller that is about to
856    /// insert asks this so it can open a paragraph first — see
857    /// [`Doc::insert`](crate::Doc::insert).
858    ///
859    /// An *inline* image reports `None`: it has no placeholder row and no stops of
860    /// its own, and typing beside one is ordinary editing.
861    ///
862    /// Answers with the media's own source span as well, since a caller that has
863    /// to keep the picture whole usually has to address it — [`Doc::backspace`]
864    /// takes the picture out in one piece rather than nibbling a byte off its
865    /// markup, which is the same dissolution from the other side.
866    ///
867    /// [`Doc::backspace`]: crate::Doc::backspace
868    pub fn block_media_stop(&self, off: usize) -> Option<(MediaStop, Range<usize>)> {
869        for m in &self.media {
870            let Some(row) = self.rows.get(m.rows_span.start) else {
871                continue;
872            };
873            // Every glyph of the `🖼 alt` label maps to the media's start offset;
874            // the row's end is past its markup. Read the start off the label
875            // rather than the first glyph, which on a quoted or listed picture is
876            // the block prefix and points at the gutter.
877            let Some(start) = row
878                .glyphs
879                .iter()
880                .find(|g| g.style.role == Role::Image)
881                .map(|g| g.src)
882            else {
883                continue;
884            };
885            if off == start {
886                return Some((MediaStop::Before, start..row.end_src));
887            }
888            if off == row.end_src {
889                return Some((MediaStop::After, start..row.end_src));
890            }
891        }
892        None
893    }
894
895    /// Whether `off` is a table's trailing caret stop — the one home past a
896    /// table's last cell, at the block's own end ([`TableInfo::end_src`]).
897    ///
898    /// The table's peer of [`block_media_stop`](Self::block_media_stop)'s
899    /// `After`: text inserted at that offset joins the table's last source
900    /// line, and a line glued under a table is a row of it (`| 1 | 2 |x`), so
901    /// a caller about to insert there opens a paragraph first — see
902    /// [`Doc::insert`](crate::Doc::insert). Nothing else about the offset is
903    /// special: it is where Down from the last row lands and where a click in
904    /// the blank space under a trailing table lands.
905    pub fn table_end_stop(&self, off: usize) -> bool {
906        self.tables.iter().any(|t| t.end_src == off)
907    }
908
909    /// Snap `off` to the nearest caret stop — the funnel a frontend that
910    /// hit-tests pixels straight to a source offset must run its result through.
911    /// A click or drag can land in the blank gap a paragraph break is drawn with,
912    /// or inside a hidden delimiter; both are offsets the caret can't rest at, so
913    /// resting there would draw the caret in one place and type in another. This
914    /// settles it on a real caret home instead. Idempotent on an offset that is
915    /// already a stop — the `(row, col)` click path already snaps this way inside
916    /// [`offset_of_pos`](Self::offset_of_pos), and this gives the pixel path the
917    /// same guarantee. Returns `off` unchanged only for an empty document (no
918    /// stops at all).
919    pub fn snap_to_stop(&self, off: usize) -> usize {
920        self.nearest_stop(off)
921    }
922
923    /// The caret stop nearest `off`, preferring the one before it when `off`
924    /// falls exactly between two. Returns `off` unchanged if there are no stops
925    /// at all (an empty document). A mark's content end counts: it is a place
926    /// the caret rests, and the one a drag ending on a marked word means.
927    fn nearest_stop(&self, off: usize) -> usize {
928        let before = Self::last_at_or_before(&self.stops, off)
929            .max(Self::last_at_or_before(&self.mark_ends, off));
930        let after = match (
931            Self::first_at_or_after(&self.stops, off),
932            Self::first_at_or_after(&self.mark_ends, off),
933        ) {
934            (Some(a), Some(b)) => Some(a.min(b)),
935            (a, b) => a.or(b),
936        };
937        match (before, after) {
938            (Some(b), Some(a)) if off - b <= a - off => b,
939            (_, Some(a)) => a,
940            (Some(b), None) => b,
941            (None, None) => off,
942        }
943    }
944
945    /// The glyph stop nearest `off` — [`nearest_stop`](Self::nearest_stop)
946    /// for a walk that pairs stops with characters, which a mark's content
947    /// end has none of. A caret resting on one resolves to the glyph stop
948    /// drawn at the same spot, the one just past the hidden delimiter, so the
949    /// text a system input is shown from there and the steps it counts agree.
950    pub fn snap_to_glyph_stop(&self, off: usize) -> usize {
951        if self.mark_ends.binary_search(&off).is_ok()
952            && let Some(next) = Self::first_at_or_after(&self.stops, off)
953        {
954            return next;
955        }
956        let before = Self::last_at_or_before(&self.stops, off);
957        let after = Self::first_at_or_after(&self.stops, off);
958        match (before, after) {
959            (Some(b), Some(a)) if off - b <= a - off => b,
960            (_, Some(a)) => a,
961            (Some(b), None) => b,
962            (None, None) => off,
963        }
964    }
965
966    /// The last of `sorted` at or before `off`, if any.
967    fn last_at_or_before(sorted: &[usize], off: usize) -> Option<usize> {
968        let i = sorted.partition_point(|&s| s <= off);
969        i.checked_sub(1).map(|i| sorted[i])
970    }
971
972    /// The first of `sorted` at or after `off`, if any.
973    fn first_at_or_after(sorted: &[usize], off: usize) -> Option<usize> {
974        let i = sorted.partition_point(|&s| s < off);
975        sorted.get(i).copied()
976    }
977
978    /// The next place the caret rests past `off` — the next glyph stop or the
979    /// next mark's content end, whichever comes first. What Right walks:
980    /// leaving `**bold**` from the `d` is two presses, one onto the end of the
981    /// bold (still bold, the toolbar lit) and one past its delimiter, at the
982    /// same spot on screen. [`stop_after`](Self::stop_after) is the walk that
983    /// skips the first, for every caller that pairs stops with characters.
984    pub fn caret_stop_after(&self, off: usize) -> Option<usize> {
985        match (
986            self.stop_after(off),
987            Self::first_at_or_after(&self.mark_ends, off + 1),
988        ) {
989            (Some(a), Some(b)) => Some(a.min(b)),
990            (a, b) => a.or(b),
991        }
992    }
993
994    /// The previous place the caret rests before `off` — the mirror of
995    /// [`caret_stop_after`](Self::caret_stop_after), what Left walks.
996    pub fn caret_stop_before(&self, off: usize) -> Option<usize> {
997        self.stop_before(off).max(
998            off.checked_sub(1)
999                .and_then(|o| Self::last_at_or_before(&self.mark_ends, o)),
1000        )
1001    }
1002
1003    /// Whether the caret can occupy `row` at all: decoration rows (a table's
1004    /// border rules) are stepped over by vertical motion.
1005    pub fn row_is_navigable(&self, row: usize) -> bool {
1006        self.rows.get(row).is_some_and(|r| !r.decoration)
1007    }
1008
1009    /// The first offset the caret can rest at on `row` — its first stop, or the
1010    /// row's own end when it holds no text (an empty paragraph). `None` for a
1011    /// decoration row, which holds no caret at all.
1012    ///
1013    /// Not `offset_of_pos(row, 0)`: column 0 of a quoted or listed row is the
1014    /// gutter, and a gutter's `src` points at the *block* it opens, so the stop
1015    /// nearest it is the one on the block's first row rather than on this one.
1016    /// Which is right for a click — the gutter decorates the whole block — and
1017    /// wrong for Home, whose whole question is where *this* row starts.
1018    pub fn row_start(&self, row: usize) -> Option<usize> {
1019        let r = self.rows.get(row).filter(|r| !r.decoration)?;
1020        Some(
1021            r.glyphs
1022                .iter()
1023                .find(|g| g.stop)
1024                .map_or(r.end_src, |g| g.src),
1025        )
1026    }
1027
1028    /// The last row the caret can rest on — the fallback when an offset is past
1029    /// everything rendered (a table's bottom border must not swallow the caret).
1030    fn last_stop_row(&self) -> usize {
1031        (0..self.rows.len())
1032            .rev()
1033            .find(|&r| self.row_is_navigable(r))
1034            .unwrap_or(0)
1035    }
1036
1037    /// The nearest row above `row` the caret can occupy, skipping decoration.
1038    pub fn navigable_above(&self, row: usize) -> Option<usize> {
1039        (0..row.min(self.rows.len()))
1040            .rev()
1041            .find(|&r| self.row_is_navigable(r))
1042    }
1043
1044    /// The nearest row below `row` the caret can occupy, skipping decoration.
1045    pub fn navigable_below(&self, row: usize) -> Option<usize> {
1046        ((row + 1)..self.rows.len()).find(|&r| self.row_is_navigable(r))
1047    }
1048
1049    /// The caret stop just before `off` — one press of Left. `None` at the
1050    /// first stop in the document.
1051    ///
1052    /// Runs of decoration (a table border, a cell's alignment padding) are
1053    /// stepped over in a single press: they hold no stop, so they aren't in the
1054    /// table to land on.
1055    pub fn stop_before(&self, off: usize) -> Option<usize> {
1056        let i = self.stops.partition_point(|&s| s < off);
1057        i.checked_sub(1).map(|i| self.stops[i])
1058    }
1059
1060    /// The caret stop just after `off` — one press of Right. `None` at the last
1061    /// stop in the document.
1062    pub fn stop_after(&self, off: usize) -> Option<usize> {
1063        let i = self.stops.partition_point(|&s| s <= off);
1064        self.stops.get(i).copied()
1065    }
1066
1067    /// The first caret stop at or past `off` — where the caret at a hidden
1068    /// offset is *drawn*, and so where a rightward walk over the rendered text
1069    /// starts from.
1070    pub fn stop_at_or_after(&self, off: usize) -> Option<usize> {
1071        let i = self.stops.partition_point(|&s| s < off);
1072        self.stops.get(i).copied()
1073    }
1074
1075    /// The last caret stop at or before `off` — where a leftward walk starts
1076    /// from. Snapping the way the walk is headed, rather than always forward,
1077    /// is what keeps a leftward motion from ever moving the caret right.
1078    pub fn stop_at_or_before(&self, off: usize) -> Option<usize> {
1079        let i = self.stops.partition_point(|&s| s <= off);
1080        i.checked_sub(1).map(|i| self.stops[i])
1081    }
1082
1083    /// Whether the caret may rest at `off` — the invariant every motion in this
1084    /// view has to leave standing. A glyph stop, a row's end, or a hidden
1085    /// mark's content end ([`mark_ends`](Self::mark_ends)).
1086    pub fn is_stop(&self, off: usize) -> bool {
1087        self.stops.binary_search(&off).is_ok() || self.mark_ends.binary_search(&off).is_ok()
1088    }
1089
1090    /// The visible text a caret crosses walking rightward from `from` up to
1091    /// (but not including) `to` — `UITextInput.text(in:)`'s `[from, to)` in
1092    /// *this* view. A hidden inline-mark delimiter (`**`, `` ` ``, `_`, an
1093    /// escape backslash) never got a glyph in the first place — see
1094    /// [`push_text`]/[`synth`] — so it contributes nothing; what's left is
1095    /// what's drawn on screen for that span, one character per caret stop.
1096    ///
1097    /// **Exactly one character per stop** is the contract, and it is the
1098    /// system text input's, not a nicety: `UITextInput`'s tokenizer reads a
1099    /// window of this text around a tap, indexes into it by the integer
1100    /// `offset(from:to:)` reports (`distance_offset` in `leaf-ffi`, a count of
1101    /// [`stop_after`](Self::stop_after) hops), finds a word boundary at some
1102    /// character index, and hands the delta back through
1103    /// `position(from:offset:)`, which hops stops again. If the text ever
1104    /// spends a character on something that is not a stop, or a stop on
1105    /// nothing, every index past that point is off by one and the word the
1106    /// reader double-tapped comes back shifted — into the header row of a
1107    /// table, or one letter short. So a stop that draws a glyph is spelled
1108    /// as that glyph, and a stop that draws none is spelled `'\n'`:
1109    ///
1110    /// - a row's own end stop ([`VRow::end_src`]) — the caret home past a
1111    ///   paragraph's, heading's, list item's, or code line's last glyph. This
1112    ///   is also what keeps two blocks' words apart: without it the last word
1113    ///   of one paragraph and the first of the next read as one run of
1114    ///   letters (`"…edb\n\nhello\n"` came back as `"edbhello"`), and the
1115    ///   tokenizer selected across the boundary. A list item's end is a
1116    ///   row end like any other, though no blank gap row follows it.
1117    /// - a table cell's end, which [`push_table_row`] draws as the gutter
1118    ///   space before the next `│` so the caret has somewhere to stand past
1119    ///   the cell's last character. To a reader of *this* text a cell ends a
1120    ///   line: spelled as a space, a touch surface that lands a tap at a
1121    ///   word's end past the space that follows it stepped into the next
1122    ///   cell — or the next row, from the last column.
1123    ///
1124    /// A hidden mark's content end ([`mark_ends`](Self::mark_ends)) is a place
1125    /// the caret rests but not a stop the walks above count, so it has no
1126    /// character here either; `from` is snapped to the glyph stop drawn at
1127    /// the same spot first, exactly as [`snap_to_glyph_stop`] does for those
1128    /// walks. `to` is left as given, so a stop landing exactly on it is still
1129    /// excluded — the same half-open range `distance_offset`'s loop counts.
1130    ///
1131    /// [`push_table_row`]: Builder::push_table_row
1132    /// [`snap_to_glyph_stop`]: Self::snap_to_glyph_stop
1133    pub fn visible_text(&self, from: usize, to: usize) -> String {
1134        self.visible_items(from, to)
1135            .into_iter()
1136            .map(|(_, ch)| ch.unwrap_or('\n'))
1137            .collect()
1138    }
1139
1140    /// The UTF-16 length of `visible_text(from, to)` — what an `NSRange`
1141    /// location into that text is, without building the string.
1142    ///
1143    /// AppKit's `NSTextInputClient` and `NSAccessibility` speak in UTF-16
1144    /// units of *the text as the system sees it*, which for leaf is the visible
1145    /// text — delimiters hidden. A frontend reporting its selection to the
1146    /// system converts each end with this and gets back an index into the
1147    /// string `visible_text(0, end)` returns, which is exactly what the system
1148    /// will index into.
1149    pub fn visible_utf16_len(&self, from: usize, to: usize) -> usize {
1150        let (lo, hi) = self.visible_span(from, to);
1151        let utf16 = &self.spelling().utf16;
1152        utf16[hi] - utf16[lo]
1153    }
1154
1155    /// The inverse of `visible_utf16_len(0, ·)`: the source offset of the
1156    /// visible character a UTF-16 index into `visible_text(0, to)` lands on.
1157    ///
1158    /// An index inside a surrogate pair resolves to the character that owns
1159    /// it; one at or past the end of the text returns `None`, so a caller can
1160    /// substitute the document's end stop. The `\n` a row's or a cell's end
1161    /// is spelled with resolves to that end stop — a caret home, so a caller
1162    /// placing a caret there needs no snap.
1163    pub fn offset_at_visible_utf16(&self, to: usize, index: usize) -> Option<usize> {
1164        let (lo, hi) = self.visible_span(0, to);
1165        let utf16 = &self.spelling().utf16;
1166        // The stop whose text ends past the index is the one it lands on; a
1167        // stop whose text ends at or before it lies wholly before it.
1168        let target = utf16[lo] + index;
1169        let i = lo + utf16[lo + 1..=hi].partition_point(|&end| end <= target);
1170        (i < hi).then(|| self.stops[i])
1171    }
1172
1173    /// The items `visible_text` spells, in order — one per caret stop in
1174    /// `[from, to)`, keyed by the stop's source offset: the glyph it draws
1175    /// (`Some`), or `None` for a stop with no character of its own, which the
1176    /// text spells `'\n'`. See [`visible_text`](Self::visible_text) for which
1177    /// stops those are and why.
1178    fn visible_items(&self, from: usize, to: usize) -> Vec<(usize, Option<char>)> {
1179        let (lo, hi) = self.visible_span(from, to);
1180        self.stops[lo..hi]
1181            .iter()
1182            .copied()
1183            .zip(self.spelling().chars[lo..hi].iter().copied())
1184            .collect()
1185    }
1186
1187    /// The stops `visible_text(from, to)` spells, as a range into the stop
1188    /// table: from the glyph stop `from` snaps to, up to but excluding the
1189    /// first stop at or past `to`.
1190    fn visible_span(&self, from: usize, to: usize) -> (usize, usize) {
1191        let from = self.snap_to_glyph_stop(from);
1192        let lo = self.stops.partition_point(|&s| s < from);
1193        // The document's last stop is the end of the text, not a character in
1194        // it: `distance_offset` has no hop past it to pair one with.
1195        let last = self.stops.len().saturating_sub(1);
1196        let hi = self.stops.partition_point(|&s| s < to).min(last).max(lo);
1197        (lo, hi)
1198    }
1199
1200    /// The [`Spelling`] of this map's stops, tabulated on first use.
1201    fn spelling(&self) -> &Spelling {
1202        self.spelling.get_or_init(|| {
1203            // The glyph each stop draws — the first at its offset in row
1204            // order, since a media row's label glyphs all share the media's
1205            // offset and a wrapped line's end is the next line's first glyph.
1206            // Row order only follows source order outside a table's wrapped
1207            // cells (see `pos_of_offset`), which is why each glyph looks its
1208            // stop up rather than the two being walked side by side.
1209            //
1210            // Within a row offsets ascend, so a cursor into the stop table
1211            // walks forward with the row's glyphs and the whole pass is a
1212            // read of the glyphs plus one search per row — a keystroke's
1213            // first conversion pays for this, so it is kept to that. The
1214            // search is repeated only if a row's offsets step back, which
1215            // none does; the walk is correct either way.
1216            let stops = &self.stops;
1217            let mut chars: Vec<Option<char>> = vec![None; stops.len()];
1218            for row in self.rows.iter().filter(|r| !r.decoration) {
1219                let mut i = 0;
1220                let mut prev = usize::MAX;
1221                for g in row.glyphs.iter().filter(|g| g.stop) {
1222                    if prev == usize::MAX || g.src < prev {
1223                        i = stops.partition_point(|&s| s < g.src);
1224                    } else {
1225                        while i < stops.len() && stops[i] < g.src {
1226                            i += 1;
1227                        }
1228                    }
1229                    prev = g.src;
1230                    if i < stops.len() && stops[i] == g.src && chars[i].is_none() {
1231                        chars[i] = Some(g.ch);
1232                    }
1233                }
1234            }
1235            // A cell's end stop has a glyph (the gutter space) but is spelled
1236            // as a line end; the structural grid is where the cells' offsets
1237            // live.
1238            for cell in self
1239                .tables
1240                .iter()
1241                .flat_map(|t| t.grid.iter())
1242                .flat_map(|r| r.cells.iter())
1243            {
1244                if let Ok(i) = self.stops.binary_search(&cell.end) {
1245                    chars[i] = None;
1246                }
1247            }
1248            let mut utf16 = Vec::with_capacity(chars.len() + 1);
1249            utf16.push(0);
1250            for ch in &chars {
1251                let before = *utf16.last().unwrap_or(&0);
1252                utf16.push(before + ch.map_or(1, char::len_utf16));
1253            }
1254            Spelling { chars, utf16 }
1255        })
1256    }
1257}
1258
1259/// Collect the caret stops of a laid-out grid: every stop glyph's offset plus
1260/// every row's end, ascending and deduplicated. Duplicates are the norm rather
1261/// than the exception — a wrapped line's end is the same offset as the next
1262/// line's first glyph — and collapsing them is what makes one press of Left or
1263/// Right cross exactly one stop.
1264fn collect_stops(rows: &[VRow]) -> Vec<usize> {
1265    let mut stops: Vec<usize> = rows
1266        .iter()
1267        .filter(|r| !r.decoration)
1268        .flat_map(|r| {
1269            r.glyphs
1270                .iter()
1271                .filter(|g| g.stop)
1272                .map(|g| g.src)
1273                .chain(std::iter::once(r.end_src))
1274        })
1275        .collect();
1276    stops.sort_unstable();
1277    stops.dedup();
1278    stops
1279}
1280
1281/// Collect every row's [`VRow::mark_ends`] into one ascending, deduplicated
1282/// table — the peer of [`collect_stops`] for the caret's second home at the
1283/// end of a hidden mark. A mark that closes at a row's end coincides with the
1284/// row's own end stop; that offset is in both tables, and harmlessly so.
1285fn collect_mark_ends(rows: &[VRow]) -> Vec<usize> {
1286    let mut ends: Vec<usize> = rows
1287        .iter()
1288        .filter(|r| !r.decoration)
1289        .flat_map(|r| r.mark_ends.iter().copied())
1290        .collect();
1291    ends.sort_unstable();
1292    ends.dedup();
1293    ends
1294}
1295
1296/// Group the rows tagged [`VRow::code`] into one [`CodeBlockInfo`] per maximal
1297/// run — the block-level view a frontend needs to box and scroll each code
1298/// block. Two code blocks are always parted by the blank separator row a block
1299/// boundary is spelled with (never itself a code row), so a contiguous run is
1300/// exactly one block. Derived from the final rows rather than tracked through
1301/// the builder so it comes out right no matter how [`build_cached`] and
1302/// [`build_spliced`] shuffle rows around.
1303fn code_block_spans(rows: &[VRow]) -> Vec<CodeBlockInfo> {
1304    let mut blocks = Vec::new();
1305    let mut start: Option<usize> = None;
1306    for (i, row) in rows.iter().enumerate() {
1307        match (row.code, start) {
1308            (true, None) => start = Some(i),
1309            (false, Some(s)) => {
1310                blocks.push(CodeBlockInfo {
1311                    rows_span: s..i,
1312                    lang: rows[s].code_lang.clone(),
1313                });
1314                start = None;
1315            }
1316            _ => {}
1317        }
1318    }
1319    if let Some(s) = start {
1320        blocks.push(CodeBlockInfo {
1321            rows_span: s..rows.len(),
1322            lang: rows[s].code_lang.clone(),
1323        });
1324    }
1325    blocks
1326}
1327
1328/// The value of `node`'s `key` attribute, if it carries one *with* a value. A
1329/// bare attribute (`controls`, `muted`) has a `None` value and so reads as
1330/// absent here — a caller wanting presence-not-value tests the list directly.
1331/// Shared by the media element and `<source>` readers.
1332fn attr_of(node: &FlatNode, key: &str) -> Option<String> {
1333    node.attrs
1334        .iter()
1335        .find(|(k, _)| k == key)
1336        .and_then(|(_, v)| v.clone())
1337}
1338
1339/// Collect one [`MediaInfo`] per row carrying a [`VRow::media`] mark — the
1340/// block-level view a frontend needs to replace each placeholder row with a real
1341/// picture. The mark rides the block's *first* row and names how many rows the
1342/// media reserves ([`MediaMark::rows`]); the rows below it are blank
1343/// [`decoration`](VRow::decoration) fillers that hold the vertical space and no
1344/// caret. So the span runs from the marked row across those fillers. Derived from
1345/// the final rows rather than tracked through the builder so it survives however
1346/// [`build_cached`] and [`build_spliced`] shuffle rows around.
1347fn media_spans(rows: &[VRow]) -> Vec<MediaInfo> {
1348    rows.iter()
1349        .enumerate()
1350        .filter_map(|(i, row)| {
1351            row.media.as_ref().map(|m| MediaInfo {
1352                rows_span: i..i + m.rows.max(1),
1353                kind: m.kind,
1354                destination: m.destination.clone(),
1355                sources: m.sources.clone(),
1356                alt: m.alt.clone(),
1357                poster: m.poster.clone(),
1358            })
1359        })
1360        .collect()
1361}
1362
1363/// Re-label the drawn block boundaries either side of a block-level media
1364/// placeholder, so the pair a frontend spaces by names the picture.
1365///
1366/// [`BlockClass::from_node_kind`] classifies the node the walk is standing on,
1367/// and a block image is never a node of its own: [`Builder::media_only`] promotes
1368/// its *wrapper* — a `paragraph`, or the `container` a `<video>`/`<audio>`
1369/// arrives as — so the gap above a picture reported [`BlockClass::Paragraph`] and
1370/// the gap above a movie reported [`BlockClass::Directive`], the class a frontend
1371/// paints a tinted panel for. [`BlockClass::Media`] was unreachable in
1372/// consequence: the vocabulary named a kind no frontend could ever be told about.
1373///
1374/// Done as a pass over the finished rows rather than inside the walk because
1375/// only the rows know. The incremental top-level walk carries no node arena at
1376/// all (`nodes: &[]`) and can classify by kind alone, so teaching the wrapper
1377/// promotion to the whole-arena walk would label the full and incremental builds
1378/// differently — the exact drift that walk's own comment forbids. Both builds
1379/// emit the same [`VRow::media`] marks, so both reach the same answer here. The
1380/// [`media_spans`] / [`code_block_spans`] pattern.
1381///
1382/// One gap can be spelled with several rows — [`Builder::emit_separators_before`]
1383/// draws the row that closes the block above and the row that opens the block
1384/// below, with any extra blank source lines navigable between them — and gives
1385/// every one of them the same [`Boundary`]. So the walk crosses those navigable
1386/// blanks and relabels the whole run, stopping at the first row that is neither.
1387fn label_media_boundaries(rows: &mut [VRow]) {
1388    // A display formula's placeholder is promoted from its paragraph exactly
1389    // as a picture is, and its gaps are relabelled the same way, as `Math`.
1390    let spans: Vec<(Range<usize>, BlockClass)> = rows
1391        .iter()
1392        .enumerate()
1393        .filter_map(|(i, row)| {
1394            if let Some(m) = &row.media {
1395                Some((i..i + m.rows.max(1), BlockClass::Media))
1396            } else {
1397                row.math
1398                    .iter()
1399                    .find(|m| m.glyph.is_none())
1400                    .map(|m| (i..i + m.rows.max(1), BlockClass::Math))
1401            }
1402        })
1403        .collect();
1404    // A row inside one gap: a drawn boundary to relabel, or one of the navigable
1405    // blank lines sitting between two drawn ones. Anything else ends the run.
1406    fn in_gap(row: &VRow) -> bool {
1407        row.boundary.is_some() || (!row.decoration && row.glyphs.is_empty())
1408    }
1409    for (span, class) in spans {
1410        for i in (0..span.start).rev() {
1411            if !in_gap(&rows[i]) {
1412                break;
1413            }
1414            if let Some(b) = rows[i].boundary.as_mut() {
1415                b.below = class;
1416            }
1417        }
1418        for row in rows.iter_mut().skip(span.end) {
1419            if !in_gap(row) {
1420                break;
1421            }
1422            if let Some(b) = row.boundary.as_mut() {
1423                b.above = class;
1424            }
1425        }
1426    }
1427}
1428
1429/// Collect one [`DirectiveInfo`] per row carrying a [`VRow::leaf_directive`]
1430/// mark — the block-level view a frontend needs to replace each placeholder row
1431/// with whatever the directive means to it. The peer of [`media_spans`], derived
1432/// from the final rows for the same reason: it survives however [`build_cached`]
1433/// and [`build_spliced`] shuffle rows around.
1434fn directive_spans(rows: &[VRow]) -> Vec<DirectiveInfo> {
1435    rows.iter()
1436        .enumerate()
1437        .filter_map(|(i, row)| {
1438            row.leaf_directive.as_ref().map(|m| DirectiveInfo {
1439                rows_span: i..i + m.rows.max(1),
1440                name: m.name.clone(),
1441                attrs: m.attrs.clone(),
1442                label: m.label.clone(),
1443            })
1444        })
1445        .collect()
1446}
1447
1448/// Collect one [`MathInfo`] per [`VRow::math`] mark — the peer of
1449/// [`media_spans`] and [`directive_spans`], derived from the final rows for the
1450/// same reason. A block mark spans its fillers; an atom spans its own row.
1451fn math_spans(rows: &[VRow]) -> Vec<MathInfo> {
1452    rows.iter()
1453        .enumerate()
1454        .flat_map(|(i, row)| {
1455            row.math.iter().map(move |m| {
1456                let src = match m.glyph {
1457                    Some(g) => row.glyphs.get(g).map_or(row.end_src, |g| g.src),
1458                    None => row
1459                        .glyphs
1460                        .iter()
1461                        .find(|g| g.style.role == Role::Math)
1462                        .map_or(row.end_src, |g| g.src),
1463                };
1464                MathInfo {
1465                    rows_span: i..i + m.rows.max(1),
1466                    row: i,
1467                    glyph: m.glyph,
1468                    tex: m.tex.clone(),
1469                    display: m.display,
1470                    src,
1471                }
1472            })
1473        })
1474        .collect()
1475}
1476
1477/// The source range of a fenced code block's info string — everything on the
1478/// opening line past the fence (`` ```rust `` → the `rust`). `block_start` is the
1479/// code block node's `span.start`. `None` for an indented code block, which
1480/// opens with no fence to carry one. The range is empty for a fence written
1481/// bare (`` ``` `` alone), which is exactly where a language would be inserted.
1482///
1483/// A block inside a quote or a list item starts at its line's start, with the
1484/// container's marker in front of the fence — `> ```rust`, `- ```rust` — so
1485/// the marker is skipped first, and the fence's three-space indent allowance
1486/// is measured from where the container's content begins: past the marker on
1487/// the fence's own line, or, on a continuation line, from the content column
1488/// of the list item above. That is what keeps an *indented* code block inside
1489/// a list item answering `None`.
1490///
1491/// Shared by the WYSIWYG builder (to label the box) and [`crate::Doc`] (to edit
1492/// the label through a prompt), so the two agree on where the language lives.
1493pub fn code_info_span(source: &str, block_start: usize) -> Option<Range<usize>> {
1494    let rest = source.get(block_start..)?;
1495    let line_len = rest.find('\n').unwrap_or(rest.len());
1496    let line = &rest[..line_len];
1497    let (depth, quoted) = strip_quote_markers(line);
1498    let mut content = quoted;
1499    let mut listed = false;
1500    while let Some(n) = list_marker_len(&line[content..], 3) {
1501        content += n;
1502        listed = true;
1503    }
1504    let lead = leading_spaces(&line[content..]);
1505    // No marker of its own: a continuation line, whose leading spaces include
1506    // the enclosing item's indent. Only when the block owns its line — a span
1507    // that starts mid-line has had its container prefix measured off already.
1508    let at_line_start = block_start == 0 || source.as_bytes()[block_start - 1] == b'\n';
1509    let base = if listed || !at_line_start {
1510        0
1511    } else {
1512        item_content_column(&source[..block_start], depth, lead)
1513    };
1514    // A fence may be indented up to three spaces; past that it opens with a run
1515    // of the same fence character.
1516    if lead - base > 3 {
1517        return None;
1518    }
1519    let at = content + lead;
1520    let fence = line[at..].chars().next()?;
1521    if fence != '`' && fence != '~' {
1522        return None; // an indented block, not a fenced one
1523    }
1524    let fence_len = line[at..].chars().take_while(|&c| c == fence).count();
1525    let info_start = block_start + at + fence_len;
1526    Some(info_start..block_start + line_len)
1527}
1528
1529/// The spaces a line opens with.
1530fn leading_spaces(s: &str) -> usize {
1531    s.bytes().take_while(|&b| b == b' ').count()
1532}
1533
1534/// A line's block-quote markers — each `>` behind up to three spaces, with the
1535/// one space after it — as the quote depth and the byte offset past them.
1536fn strip_quote_markers(line: &str) -> (usize, usize) {
1537    let b = line.as_bytes();
1538    let (mut depth, mut i) = (0, 0);
1539    loop {
1540        let j = i + leading_spaces(&line[i..]);
1541        if j - i > 3 || b.get(j) != Some(&b'>') {
1542            return (depth, i);
1543        }
1544        depth += 1;
1545        i = j + 1 + usize::from(b.get(j + 1) == Some(&b' '));
1546    }
1547}
1548
1549/// The length of a list marker opening `s` — its indent (at most `max_lead`
1550/// spaces), a bullet or an ordinal, and the one space the item's content
1551/// starts after — or `None` when `s` opens with none.
1552fn list_marker_len(s: &str, max_lead: usize) -> Option<usize> {
1553    let b = s.as_bytes();
1554    let lead = leading_spaces(s);
1555    if lead > max_lead {
1556        return None;
1557    }
1558    let mark = match b.get(lead)? {
1559        b'-' | b'*' | b'+' => 1,
1560        c if c.is_ascii_digit() => {
1561            let digits = b[lead..].iter().take_while(|c| c.is_ascii_digit()).count();
1562            if digits > 9 || !matches!(b.get(lead + digits), Some(b'.' | b')')) {
1563                return None;
1564            }
1565            digits + 1
1566        }
1567        _ => return None,
1568    };
1569    match b.get(lead + mark) {
1570        Some(b' ') => Some(lead + mark + 1),
1571        None => Some(lead + mark),
1572        _ => None,
1573    }
1574}
1575
1576/// The content column of the list item a continuation line indented `lead`
1577/// spaces (past `depth` quote markers) sits in: the nearest item above whose
1578/// content starts at or before `lead`. `0` when a line at the margin, or a
1579/// change of quote depth, says there is no such item.
1580fn item_content_column(before: &str, depth: usize, lead: usize) -> usize {
1581    for line in before.strip_suffix('\n').unwrap_or(before).rsplit('\n') {
1582        let (d, q) = strip_quote_markers(line);
1583        let s = &line[q..];
1584        if s.trim().is_empty() {
1585            continue;
1586        }
1587        if d != depth {
1588            return 0;
1589        }
1590        let mut col = 0;
1591        while let Some(n) = list_marker_len(&s[col..], usize::MAX) {
1592            col += n;
1593        }
1594        if col > 0 && col <= lead {
1595            return col;
1596        }
1597        if col == 0 && leading_spaces(s) == 0 {
1598            return 0;
1599        }
1600    }
1601    0
1602}
1603
1604/// A fenced code block's language for display: its info string, trimmed, or
1605/// `None` when there's no fence or the fence carries no language. The trimmed
1606/// text is what a frontend labels the box with; [`code_info_span`] is what an
1607/// edit replaces.
1608pub fn code_language(source: &str, block_start: usize) -> Option<String> {
1609    let span = code_info_span(source, block_start)?;
1610    let text = source.get(span)?.trim();
1611    (!text.is_empty()).then(|| text.to_string())
1612}
1613
1614/// A horizontal rule's dash count when the map isn't wrapping to a column grid
1615/// (the GUI, which wraps at pixel width): a fixed, sane width the frontend can
1616/// paint or re-wrap, instead of a runaway count from an unbounded wrap width.
1617const UNWRAPPED_RULE_WIDTH: usize = 40;
1618
1619/// The one glyph an inline formula renders to on a surface that paints
1620/// pictures in a line — what a plain surface handed such a map would show.
1621/// One column wide, so a column-wrapped build's arithmetic still holds; the
1622/// frontend that asked for atoms draws the picture as wide as it is.
1623const MATH_ATOM: char = '∑';
1624
1625/// What the surface a map is built for can paint, and how tall its pictures
1626/// came out — the things about a frontend that change the rows core lays
1627/// down, gathered from the frontend by [`crate::Doc`] and threaded into every
1628/// build. The defaults are the plain surface: nothing painted in a line, every
1629/// picture a one-row placeholder, which is what every test that passes
1630/// `Surface::default()` gets and what every build got before there was one.
1631#[derive(Clone, Debug, Default, PartialEq, Eq)]
1632pub struct Surface {
1633    /// How many visual rows each block image reserves, keyed by its
1634    /// destination — the frontend's per-image height, set through
1635    /// [`crate::Doc::set_media_rows`] so [`Builder::block_media`] can size the
1636    /// placeholder without core doing any I/O. A destination absent from the
1637    /// map (or a `0`/`1` entry) reserves the bare one-row placeholder.
1638    pub media_rows: HashMap<String, usize>,
1639    /// The same for each display formula, keyed by its TeX verbatim (the
1640    /// [`MathMark::tex`] a frontend was handed) — set through
1641    /// [`crate::Doc::set_math_rows`] once the frontend has typeset and
1642    /// measured the picture.
1643    pub math_rows: HashMap<String, usize>,
1644    /// Whether the surface can paint a picture *inside* a line of text, so an
1645    /// inline formula may render to one atom glyph it draws over
1646    /// ([`MathInfo`]). A pixel-laid-out frontend says yes; a terminal cannot
1647    /// composite an image over one cell, and leaves this off to keep an inline
1648    /// formula as the code-styled TeX it always showed. Off by default.
1649    pub inline_pictures: bool,
1650}
1651
1652/// The one source line rendering its markup raw — the caret's, when the mode
1653/// or the content asks for it — and how much of the markup that means. See
1654/// [`crate::Doc::reveal_line`], which decides both.
1655///
1656/// Two grades because two things ask. Under
1657/// [`MarkupMode::Full`](crate::MarkupMode::Full) *every* delimiter on the line
1658/// comes back (`markup: true`). In the two hidden modes a formula still
1659/// reveals — its content is its TeX and not its picture, so hiding is not
1660/// enough — and the line is threaded through with `markup: false`: a math node
1661/// meeting it shows its source, and an emphasis meeting it hides its
1662/// asterisks as it always did.
1663#[derive(Clone, Debug, PartialEq, Eq)]
1664pub struct Reveal {
1665    /// The source byte range of the line, newline excluded — empty but present
1666    /// on a blank line.
1667    pub line: Range<usize>,
1668    /// Whether ordinary inline markup reveals on it too, or only math.
1669    pub markup: bool,
1670}
1671
1672impl Reveal {
1673    /// The caret's line under `MarkupMode::Full`: everything on it reveals.
1674    pub fn full(line: Range<usize>) -> Self {
1675        Reveal { line, markup: true }
1676    }
1677
1678    /// The caret's line in a hidden mode, where only a formula reveals.
1679    pub fn math(line: Range<usize>) -> Self {
1680        Reveal {
1681            line,
1682            markup: false,
1683        }
1684    }
1685
1686    /// Whether `span` meets this line — the test every arm that reveals runs.
1687    ///
1688    /// Touching at an endpoint counts: an emphasis ending exactly where the
1689    /// line does is on that line, and a zero-length reveal range (the caret
1690    /// alone on a blank line) still meets a node that starts there. The test
1691    /// is deliberately generous — the failure it avoids is revealing one
1692    /// delimiter of a pair while hiding the other, which looks like corruption
1693    /// rather than like markup.
1694    fn meets(&self, span: &Range<usize>) -> bool {
1695        span.start <= self.line.end && self.line.start <= span.end
1696    }
1697}
1698
1699/// Render the document to a [`VisualMap`]. `wrap` is the column budget for
1700/// word-wrapping (`Some` for the monospace TUI), or `None` to emit one row per
1701/// block — the GUI does its own proportional pixel wrapping over these rows.
1702/// Text and offsets come from the AST (`str` nodes carry the verbatim source
1703/// slice and an exact span), so the original source string isn't needed here.
1704pub fn build(
1705    nodes: &[FlatNode],
1706    source: &str,
1707    wrap: Option<usize>,
1708    preserve_soft: bool,
1709    surface: &Surface,
1710    reveal: Option<Reveal>,
1711) -> VisualMap {
1712    let Some(doc) = nodes.iter().position(|n| n.kind == Kind::Doc) else {
1713        return VisualMap::default();
1714    };
1715    let top = top_level(nodes, doc);
1716    let mut b = Builder {
1717        nodes,
1718        source,
1719        wrap: wrap.map(|w| w.max(8)),
1720        rows: Vec::new(),
1721        tables: Vec::new(),
1722        last_off: 0,
1723        stepped_over: 0,
1724        surface,
1725        break_glyph: Cell::new(' '),
1726        preserve_soft,
1727        reveal: reveal.clone(),
1728        pending_mark_ends: RefCell::new(Vec::new()),
1729        pending_math: RefCell::new(Vec::new()),
1730        saw_math: Cell::new(false),
1731        presentation: Presentation::default(),
1732        faces: RefCell::new(FaceTable::default()),
1733    };
1734    let last_drawn = b.top_blocks(&top);
1735    // The hidden frontmatter's end is the baseline for both the trailing blank
1736    // rows and the caret floor — see [`hidden_prefix_end`]. `top_level` has
1737    // already dropped every `metadata` child, so read it off the arena.
1738    let hidden_end = hidden_prefix_end(source, metadata_end_of(nodes, doc));
1739    b.emit_trailing_blank_lines(last_drawn.unwrap_or(BlockClass::Paragraph), hidden_end);
1740    let content_start = top.first().map_or(hidden_end, |&i| nodes[i].span.start);
1741    let stops = collect_stops(&b.rows);
1742    let mark_ends = collect_mark_ends(&b.rows);
1743    label_media_boundaries(&mut b.rows);
1744    let code_blocks = code_block_spans(&b.rows);
1745    let media = media_spans(&b.rows);
1746    let directives = directive_spans(&b.rows);
1747    let math = math_spans(&b.rows);
1748    VisualMap {
1749        rows: b.rows,
1750        content_start,
1751        stops,
1752        mark_ends,
1753        tables: b.tables,
1754        code_blocks,
1755        media,
1756        directives,
1757        math,
1758        faces: b.faces.into_inner(),
1759        spelling: OnceLock::new(),
1760    }
1761}
1762
1763/// Like [`build`], but reuses a persistent [`BlockCache`] so an edit re-renders
1764/// only the top-level blocks whose source bytes changed *and* marshals only
1765/// those blocks from twig instead of the whole arena.
1766///
1767/// `top` is the document's top-level blocks — twig's `child_spans` of the doc
1768/// root: `(node_id, kind, span)` for each, in order. `fetch_subtree(node_id)`
1769/// marshals one block's subtree (local-indexed, root at 0) and is called *only*
1770/// for a block that missed the cache, i.e. one that actually changed. So a
1771/// keystroke marshals one small subtree, not ~20k nodes. The result is
1772/// byte-for-byte identical to [`build`] on the same document (the
1773/// `build_cached_matches_build` test pins this); [`build`] stays the cache-free,
1774/// whole-arena reference. This is the entry point [`crate::Doc`] uses.
1775// One builder, and every one of these is a distinct input to the same layout
1776// pass — a struct of them would be built at the one call site and unpacked
1777// here, which is the same arguments with an extra name in the way.
1778#[allow(clippy::too_many_arguments)]
1779pub fn build_cached(
1780    top: &[QueryMatch],
1781    source: &str,
1782    wrap: Option<usize>,
1783    preserve_soft: bool,
1784    surface: &Surface,
1785    reveal: Option<Reveal>,
1786    cache: &mut BlockCache,
1787    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
1788) -> VisualMap {
1789    let wrap = wrap.map(|w| w.max(8));
1790
1791    // Wrapping is a function of the width, so a width change makes every cached
1792    // row's wrap wrong: start the cache over.
1793    if cache.wrap != Some(wrap) {
1794        cache.entries.clear();
1795        cache.wrap = Some(wrap);
1796    }
1797    cache.generation = cache.generation.wrapping_add(1);
1798
1799    // Frontmatter (a leading `metadata` block) is document metadata, not prose:
1800    // hidden in the rich view exactly as [`Builder::blocks`] skips it.
1801    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
1802
1803    // The outer builder only accumulates rows/tables and spells block boundaries
1804    // — both a function of the source and `last_off`, never of a node array — so
1805    // it carries an empty `nodes`. Each changed block is rendered by a *fresh*
1806    // builder over that block's subtree.
1807    let mut b = Builder {
1808        nodes: &[],
1809        source,
1810        wrap,
1811        rows: Vec::new(),
1812        tables: Vec::new(),
1813        last_off: 0,
1814        stepped_over: 0,
1815        surface,
1816        break_glyph: Cell::new(' '),
1817        preserve_soft,
1818        reveal: reveal.clone(),
1819        pending_mark_ends: RefCell::new(Vec::new()),
1820        pending_math: RefCell::new(Vec::new()),
1821        saw_math: Cell::new(false),
1822        presentation: Presentation::default(),
1823        faces: RefCell::new(FaceTable::default()),
1824    };
1825
1826    // Record the per-block row decomposition as we go, so a later
1827    // [`build_spliced`] can patch one block without rebuilding the map.
1828    let mut layout_blocks: Vec<BlockLayout> = Vec::with_capacity(blocks.len());
1829    // The document's face table, assembled block by block: from the walk on a
1830    // miss, from what the entry stored on a hit. The outer builder walks no
1831    // attributes of its own (it spells boundaries), so it never adds to it.
1832    let mut faces = FaceTable::default();
1833    let mut all_shift_safe = true;
1834    // The class of the last block that drew anything: what the next separator
1835    // closes, and what the trailing blank lines close at the end. A hidden block
1836    // (a comment) never becomes it — see [`Builder::block_or_hidden`], whose
1837    // step-over this loop repeats for the incremental walk.
1838    let mut above: Option<BlockClass> = None;
1839    for block in &blocks {
1840        let start = block.span.start;
1841        let before_sep = b.rows.len();
1842        if let Some(above) = above {
1843            // This walker has no node arena at all (see the `nodes: &[]` above),
1844            // but a top-level query match carries its kind — the same string
1845            // `BlockClass::from_node_kind` classifies for the whole-arena walk, so
1846            // the incremental and full builds label a boundary identically.
1847            b.emit_separators_before(
1848                start,
1849                &[],
1850                true,
1851                Boundary {
1852                    above,
1853                    below: BlockClass::from_node_kind(&block.kind),
1854                },
1855            );
1856        }
1857        let after_sep = b.rows.len();
1858        let bytes = block_bytes(source, &block.span);
1859        let hash = block_hash(bytes);
1860        // How this block meets the reveal line, if at all — part of its cache
1861        // key, since the same bytes render differently on the caret's line.
1862        let rkey = reveal_key(&reveal, &block.span);
1863
1864        // Hit: clone the block's rows shifted to its current offset and restore
1865        // the (shifted) `last_off` so the next separator lands right — no marshal.
1866        // Only shift-safe blocks are ever cached, so a hit is safe by construction.
1867        let mut has_math = false;
1868        if let Some(hit) = cache.reuse(hash, bytes, &rkey) {
1869            faces.merge(&hit.faces);
1870            has_math = hit.has_math;
1871            let delta = start as isize - hit.built_start as isize;
1872            for row in &hit.rows {
1873                b.rows.push(shift_row(row, delta));
1874            }
1875            b.last_off = (hit.last_off as isize + delta) as usize;
1876            // `0` is a block that stepped over nothing, and no answer to shift.
1877            if hit.stepped_over > 0 {
1878                let stepped = (hit.stepped_over as isize + delta) as usize;
1879                b.stepped_over = b.stepped_over.max(stepped);
1880            }
1881        } else {
1882            // Miss: marshal just this block's subtree and render it. A subtree is
1883            // self-contained with local ids (root at 0) and absolute spans, so a
1884            // fresh builder over it produces the same rows the whole-arena path
1885            // would. An empty subtree (twig couldn't hand it back) renders nothing.
1886            let subtree = fetch_subtree(block.node_id);
1887            if !subtree.is_empty() {
1888                let mut sub = Builder {
1889                    nodes: &subtree,
1890                    source,
1891                    wrap,
1892                    rows: Vec::new(),
1893                    tables: Vec::new(),
1894                    last_off: 0,
1895                    stepped_over: 0,
1896                    surface,
1897                    break_glyph: Cell::new(' '),
1898                    preserve_soft,
1899                    reveal: reveal.clone(),
1900                    pending_mark_ends: RefCell::new(Vec::new()),
1901                    pending_math: RefCell::new(Vec::new()),
1902                    saw_math: Cell::new(false),
1903                    presentation: Presentation::default(),
1904                    faces: RefCell::new(FaceTable::default()),
1905                };
1906                sub.block(0, &[], &[]);
1907                // A block that drew nothing is stepped over, not stood on: its
1908                // `last_off` is its own end, so the separator after it counts
1909                // from there. The sub-builder started at 0 and never moved, and
1910                // 0 is where the next separator would otherwise count from —
1911                // every line of the document, as a blank row each.
1912                let last_off = if sub.rows.is_empty() {
1913                    block.span.end
1914                } else {
1915                    sub.last_off
1916                };
1917                let stepped_over = sub.stepped_over;
1918                b.stepped_over = b.stepped_over.max(stepped_over);
1919                // The names this block's glyph ids stand for. They go into the
1920                // document's table *and* into the cache entry, because a hit
1921                // re-emits these rows without walking an attribute again.
1922                let block_faces = sub.faces.into_inner();
1923                faces.merge(&block_faces);
1924                has_math = sub.saw_math.get();
1925                // Cache only a block that is table-free AND renders inside its own
1926                // span: those two are the conditions for reuse-by-shift to be
1927                // correct. A block failing either is re-rendered every build (a
1928                // fresh render always matches a fresh whole-document build).
1929                if sub.tables.is_empty() {
1930                    if rows_within(&sub.rows, &block.span) {
1931                        cache.store(
1932                            hash,
1933                            bytes,
1934                            start,
1935                            sub.rows.clone(),
1936                            last_off,
1937                            stepped_over,
1938                            rkey,
1939                            has_math,
1940                            block_faces,
1941                        );
1942                    }
1943                    b.rows.extend(sub.rows);
1944                } else {
1945                    // A table block is never cached; rebase its row-index
1946                    // bookkeeping onto the combined row vector and append.
1947                    let base = b.rows.len();
1948                    for t in &mut sub.tables {
1949                        t.rows_span = (t.rows_span.start + base)..(t.rows_span.end + base);
1950                    }
1951                    b.rows.extend(sub.rows);
1952                    b.tables.extend(sub.tables);
1953                }
1954                b.last_off = last_off;
1955            }
1956        }
1957        let content_rows = b.rows.len() - after_sep;
1958        let sep_rows = if content_rows == 0 {
1959            // Hidden: take back the separator drawn for it, so what stands
1960            // either side meets across one boundary. Its layout entry stays, at
1961            // no rows, so the splice arithmetic still counts one entry per block.
1962            b.rows.truncate(before_sep);
1963            // A cache hit restored the stored `last_off` above; an empty subtree
1964            // (twig couldn't hand it back) restored nothing. Either way the walk
1965            // stands past the block.
1966            b.last_off = b.last_off.max(block.span.end);
1967            b.stepped_over = b.stepped_over.max(block.span.end);
1968            0
1969        } else {
1970            above = Some(BlockClass::from_node_kind(&block.kind));
1971            all_shift_safe &= rows_within(&b.rows[after_sep..], &block.span);
1972            after_sep - before_sep
1973        };
1974        layout_blocks.push(BlockLayout {
1975            span: block.span.clone(),
1976            kind: block.kind.clone(),
1977            sep_rows,
1978            content_rows,
1979            has_math,
1980        });
1981    }
1982
1983    let before_trailing = b.rows.len();
1984    let hidden_end = hidden_prefix_end(
1985        source,
1986        top.iter()
1987            .filter(|m| m.kind == Kind::Metadata)
1988            .map(|m| m.span.end)
1989            .next_back(),
1990    );
1991    b.emit_trailing_blank_lines(above.unwrap_or(BlockClass::Paragraph), hidden_end);
1992    let trailing_rows = b.rows.len() - before_trailing;
1993
1994    // Evict every entry no block reused this build, so the cache tracks the
1995    // current document instead of growing without bound over a session.
1996    let g = cache.generation;
1997    cache.entries.retain(|_, bucket| {
1998        bucket.retain(|e| e.generation == g);
1999        !bucket.is_empty()
2000    });
2001
2002    cache.layout = Layout {
2003        blocks: layout_blocks,
2004        trailing_rows,
2005        built_len: source.len(),
2006        has_tables: !b.tables.is_empty(),
2007        all_shift_safe,
2008        reveal: reveal.clone(),
2009    };
2010
2011    // The first rendered offset is the first non-metadata block's start — the
2012    // analogue of [`first_content_offset`] for the top-level list. With nothing
2013    // but frontmatter it's the end of that frontmatter, and 0 for an empty
2014    // document ([`hidden_prefix_end`]).
2015    let content_start = blocks.first().map_or(hidden_end, |m| m.span.start);
2016    let stops = collect_stops(&b.rows);
2017    let mark_ends = collect_mark_ends(&b.rows);
2018    label_media_boundaries(&mut b.rows);
2019    let code_blocks = code_block_spans(&b.rows);
2020    let media = media_spans(&b.rows);
2021    let directives = directive_spans(&b.rows);
2022    let math = math_spans(&b.rows);
2023    VisualMap {
2024        rows: b.rows,
2025        content_start,
2026        stops,
2027        mark_ends,
2028        tables: b.tables,
2029        code_blocks,
2030        media,
2031        directives,
2032        math,
2033        faces,
2034        spelling: OnceLock::new(),
2035    }
2036}
2037
2038/// The fast path for a single-block edit: patch the previous [`VisualMap`] in
2039/// place rather than reassembling it. Returns `Some(new_map)` when it applies,
2040/// or `None` to tell the caller to fall back to [`build_cached`] (always
2041/// correct). Consumes `prev` either way — on `None` the caller rebuilds from
2042/// scratch and doesn't need it.
2043///
2044/// It applies only when `dirty` (twig's dirty byte range) falls inside exactly
2045/// one top-level block AND the block structure around it is unchanged — verified
2046/// by matching the new `top` list against the previous [`Layout`] block for
2047/// block: kinds unchanged, spans before the edit identical, spans after it
2048/// shifted by the byte delta, count unchanged. Any deviation — a block split or
2049/// merged, a fence opened to swallow later blocks, a table anywhere, a
2050/// multi-block edit — fails the match and returns `None`. That check is what
2051/// makes the byte-range trustworthy: twig's dirty range is exact about *bytes*
2052/// but silent about *reparse*, and the structural match catches the reparse
2053/// effects it can't see.
2054///
2055/// When it applies, the unchanged prefix rows move verbatim, the suffix rows
2056/// shift by the delta *in place* (integer adds, no glyph copy), and only the one
2057/// dirty block is re-marshalled and re-rendered; stops splice the same way by
2058/// offset. So the cost is O(rows after the edit), and nothing before the edit is
2059/// touched. The hash-keyed entry cache is left alone — a later [`build_cached`]
2060/// will miss on the changed block, re-render it, and evict the stale entry, so
2061/// chained splices neither corrupt nor grow it.
2062// One builder, and every one of these is a distinct input to the same layout
2063// pass — a struct of them would be built at the one call site and unpacked
2064// here, which is the same arguments with an extra name in the way.
2065#[allow(clippy::too_many_arguments)]
2066pub fn build_spliced(
2067    prev: VisualMap,
2068    source: &str,
2069    wrap: Option<usize>,
2070    preserve_soft: bool,
2071    top: &[QueryMatch],
2072    dirty: Range<usize>,
2073    surface: &Surface,
2074    reveal: Option<Reveal>,
2075    cache: &mut BlockCache,
2076    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
2077) -> Option<VisualMap> {
2078    let wrap = wrap.map(|w| w.max(8));
2079    // A width change invalidates every cached row — a full rebuild's job.
2080    if cache.wrap != Some(wrap) {
2081        return None;
2082    }
2083    // So does a moved reveal line, and for the same reason: this path reuses
2084    // every row outside the dirty block, and those rows encode which line was
2085    // showing its raw markup when they were built. Typing almost always moves
2086    // the caret, so under `MarkupMode::Full` this bails to `build_cached` on
2087    // most keystrokes — still block-cached, so only the edited block and the
2088    // revealed one actually re-render.
2089    if cache.layout.reveal != reveal {
2090        return None;
2091    }
2092    // Take the previous layout; on any bail below the caller rebuilds it (and the
2093    // map) via `build_cached`, so leaving it empty is fine. A table or a block
2094    // that renders outside its span (a degenerate inline span) makes shifting
2095    // unsound, so those force the full-rebuild path.
2096    let prev_layout = std::mem::take(&mut cache.layout);
2097    if prev_layout.built_len == 0 || prev_layout.has_tables || !prev_layout.all_shift_safe {
2098        return None;
2099    }
2100    // The layout addresses `prev` by row index, so it is only usable against the
2101    // map it was built from. A frontend is free to hold the map it was handed and
2102    // present it differently — leaf-ratatui splices blank filler rows under an
2103    // oversized heading so the raster has somewhere to stand — and if one of those
2104    // comes back here the row arithmetic below lands on the wrong rows: the
2105    // re-rendered block is laid over a filler and the rows it really occupied
2106    // survive into the suffix, stranding a stale copy of the edited line and
2107    // pushing everything after it one row down, once per keystroke. A row count
2108    // that doesn't match what this layout describes is the tell, and the honest
2109    // answer is the full rebuild.
2110    let described_rows = prev_layout
2111        .blocks
2112        .iter()
2113        .map(|pl| pl.sep_rows + pl.content_rows)
2114        .sum::<usize>()
2115        + prev_layout.trailing_rows;
2116    if described_rows != prev.rows.len() {
2117        return None;
2118    }
2119
2120    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
2121    if blocks.is_empty() || blocks.len() != prev_layout.blocks.len() {
2122        return None;
2123    }
2124    let delta = source.len() as isize - prev_layout.built_len as isize;
2125
2126    // The single block whose NEW span contains the whole dirty range. A dirty
2127    // range straddling a block boundary (or a separator) finds none → bail.
2128    let k = blocks
2129        .iter()
2130        .position(|m| m.span.start <= dirty.start && dirty.end <= m.span.end)?;
2131
2132    // Structural match: every OTHER block is unchanged — same kind throughout,
2133    // span identical before the edit and shifted by `delta` after it. A mismatch
2134    // means the reparse reshaped the block structure, which only a full rebuild
2135    // renders correctly.
2136    for (i, (m, pl)) in blocks.iter().zip(&prev_layout.blocks).enumerate() {
2137        if m.kind != pl.kind {
2138            return None;
2139        }
2140        if i == k {
2141            continue;
2142        }
2143        let want = if i < k {
2144            pl.span.clone()
2145        } else {
2146            (pl.span.start as isize + delta) as usize..(pl.span.end as isize + delta) as usize
2147        };
2148        if m.span != want {
2149            return None;
2150        }
2151    }
2152    // The dirty block itself: start unchanged (the edit is inside it, past its
2153    // start), end moved by exactly the delta.
2154    let pk_start = prev_layout.blocks[k].span.start;
2155    let pk_end = prev_layout.blocks[k].span.end;
2156    let pk_sep = prev_layout.blocks[k].sep_rows;
2157    let pk_content = prev_layout.blocks[k].content_rows;
2158    if blocks[k].span.start != pk_start || blocks[k].span.end != (pk_end as isize + delta) as usize
2159    {
2160        return None;
2161    }
2162
2163    // Re-render the dirty block from its subtree. A table makes the splice
2164    // bookkeeping unsafe, so bail if one appears.
2165    let subtree = fetch_subtree(blocks[k].node_id);
2166    if subtree.is_empty() {
2167        return None;
2168    }
2169    let mut sub = Builder {
2170        nodes: &subtree,
2171        source,
2172        wrap,
2173        rows: Vec::new(),
2174        tables: Vec::new(),
2175        last_off: 0,
2176        stepped_over: 0,
2177        surface,
2178        break_glyph: Cell::new(' '),
2179        preserve_soft,
2180        reveal: reveal.clone(),
2181        pending_mark_ends: RefCell::new(Vec::new()),
2182        pending_math: RefCell::new(Vec::new()),
2183        saw_math: Cell::new(false),
2184        presentation: Presentation::default(),
2185        faces: RefCell::new(FaceTable::default()),
2186    };
2187    sub.block(0, &[], &[]);
2188    // A table, or content that renders outside the block's span (a degenerate
2189    // inline span), makes the shift bookkeeping unsound — fall back.
2190    if !sub.tables.is_empty() || !rows_within(&sub.rows, &blocks[k].span) {
2191        return None;
2192    }
2193    // The face table starts from the previous map's, because every row this
2194    // path keeps was built against it and its glyphs' ids still mean what they
2195    // meant. The re-rendered block adds whatever it met. An id the edit took
2196    // the last glyph of stays in the table, naming nothing — the price of not
2197    // walking the rows this path exists to avoid walking.
2198    let mut faces = prev.faces;
2199    faces.merge(&sub.faces.into_inner());
2200    let sub_saw_math = sub.saw_math.get();
2201    let new_content = sub.rows;
2202    let new_content_len = new_content.len();
2203    let new_stops = collect_stops(&new_content);
2204    let new_mark_ends = collect_mark_ends(&new_content);
2205
2206    // Row span of the dirty block's CONTENT. Its leading separator stays in the
2207    // prefix: the gap before block k is unchanged, since k's start didn't move.
2208    let content_start_row: usize = prev_layout.blocks[..k]
2209        .iter()
2210        .map(|pl| pl.sep_rows + pl.content_rows)
2211        .sum::<usize>()
2212        + pk_sep;
2213    let content_end_row = content_start_row + pk_content;
2214
2215    // Splice rows: [prefix | new content | suffix + delta]. The prefix moves
2216    // untouched; the suffix shifts in place — integer adds, no glyph copy.
2217    let mut rows = prev.rows;
2218    let mut suffix = rows.split_off(content_end_row);
2219    rows.truncate(content_start_row);
2220    for row in &mut suffix {
2221        shift_row_in_place(row, delta);
2222    }
2223    rows.reserve(new_content_len + suffix.len());
2224    rows.extend(new_content);
2225    rows.extend(suffix);
2226
2227    // Splice stops by offset. The old dirty block covered `[pk_start, pk_end]`:
2228    // prefix stops fall below it, suffix stops above it (shift by delta), the new
2229    // content supplies the middle. The three ranges stay disjoint and ascending,
2230    // so the result needs no re-sort.
2231    let p1 = prev.stops.partition_point(|&s| s < pk_start);
2232    let p2 = prev.stops.partition_point(|&s| s <= pk_end);
2233    let mut stops = Vec::with_capacity(p1 + new_stops.len() + (prev.stops.len() - p2));
2234    stops.extend_from_slice(&prev.stops[..p1]);
2235    stops.extend(new_stops);
2236    for &s in &prev.stops[p2..] {
2237        stops.push((s as isize + delta) as usize);
2238    }
2239    // The mark ends splice the same way: they are offsets in the same
2240    // coordinates, cut at the same block.
2241    let m1 = prev.mark_ends.partition_point(|&s| s < pk_start);
2242    let m2 = prev.mark_ends.partition_point(|&s| s <= pk_end);
2243    let mut mark_ends = Vec::with_capacity(m1 + new_mark_ends.len() + (prev.mark_ends.len() - m2));
2244    mark_ends.extend_from_slice(&prev.mark_ends[..m1]);
2245    mark_ends.extend(new_mark_ends);
2246    for &s in &prev.mark_ends[m2..] {
2247        mark_ends.push((s as isize + delta) as usize);
2248    }
2249
2250    // Record the patched layout for the next splice: spans move to the new
2251    // coordinates, and the dirty block takes its new content-row count.
2252    let mut new_blocks = prev_layout.blocks;
2253    for (pl, m) in new_blocks.iter_mut().zip(&blocks) {
2254        pl.span = m.span.clone();
2255    }
2256    new_blocks[k].content_rows = new_content_len;
2257    new_blocks[k].has_math = sub_saw_math;
2258    cache.layout = Layout {
2259        blocks: new_blocks,
2260        trailing_rows: prev_layout.trailing_rows,
2261        built_len: source.len(),
2262        has_tables: false,
2263        // Every prefix/suffix block was shift-safe last build (we bailed
2264        // otherwise) and the re-rendered block was just checked, so the patched
2265        // document is still entirely shift-safe.
2266        all_shift_safe: true,
2267        reveal,
2268    };
2269
2270    label_media_boundaries(&mut rows);
2271    let code_blocks = code_block_spans(&rows);
2272    let media = media_spans(&rows);
2273    let directives = directive_spans(&rows);
2274    let math = math_spans(&rows);
2275    Some(VisualMap {
2276        rows,
2277        content_start: blocks[0].span.start,
2278        stops,
2279        mark_ends,
2280        tables: Vec::new(),
2281        code_blocks,
2282        media,
2283        directives,
2284        math,
2285        faces,
2286        spelling: OnceLock::new(),
2287    })
2288}
2289
2290/// A persistent, content-keyed cache of the rows each top-level block renders
2291/// to — the [`VisualMap`] analogue of the GUI's ShapedLine cache, one level
2292/// down. Held by a [`crate::Doc`] and threaded into [`build_cached`], it is what
2293/// makes a rebuild after a keystroke cost "re-render the edited block + shift
2294/// the rest" instead of re-rendering the whole document.
2295///
2296/// A top-level block's rows are a pure function of its source bytes and the wrap
2297/// width, so an unchanged block's rows are cloned and their source offsets
2298/// shifted by the edit's byte delta rather than rebuilt glyph by glyph. Two
2299/// things make that purity hold: at the top level the render prefix is always
2300/// empty (nesting prefixes — a quote gutter, a list indent — exist only *inside*
2301/// a top-level block, within its cached unit), and a block's output never reads
2302/// the incoming `last_off` (it writes `last_off` from its own content before any
2303/// nested separator reads it). So the only thing that differs between two
2304/// positions of an unchanged block is a uniform offset shift. Keyed by a fast
2305/// hash of the block's bytes with the bytes kept for a verify-on-hit — exactly
2306/// the shape cache's weak-hash-then-compare, so a collision costs a re-render,
2307/// never a wrong row.
2308///
2309/// Tables are never cached (a block that emits any table row is always rebuilt):
2310/// their rows are cross-referenced from the map's `tables` side-table by row
2311/// index, which a blind offset-shift wouldn't fix up, and they are rare enough
2312/// that the simplicity beats the reuse.
2313#[derive(Default)]
2314pub struct BlockCache {
2315    /// The wrap width every entry was built at; a change invalidates all of
2316    /// them. `None` before the first build (distinct from `Some(None)`, the
2317    /// unwrapped GUI width).
2318    wrap: Option<Option<usize>>,
2319    /// Bumped once per [`build_cached`]. An entry reused or inserted this build
2320    /// carries the current value; stale entries are dropped at the end of it.
2321    generation: u64,
2322    /// `hash(bytes)` → the block(s) sharing that hash — a bucket because
2323    /// distinct blocks can collide, while two *identical* blocks share one entry
2324    /// (free dedup).
2325    entries: HashMap<u64, Vec<CachedBlock>>,
2326    /// The row/stop decomposition of the last build, which [`build_spliced`]
2327    /// patches in place for a single-block edit. Kept in step with whatever
2328    /// [`VisualMap`] was last produced; empty before the first build.
2329    layout: Layout,
2330}
2331
2332/// How the last build's [`VisualMap`] decomposes into top-level blocks — the
2333/// bookkeeping [`build_spliced`] needs to splice one block's rows and stops
2334/// without rebuilding the whole map. Every field describes the *previous* build,
2335/// in that build's coordinates.
2336#[derive(Default)]
2337struct Layout {
2338    /// One entry per rendered (metadata-filtered) top-level block, in order.
2339    blocks: Vec<BlockLayout>,
2340    /// Trailing blank rows past the last block (from `emit_trailing_blank_lines`).
2341    trailing_rows: usize,
2342    /// The source length this layout was built at — the reference for the edit's
2343    /// byte delta.
2344    built_len: usize,
2345    /// Whether the last build drew any table. A table's cross-referenced row
2346    /// indices don't survive a blind splice, so their presence makes
2347    /// [`build_spliced`] bail to a full rebuild.
2348    has_tables: bool,
2349    /// Whether every block rendered strictly inside its own span (see
2350    /// [`rows_within`]). A block that doesn't — a malformed Markdown inline node
2351    /// that twig leaves with a degenerate `0..0` span renders at a fixed offset
2352    /// outside its block — can't be shifted correctly, so its presence makes
2353    /// [`build_spliced`] bail to a full rebuild.
2354    all_shift_safe: bool,
2355    /// The reveal line this layout was built under (see [`Builder::reveal`]).
2356    /// A splice reuses every row it isn't re-rendering, so a reveal line that
2357    /// has moved would leave the old line still showing its delimiters and the
2358    /// new one still hiding them — [`build_spliced`] bails when this changes.
2359    reveal: Option<Reveal>,
2360}
2361
2362/// One top-level block's contribution to the last build: its span and kind (for
2363/// the structural match that proves only one block changed) and how many
2364/// separator and content rows it emitted (to locate its slice of the row
2365/// vector).
2366struct BlockLayout {
2367    span: Range<usize>,
2368    kind: Kind,
2369    sep_rows: usize,
2370    content_rows: usize,
2371    /// Whether the block holds a formula — see [`BlockCache::math_meets`].
2372    has_math: bool,
2373}
2374
2375/// One cached block: the rows it rendered to, plus what a reuse at a new
2376/// position needs to shift them. Offsets are stored absolute (as built) and
2377/// shifted by `new_start - built_start` on reuse.
2378struct CachedBlock {
2379    /// The block's exact source bytes, compared on a hash hit so a collision
2380    /// can never hand back another block's rows.
2381    bytes: Box<[u8]>,
2382    /// The offset the rows were built at (the block's `span.start`).
2383    built_start: usize,
2384    /// The block's rows, offsets absolute as built.
2385    rows: Vec<VRow>,
2386    /// `last_off` after this block was emitted, absolute as built — restored
2387    /// (shifted) on reuse so the following separator lands correctly.
2388    last_off: usize,
2389    /// `stepped_over` after this block was emitted, absolute as built — the
2390    /// hidden tail a block ends with (a `</div>`), restored with `last_off`
2391    /// so the trailing blank lines are counted from past it on a hit too.
2392    stepped_over: usize,
2393    /// Where the reveal line fell *within this block* when the rows were built,
2394    /// as a block-relative byte range — see [`reveal_key`]. Compared alongside
2395    /// `bytes` on a hit, because identical source renders to different rows
2396    /// depending on whether the caret's line is inside it: the same `*em*`
2397    /// shows its asterisks on the revealed line and hides them everywhere else.
2398    ///
2399    /// Block-relative rather than absolute so an unaffected block still hits
2400    /// after an edit shifts it, and `None` for the overwhelmingly common
2401    /// no-reveal case — which is why an entry stored under `MarkupMode::None`
2402    /// keeps hitting for every block that isn't the caret's.
2403    reveal: Option<Range<usize>>,
2404    /// Whether the block holds a formula, so a hit can say so to the layout
2405    /// without walking the rows it is re-emitting.
2406    has_math: bool,
2407    /// The named families this block's glyphs are set in — see
2408    /// [`VisualMap::faces`]. Stored with the rows because a hit re-emits them
2409    /// without walking a `data-font` again, and the map still has to be able to
2410    /// say what the id on a reused glyph names. Empty for every block that
2411    /// names no family, which is nearly all of them.
2412    faces: FaceTable,
2413    /// The build that last reused or inserted this entry (see `generation`).
2414    generation: u64,
2415}
2416
2417/// Where `reveal` falls inside a block, in block-relative bytes — the extra key
2418/// a cached block is stored and matched under.
2419///
2420/// `None` when the block doesn't meet the reveal line at all, which is every
2421/// block on every build in the two hidden modes, and all but one of them under
2422/// [`crate::MarkupMode::Full`]. So the cache keeps its hit rate as the caret
2423/// moves: only the line the caret leaves and the line it arrives at re-render.
2424fn reveal_key(reveal: &Option<Reveal>, span: &Range<usize>) -> Option<Range<usize>> {
2425    let r = reveal.as_ref()?;
2426    // The same generous intersection test `Builder::revealed` uses, so a block
2427    // is keyed as revealed exactly when its glyphs will be built that way.
2428    // Whether the line reveals markup or only math is not in the key: that is
2429    // a mode, and a mode change empties the cache.
2430    r.meets(span).then(|| {
2431        let start = r.line.start.max(span.start) - span.start;
2432        let end = r.line.end.min(span.end) - span.start;
2433        start..end
2434    })
2435}
2436
2437impl BlockCache {
2438    /// Whether the caret's `line` meets a top-level block that holds a
2439    /// formula, as of the last build — the question [`crate::Doc::reveal_line`]
2440    /// asks in the hidden markup modes before it threads the line through, so
2441    /// that only a line with something to reveal costs a rebuild.
2442    ///
2443    /// Answered from the layout rather than from twig because the layout is
2444    /// free: every build records per block whether its walk met a formula
2445    /// ([`BlockLayout::has_math`]), and a query against the tree is
2446    /// O(document) on every frame. Coarse on purpose — a block, not a line —
2447    /// since a block with a formula in it is rare, small, and the one thing
2448    /// worth re-rendering as the caret moves through it.
2449    ///
2450    /// Exact between edits, when the spans are the document's. Across an edit
2451    /// the spans are the previous revision's, so the caller checks again once
2452    /// the new layout is in and rebuilds if the answer changed.
2453    pub(crate) fn math_meets(&self, line: &Range<usize>) -> bool {
2454        self.layout
2455            .blocks
2456            .iter()
2457            .any(|b| b.has_math && b.span.start <= line.end && line.start <= b.span.end)
2458    }
2459
2460    /// Look up a block by hash, verify its bytes and reveal key, and on a hit
2461    /// stamp it used this build and hand back a borrow to shift-and-clone from.
2462    /// `None` on a miss (unknown hash, a collision whose bytes differ, or the
2463    /// same bytes built under a different reveal).
2464    fn reuse(
2465        &mut self,
2466        hash: u64,
2467        bytes: &[u8],
2468        reveal: &Option<Range<usize>>,
2469    ) -> Option<&CachedBlock> {
2470        let g = self.generation;
2471        let bucket = self.entries.get_mut(&hash)?;
2472        let e = bucket
2473            .iter_mut()
2474            .find(|e| &*e.bytes == bytes && &e.reveal == reveal)?;
2475        e.generation = g;
2476        Some(&*e)
2477    }
2478
2479    /// Cache the rows a freshly-rendered block produced (or refresh an existing
2480    /// entry for the same bytes and reveal — an identical block elsewhere, or a
2481    /// re-render).
2482    #[allow(clippy::too_many_arguments)]
2483    fn store(
2484        &mut self,
2485        hash: u64,
2486        bytes: &[u8],
2487        built_start: usize,
2488        rows: Vec<VRow>,
2489        last_off: usize,
2490        stepped_over: usize,
2491        reveal: Option<Range<usize>>,
2492        has_math: bool,
2493        faces: FaceTable,
2494    ) {
2495        let g = self.generation;
2496        let bucket = self.entries.entry(hash).or_default();
2497        if let Some(e) = bucket
2498            .iter_mut()
2499            .find(|e| &*e.bytes == bytes && e.reveal == reveal)
2500        {
2501            e.built_start = built_start;
2502            e.rows = rows;
2503            e.last_off = last_off;
2504            e.stepped_over = stepped_over;
2505            e.has_math = has_math;
2506            e.faces = faces;
2507            e.generation = g;
2508        } else {
2509            bucket.push(CachedBlock {
2510                bytes: bytes.into(),
2511                built_start,
2512                rows,
2513                last_off,
2514                stepped_over,
2515                reveal,
2516                has_math,
2517                faces,
2518                generation: g,
2519            });
2520        }
2521    }
2522}
2523
2524/// The source bytes a top-level block covers — the block cache's key material.
2525///
2526/// Clamped to the source rather than sliced by the span as twig gives it,
2527/// because that span can end *past* the last byte: the final block of a document
2528/// with no trailing newline is closed on the virtual newline the parser supplies
2529/// at EOF, so its `span.end` is `source.len() + 1`. Slicing by such a range
2530/// yields `None`, and the obvious `unwrap_or(&[])` reads that as *this block has
2531/// no bytes* — the wrong answer twice over.
2532///
2533/// Two blocks whose spans both overrun then key alike, and the second is served
2534/// the first one's rows. That is not hypothetical: a footnote definition is a
2535/// root beside `doc` merged back into the top level by [`top_blocks`], while the
2536/// `section` above it spans the definition's bytes too, so both end at EOF —
2537/// and a document ending in `[^note]: …` renders that definition as a second
2538/// copy of the heading. Even alone, a block that keeps hashing empty as the user
2539/// types in it is served the stale rows built before the edit.
2540///
2541/// Clamping hands back the bytes the block really covers, which tells both cases
2542/// apart, and costs nothing for a span that was in range to begin with.
2543fn block_bytes<'a>(source: &'a str, span: &Range<usize>) -> &'a [u8] {
2544    let bytes = source.as_bytes();
2545    let start = span.start.min(bytes.len());
2546    &bytes[start..span.end.clamp(start, bytes.len())]
2547}
2548
2549/// A fast, allocation-free content hash (FNV-1a) for a block's bytes. Weak by
2550/// design — the bytes are compared on a hit — so its only job is to spread
2551/// blocks across buckets cheaply. SipHash over every block's bytes on every
2552/// keystroke would cost more than it saves, the same lesson the shape cache
2553/// learned when it stopped hashing through the standard hasher.
2554fn block_hash(bytes: &[u8]) -> u64 {
2555    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
2556    for &x in bytes {
2557        h ^= x as u64;
2558        h = h.wrapping_mul(0x0000_0100_0000_01b3);
2559    }
2560    h
2561}
2562
2563/// Clone a cached row with every source offset advanced by `delta` — the whole
2564/// cost of reusing an unchanged block: integer adds where a rebuild would
2565/// re-shape every glyph.
2566fn shift_row(row: &VRow, delta: isize) -> VRow {
2567    let shift = |off: usize| (off as isize + delta) as usize;
2568    VRow {
2569        glyphs: row
2570            .glyphs
2571            .iter()
2572            .map(|g| Glyph {
2573                ch: g.ch,
2574                style: g.style,
2575                src: shift(g.src),
2576                stop: g.stop,
2577            })
2578            .collect(),
2579        end_src: shift(row.end_src),
2580        decoration: row.decoration,
2581        code: row.code,
2582        code_lang: row.code_lang.clone(),
2583        directive: row.directive,
2584        directive_label: row.directive_label.clone(),
2585        media: row.media.clone(),
2586        // A tick, not an offset — reuse carries it as-is, like `code_lang`.
2587        task: row.task,
2588        leaf_directive: row.leaf_directive.clone(),
2589        heading: row.heading,
2590        // Presentation, not offsets: names the author wrote, which a shifted
2591        // block still wears — like `code_lang`.
2592        align: row.align,
2593        line_height: row.line_height,
2594        // Structure, not offsets: a reused block's rows divide the same blocks
2595        // wherever the edit above moved them to.
2596        boundary: row.boundary,
2597        mark_ends: row.mark_ends.iter().map(|&o| shift(o)).collect(),
2598        // Strings and a glyph index: the glyph moved, the index into the row
2599        // did not.
2600        math: row.math.clone(),
2601    }
2602}
2603
2604/// Advance a row's source offsets by `delta` in place — the suffix half of
2605/// [`build_spliced`], where the rows are already owned and only need shifting,
2606/// not copying.
2607fn shift_row_in_place(row: &mut VRow, delta: isize) {
2608    for g in &mut row.glyphs {
2609        g.src = (g.src as isize + delta) as usize;
2610    }
2611    row.end_src = (row.end_src as isize + delta) as usize;
2612    for o in &mut row.mark_ends {
2613        *o = (*o as isize + delta) as usize;
2614    }
2615}
2616
2617/// Whether every source offset a block's rows carry falls inside the block's own
2618/// span — the precondition for reusing the block by a uniform offset shift. It
2619/// holds for well-formed blocks (their glyphs and row ends address bytes within
2620/// the block, synthetic glyphs point at the block start). It fails when a node
2621/// renders *outside* its block, which today means a malformed Markdown inline
2622/// node twig leaves with a degenerate `0..0` span: that content lands at a fixed
2623/// offset that doesn't move with the block. Such a block is re-rendered every
2624/// build instead of shifted, so the incremental map still matches a fresh one —
2625/// see [`build_cached`] and [`build_spliced`].
2626fn rows_within(rows: &[VRow], span: &Range<usize>) -> bool {
2627    rows.iter().all(|r| {
2628        r.end_src >= span.start
2629            && r.end_src <= span.end
2630            && r.glyphs
2631                .iter()
2632                .all(|g| g.src >= span.start && g.src <= span.end)
2633    })
2634}
2635
2636/// Where the rendered document begins when a leading `metadata` block is all
2637/// there is — the end of that hidden frontmatter, past the newline that closes
2638/// its last line so the floor sits at the start of the (empty) body rather than
2639/// on the closing `---`.
2640///
2641/// With a real block after it the frontmatter's end is never needed: the floor
2642/// is that block's start, and the rows begin there. With nothing after it, both
2643/// the caret floor and the trailing-blank-line count would otherwise fall back
2644/// to offset 0 — inside the hidden frontmatter — which put the caret *before*
2645/// the metadata and made typing land ahead of the opening `---`.
2646fn hidden_prefix_end(source: &str, meta_end: Option<usize>) -> usize {
2647    let Some(end) = meta_end else { return 0 };
2648    let end = end.min(source.len());
2649    let rest = &source[end..];
2650    if rest.starts_with("\r\n") {
2651        end + 2
2652    } else if rest.starts_with('\n') {
2653        end + 1
2654    } else {
2655        end
2656    }
2657}
2658
2659/// The end of the document's hidden frontmatter: the last `metadata` child of
2660/// `doc`, which is what [`top_level`] and [`Builder::blocks`] drop. `None` when
2661/// there is none.
2662fn metadata_end_of(nodes: &[FlatNode], doc: usize) -> Option<usize> {
2663    let mut end = None;
2664    let mut child = nodes[doc].first_child;
2665    while let Some(cid) = child {
2666        let n = &nodes[cid.0 as usize];
2667        if n.kind == Kind::Metadata {
2668            end = Some(n.span.end);
2669        }
2670        child = n.next_sibling;
2671    }
2672    end
2673}
2674
2675/// The document's rendered top-level blocks, as node indices in source order.
2676///
2677/// Not simply `doc`'s children, for two reasons. Frontmatter (a leading
2678/// `metadata` block) is document metadata rather than prose and is dropped, the
2679/// way [`Builder::blocks`] drops it. And a **footnote definition** (`[^1]: …`)
2680/// is not a child of `doc` at all: twig parses it as a root of its own, a
2681/// *sibling* of the document node with `parent == None`. A walk that starts at
2682/// `doc` therefore never reaches one, which is why a definition — and every
2683/// byte of its body — used to render as nothing at all. Merging the roots back
2684/// in by `span.start` puts each definition on screen exactly where it was
2685/// written, which is what keeps rows, stops, and offsets monotonic.
2686///
2687/// A **link reference definition** (`[foo]: /url`) is a root of the same kind,
2688/// and is merged for the opposite reason: it draws *nothing*, and the walk has
2689/// to know where it stands to step over it. A definition closing a README —
2690/// the `[links]: …` block under the prose — left no block over its lines, so
2691/// the separator logic read them as blank lines and drew an empty paragraph
2692/// per definition. Merged in, it is a hidden block like a comment, and
2693/// [`Builder::block_or_hidden`] moves the walk past it. One with no span
2694/// (`0..0`, what twig before 3.3.3 reported for every one) has nowhere to be
2695/// merged, and is left out as before.
2696///
2697/// Only those roots are merged. twig also leaves stray orphan `str` nodes
2698/// parented to nothing (the `*` of an emphasis run, for one); those are already
2699/// rendered as part of the subtree that owns their bytes, and re-emitting them
2700/// here would double them.
2701fn top_level(nodes: &[FlatNode], doc: usize) -> Vec<usize> {
2702    let mut out = Vec::new();
2703    let mut child = nodes[doc].first_child;
2704    while let Some(cid) = child {
2705        let n = &nodes[cid.0 as usize];
2706        if n.kind != Kind::Metadata {
2707            out.push(cid.0 as usize);
2708        }
2709        child = n.next_sibling;
2710    }
2711    out.extend(
2712        nodes
2713            .iter()
2714            .enumerate()
2715            .filter(|(_, n)| n.parent.is_none() && is_placed_definition(&n.kind, &n.span))
2716            .map(|(i, _)| i),
2717    );
2718    out.sort_by_key(|&i| nodes[i].span.start);
2719    out
2720}
2721
2722/// Is a parentless node of `kind` at `span` a definition the top-level walk
2723/// merges in — a footnote definition, or a link reference definition that
2724/// knows where it stands? Shared by [`top_level`] and [`top_blocks`] so the
2725/// two walks cannot disagree about what the top-level blocks are.
2726fn is_placed_definition(kind: &Kind, span: &Range<usize>) -> bool {
2727    match *kind {
2728        Kind::Footnote => true,
2729        Kind::Reference => span.end > span.start,
2730        _ => false,
2731    }
2732}
2733
2734/// The top-level blocks to hand [`build_cached`] / [`build_spliced`] — the
2735/// incremental path's twin of [`top_level`], which the two must agree with block
2736/// for block or the render paths diverge.
2737///
2738/// `child_spans(None)` gives `doc`'s children, which is all of them for an
2739/// ordinary document. A **footnote definition** is not one: twig parses `[^1]: …`
2740/// as a root beside `doc` with no parent, and indexes it at no offset either —
2741/// `node_at` inside its bytes answers `doc`, and a `query("footnote")` selector
2742/// finds nothing. Leaf used to discover them by marshalling the whole arena with
2743/// `nodes()` — the very cost the incremental path exists to avoid — behind a
2744/// byte-scan gate that gave documents with no `[^…]:` line a substring search
2745/// instead. twig 3.0's `definitions()` asks the library the question directly,
2746/// so both the marshal and the gate are gone.
2747///
2748/// The link reference definitions `definitions()` also reports are merged on
2749/// the same terms as [`top_level`] merges them — see [`is_placed_definition`].
2750///
2751/// This is the one part of the render that needs an [`Editor`] rather than a
2752/// marshalled node array. The builders themselves stay editor-free; this only
2753/// prepares their input.
2754pub(crate) fn top_blocks(editor: &mut Editor) -> Vec<QueryMatch> {
2755    let mut top = editor.child_spans(None).unwrap_or_default();
2756    let defs: Vec<QueryMatch> = definitions(editor)
2757        .into_iter()
2758        .filter(|m| is_placed_definition(&m.kind, &m.span))
2759        .collect();
2760    if defs.is_empty() {
2761        return top;
2762    }
2763    top.extend(defs);
2764    // Source order — what every offset-keyed thing downstream (rows, stops, the
2765    // splice path's block-for-block match) is built to assume.
2766    top.sort_by_key(|m| m.span.start);
2767    top
2768}
2769
2770/// Every `[^label]: …` definition in the document, in whatever order twig
2771/// reports them.
2772///
2773/// Filtered to [`Kind::Footnote`]: `definitions()` also reports the *link*
2774/// reference definitions (`[foo]: /url`), which are [`top_blocks`]'s business
2775/// and not [`crate::Doc::footnote_at_caret`]'s.
2776///
2777/// Empty when the document can't be walked, which leaves [`top_blocks`] with
2778/// the ordinary top-level children and [`crate::Doc::footnote_at_caret`] with an
2779/// undefined reference — in both cases the same answer as a document that has
2780/// no definitions, which is the right way to degrade.
2781pub(crate) fn footnote_definitions(editor: &mut Editor) -> Vec<QueryMatch> {
2782    definitions(editor)
2783        .into_iter()
2784        .filter(|m| m.kind == Kind::Footnote)
2785        .collect()
2786}
2787
2788/// Every definition twig resolves by label rather than by position — footnote
2789/// and link reference definitions both — or nothing when the document can't be
2790/// walked.
2791fn definitions(editor: &mut Editor) -> Vec<QueryMatch> {
2792    let Ok(mut doc) = editor.document() else {
2793        return Vec::new();
2794    };
2795    doc.definitions().unwrap_or_default()
2796}
2797
2798/// The label of the footnote definition starting at `start` — the `1` in
2799/// `[^1]: …`. twig gives the `footnote` node no label of its own (no `text`, no
2800/// `name`), and the bytes that spell it belong to no child node either — the
2801/// body `para` starts its *content* past them — so the source is the only place
2802/// to read it from. `None` when what's there isn't a definition after all.
2803pub(crate) fn footnote_label(source: &str, start: usize) -> Option<&str> {
2804    let rest = source.get(start..)?.strip_prefix("[^")?;
2805    let end = rest.find("]:")?;
2806    Some(&rest[..end])
2807}
2808
2809/// Where the body of the footnote definition spanning `span` sits in `source` —
2810/// everything past the `[^1]:` marker, which is the part a reader actually wants
2811/// when they follow a reference.
2812///
2813/// Source bytes, verbatim but for the whitespace trimmed off each end: a note
2814/// that says `see *later*` answers with the asterisks in. Rendering that body is
2815/// a frontend's business the same way painting a [`Role`] is, and a caller that
2816/// wants it laid out already has the definition on screen where it was written.
2817///
2818/// The trim is what makes the common case read right — `[^1]: text` has a space
2819/// after the colon that belongs to the marker, not the note, and a definition's
2820/// span runs to the newline ending it.
2821///
2822/// The span is taken at its word, which it has only been safe to do since twig
2823/// 3.1: a djot definition's span used to run *past* its own last line, through
2824/// the blank line separating it from the next block and into that block's first
2825/// byte, so `[^2a]: a note.` came back as `"a note.\n\n["` and the offsets named
2826/// the following note's rows as well as this one's — a reader asking about one
2827/// footnote was shown two. leaf measured the body itself to get around that, and
2828/// paid for it: the scan stopped at the first blank line, so a note with a second
2829/// indented paragraph lost it. Both halves go away with the fix, since a blank
2830/// line *inside* a definition was always interior to the span and still is.
2831///
2832/// A range rather than a slice because "go to note" needs the *position* as much
2833/// as the text, and it needs the position of the body specifically: a
2834/// definition's `[^1]:` marker is decoration the caret can't occupy (the rich
2835/// view draws it as `[1] ` and gives it no stop), so aiming a caret at the
2836/// definition's first byte lands it on the nearest real stop instead — which is
2837/// up in the paragraph *above* the note. The body's first byte is a stop, and is
2838/// where a reader following a reference wants to arrive anyway.
2839pub(crate) fn footnote_body_span(source: &str, span: Range<usize>) -> Option<Range<usize>> {
2840    let rest = source.get(span.clone())?.strip_prefix("[^")?;
2841    let marker = rest.find("]:")?;
2842    // `span.start` + `[^` + the label + `]:`.
2843    let after_marker = span.start + 2 + marker + 2;
2844    let raw = source.get(after_marker..span.end)?;
2845    // Written as a start plus a length so an all-whitespace body lands on an
2846    // empty range at the end rather than an inverted one.
2847    let start = after_marker + (raw.len() - raw.trim_start().len());
2848    Some(start..start + raw.trim().len())
2849}
2850
2851/// The label of the footnote *reference* spanning `span` — the `1` in `[^1]`.
2852///
2853/// The peer of [`footnote_label`] for the other half of the pair, and needed for
2854/// the same reason: a reference whose node carries neither a `content_span` nor
2855/// a `text` still spells its label plainly in the source. `None` when the bytes
2856/// aren't a reference after all.
2857pub(crate) fn footnote_reference_label(source: &str, span: Range<usize>) -> Option<&str> {
2858    let rest = source.get(span)?.strip_prefix("[^")?;
2859    let end = rest.find(']')?;
2860    Some(&rest[..end])
2861}
2862
2863/// Where a heading's *content* starts — past the `#`s and the space the rich
2864/// view hides, for an ATX heading; the block's own start for a setext one (which
2865/// has no leading marker) and for a format that spells headings some other way.
2866///
2867/// Only an empty heading needs asking: with any content at all, the row ends on
2868/// its last glyph. Bounded to the heading's own first line so a marker-less
2869/// heading can't scan into the text under it.
2870fn heading_content_start(source: &str, span: &Range<usize>) -> usize {
2871    let end = span.end.min(source.len());
2872    let Some(line) = source.get(span.start..end) else {
2873        return span.start;
2874    };
2875    let line = line.split('\n').next().unwrap_or("");
2876    let hashes = line.len() - line.trim_start_matches('#').len();
2877    if hashes == 0 {
2878        return span.start;
2879    }
2880    let after = &line[hashes..];
2881    span.start + hashes + (after.len() - after.trim_start_matches([' ', '\t']).len())
2882}
2883
2884struct Builder<'a> {
2885    nodes: &'a [FlatNode],
2886    /// The document source, consulted to place blank-line rows at the source
2887    /// offsets the caret should occupy on them (the AST drops blank lines).
2888    source: &'a str,
2889    /// The word-wrap column budget, or `None` to emit each block as a single
2890    /// unwrapped row (the frontend wraps).
2891    wrap: Option<usize>,
2892    rows: Vec<VRow>,
2893    /// Built alongside `rows`, never instead of them — see [`TableInfo`].
2894    tables: Vec<TableInfo>,
2895    /// The end offset of the last content emitted — the anchor for blank
2896    /// separator rows so the caret never snaps onto one.
2897    last_off: usize,
2898    /// The end of the last block the walk stepped over without drawing — a
2899    /// comment, which the rich view hides. `last_off` moves past it too, for the
2900    /// separators; this is kept apart so the trailing blank lines can be counted
2901    /// from it without also being counted from a code block's closing fence,
2902    /// which `last_off` likewise ends after. `0` until a hidden block is met.
2903    stepped_over: usize,
2904    /// How many rows each block image reserves, keyed by its destination — the
2905    /// frontend's per-image height, threaded in from [`crate::Doc::set_media_rows`]
2906    /// so [`Builder::block_media`] can size the placeholder without core doing any
2907    /// I/O. A destination absent from the map (or a `0`/`1` entry) reserves the
2908    /// bare one-row placeholder, which is the whole-document default and what
2909    /// every existing test — passing an empty map — still gets.
2910    surface: &'a Surface,
2911    /// The glyph a hard break renders as while the current inline run is built:
2912    /// a space in prose (a break folds into the flow the frontend wraps), but a
2913    /// newline (`\n`) inside a table cell, where a row is one source line and the
2914    /// only break it can carry is an explicit one that must show as a line of its
2915    /// own. Set around [`Builder::row_cells`] and otherwise left at `' '`.
2916    break_glyph: Cell<char>,
2917    /// Render a soft break (a bare newline inside a paragraph) as a line break
2918    /// where it was written, rather than folding it into the reflowed paragraph
2919    /// — the `LineFlow::Preserve` behaviour. A soft break emits a `'\n'` glyph
2920    /// (like a hard break in a cell), which [`Builder::emit_wrapped`] turns into
2921    /// a fresh visual row. `false` is the flowing-prose default. Inside a table
2922    /// cell (where `break_glyph` is already `'\n'`) it has no effect: a cell is
2923    /// one line and folds its own soft breaks regardless.
2924    preserve_soft: bool,
2925    /// The source byte range of the one line that should render its markup
2926    /// *raw* — the caret's line under `MarkupMode::Full` (see
2927    /// [`crate::Doc::reveal_line`]). `None` in every other mode and view, which
2928    /// is the delimiters-always-hidden behaviour every build had before the
2929    /// preference existed.
2930    ///
2931    /// Read only by [`Builder::revealed`], which every delimiter-bearing arm of
2932    /// [`Builder::inline`] consults. A range rather than a bare caret offset
2933    /// because the decision is per-*node*, not per-caret: a node is revealed
2934    /// when its span meets this line, so `*em*` shows both its asterisks even
2935    /// with the caret at one end of it.
2936    reveal: Option<Reveal>,
2937    /// The content ends of the hidden marks rendered since the last row was
2938    /// pushed — recorded as the inline walk meets each mark, and drained onto
2939    /// the rows as they are emitted (see [`Builder::take_mark_ends`]). A cell
2940    /// rather than a `&mut`, for the reason `break_glyph` is: the inline walk
2941    /// borrows the builder shared.
2942    pending_mark_ends: RefCell<Vec<usize>>,
2943    /// The inline atoms rendered since the last row was pushed, keyed by the
2944    /// formula's start offset — the offset the atom glyph carries, which is
2945    /// how [`Builder::take_math`] pairs each with its glyph once the wrap has
2946    /// decided which row it landed on. Drained the way `pending_mark_ends` is.
2947    pending_math: RefCell<Vec<(usize, MathMark)>>,
2948    /// Whether this walk met a formula at all, atom, block, or revealed — the
2949    /// fact [`BlockCache`] keeps per block so [`crate::Doc::reveal_line`] can
2950    /// tell whether the caret's line has anything to reveal without walking.
2951    saw_math: Cell<bool>,
2952    /// The presentation vocabulary in force at the block being walked — the
2953    /// keys the `div`s around it carry, folded together with the nearest
2954    /// winning, and [`Presentation::default`] at the top level.
2955    ///
2956    /// Saved and restored around each `div` in [`Builder::block`], so a block
2957    /// reads its own attributes over whatever its containers said and nothing
2958    /// leaks sideways to the block after it. It is per-*build* state rather
2959    /// than a parameter because every one of the dozen call sites of `block`
2960    /// would otherwise thread a value none of them care about.
2961    presentation: Presentation,
2962    /// The named families this walk has met, by the id its glyphs carry — see
2963    /// [`VisualMap::faces`]. A `RefCell` for [`pending_mark_ends`]'s reason:
2964    /// the inline walk borrows the builder shared, and a span's `data-font` is
2965    /// read from inside it.
2966    ///
2967    /// [`pending_mark_ends`]: Builder::pending_mark_ends
2968    faces: RefCell<FaceTable>,
2969}
2970
2971/// The six presentation keys as the walker carries them down a block tree —
2972/// the two that are the block's ([`Align`], [`LineHeight`]) and the three that
2973/// are a run's but may be written on the block ([`FontSize`], [`FaceRef`],
2974/// [`TextColor`]).
2975///
2976/// `Copy` and five `Option`s, because folding is the whole of what it does:
2977/// [`under`](Presentation::under) reads a container's attributes over an
2978/// existing set and a key the container does not name keeps the value it had.
2979/// That is the "nearest wins" rule stated once, rather than at each of the
2980/// three levels a key can be written at. A name and a value fold alike: the
2981/// nearer node wins whichever of the two forms either of them wrote.
2982#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2983struct Presentation {
2984    align: Option<Align>,
2985    line_height: Option<LineHeight>,
2986    size: Option<FontSize>,
2987    font: Option<FaceRef>,
2988    color: Option<TextColor>,
2989}
2990
2991impl Presentation {
2992    /// This set with whatever `attrs` names written over it — the nearer node's
2993    /// answer where it has one, the outer node's where it hasn't.
2994    ///
2995    /// `faces` is the build's intern table, which a named family is recorded in
2996    /// on the way past: the glyph carries the id and the table carries the
2997    /// string. Shared rather than `&mut` because the inline walk this feeds
2998    /// borrows the builder shared, the way `pending_mark_ends` does.
2999    fn under(self, attrs: &[(String, Option<String>)], faces: &RefCell<FaceTable>) -> Self {
3000        Self {
3001            align: Align::from_attrs(attrs).or(self.align),
3002            line_height: LineHeight::from_attrs(attrs).or(self.line_height),
3003            size: FontSize::from_attrs(attrs).or(self.size),
3004            font: faces.borrow_mut().face_from_attrs(attrs).or(self.font),
3005            color: TextColor::from_attrs(attrs).or(self.color),
3006        }
3007    }
3008
3009    /// `base` carrying the three run-level keys — the style a block's glyphs
3010    /// start from, which an attributed span inside it then writes over.
3011    fn over(self, base: Style) -> Style {
3012        base.size(self.size).font(self.font).color(self.color)
3013    }
3014}
3015
3016impl Builder<'_> {
3017    /// Note that the mark `id` closes with a hidden delimiter, so its content
3018    /// end is a caret home — unless the mark is empty, where the end is the
3019    /// start and there is nothing to extend.
3020    fn note_mark_end(&self, id: usize) {
3021        let node = &self.nodes[id];
3022        if let Some(content) = &node.content_span
3023            && content.end < node.span.end
3024            && !content.is_empty()
3025        {
3026            self.pending_mark_ends.borrow_mut().push(content.end);
3027        }
3028    }
3029
3030    /// The pending mark ends at or before `end_src`, for the row ending there
3031    /// — every mark rendered so far that closes on it. A mark's end never
3032    /// exceeds the end of the row its last glyph is on, so the leftovers are
3033    /// those of rows still to come.
3034    fn take_mark_ends(&self, end_src: usize) -> Vec<usize> {
3035        let mut pending = self.pending_mark_ends.borrow_mut();
3036        let (taken, kept): (Vec<usize>, Vec<usize>) =
3037            pending.drain(..).partition(|&o| o <= end_src);
3038        *pending = kept;
3039        taken
3040    }
3041
3042    /// The pending inline atoms whose glyph is on the row `glyphs` is about
3043    /// to become — each paired with the index of the [`Role::Math`] glyph
3044    /// carrying its offset, in glyph order. An atom whose glyph landed on an
3045    /// earlier row was taken then; one on a later row is left for it. The
3046    /// peer of [`take_mark_ends`](Self::take_mark_ends), and why an atom is
3047    /// keyed by offset: the wrap decides the row, and the offset is what the
3048    /// glyph still carries once it has.
3049    fn take_math(&self, glyphs: &[Glyph]) -> Vec<MathMark> {
3050        let mut pending = self.pending_math.borrow_mut();
3051        if pending.is_empty() {
3052            return Vec::new();
3053        }
3054        let mut out = Vec::new();
3055        for (i, g) in glyphs.iter().enumerate() {
3056            if g.style.role != Role::Math || !g.stop {
3057                continue;
3058            }
3059            if let Some(at) = pending.iter().position(|(src, _)| *src == g.src) {
3060                let (_, mut mark) = pending.remove(at);
3061                mark.glyph = Some(i);
3062                out.push(mark);
3063            }
3064        }
3065        out
3066    }
3067    /// Whether `span` belongs to the line that is showing its raw markup. True
3068    /// only when a reveal line is set *for markup* (`MarkupMode::Full`) and the
3069    /// two ranges actually meet — see [`Reveal::meets`] for what meeting is.
3070    fn revealed(&self, span: &Range<usize>) -> bool {
3071        self.reveal
3072            .as_ref()
3073            .is_some_and(|r| r.markup && r.meets(span))
3074    }
3075
3076    /// Whether a formula at `span` shows its TeX rather than its picture: it
3077    /// meets the reveal line, in *any* mode. A formula's content is its source
3078    /// and not its picture, so for it the choice is not between a clean
3079    /// surface and a raw one but between editable and not — which is why this
3080    /// does not read [`Reveal::markup`] the way [`revealed`](Self::revealed)
3081    /// does.
3082    fn math_revealed(&self, span: &Range<usize>) -> bool {
3083        self.reveal.as_ref().is_some_and(|r| r.meets(span))
3084    }
3085
3086    /// The `(opening, closing)` source byte ranges of a node's delimiters — the
3087    /// bytes its `span` holds that its `content_span` doesn't.
3088    ///
3089    /// This is how *every* inline delimiter is recovered, rather than a table of
3090    /// spellings per kind: twig gives `*em*` a span of `13..17` and a content
3091    /// span of `14..16`, so the gaps at each end are the delimiters, whatever
3092    /// they happen to be. That matters because one kind has many spellings —
3093    /// `*em*` and `_em_` are both emphasis, `` `x` `` and ``` ``x`` ``` both
3094    /// verbatim — and re-deriving the text from the source is the only way to
3095    /// show back what the author actually typed. It also gets a link's
3096    /// asymmetric `[` / `](dest)` right for free.
3097    ///
3098    /// `None` when the node has no content span, or when content and span
3099    /// coincide (nothing was elided, so there is nothing to reveal).
3100    fn delims(&self, id: usize) -> Option<(Range<usize>, Range<usize>)> {
3101        let node = &self.nodes[id];
3102        let content = node.content_span.clone()?;
3103        let span = node.span.clone();
3104        // A content span that escapes its own node's span means the two are
3105        // describing different things; reveal nothing rather than slice wildly.
3106        if content.start < span.start || content.end > span.end {
3107            return None;
3108        }
3109        let (open, close) = (span.start..content.start, content.end..span.end);
3110        // A delimiter that spans a newline isn't this line's to reveal — a setext
3111        // heading's `\n=====` underline is the case that arises in practice. It
3112        // would also inject a `'\n'` glyph, which `emit_wrapped` reads as a hard
3113        // row break, so the row would split where the author wrote no break.
3114        let multiline =
3115            |r: &Range<usize>| self.source.get(r.clone()).is_some_and(|s| s.contains('\n'));
3116        if multiline(&open) || multiline(&close) {
3117            return None;
3118        }
3119        (!open.is_empty() || !close.is_empty()).then_some((open, close))
3120    }
3121
3122    /// Emit the source bytes of `range` as revealed markup — real glyphs, each
3123    /// mapped to its own source byte and each a caret stop, so a delimiter shown
3124    /// is a delimiter that can be selected, edited and deleted like any other
3125    /// text. Styled [`Role::Delimiter`] on top of the run's own style, which is
3126    /// how a frontend tells scaffolding from prose and dims it.
3127    ///
3128    /// Deliberately *not* [`push_escaped_text`]: this is raw source, not parsed
3129    /// text, so there is no escape-driven drift between the two to correct.
3130    fn push_delim(&self, out: &mut Vec<Glyph>, range: &Range<usize>, base: Style) {
3131        let Some(text) = self.source.get(range.clone()) else {
3132            return;
3133        };
3134        push_text(out, text, range.start, base.role(Role::Delimiter));
3135    }
3136
3137    /// Render an inline node's children wrapped in its raw delimiters when the
3138    /// node is on the revealed line, and bare (delimiters resolved away) when it
3139    /// isn't — the shared body of every delimiter-bearing arm of
3140    /// [`inline`](Self::inline).
3141    ///
3142    /// `style` is the resolved styling the content still gets in *both* modes:
3143    /// revealing `*em*` shows the asterisks *and* keeps the text italic, the
3144    /// live-preview behaviour. Showing the markup is not the same as turning the
3145    /// rendering off — that is what [`crate::View::Source`] is for.
3146    fn inline_delimited(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
3147        let show = self
3148            .revealed(&self.nodes[id].span)
3149            .then(|| self.delims(id))
3150            .flatten();
3151        if let Some((open, _)) = &show {
3152            self.push_delim(out, open, style);
3153        }
3154        self.recurse(id, style, out);
3155        match &show {
3156            Some((_, close)) => self.push_delim(out, close, style),
3157            // Hidden, so the content's end has no glyph after it: give the
3158            // caret its home there.
3159            None => self.note_mark_end(id),
3160        }
3161    }
3162
3163    /// A verbatim span — or a formula drawn as its TeX — in the code style:
3164    /// its text at its content's offset, bracketed by its raw delimiters when
3165    /// `show` says the line is revealed and by nothing (plus the caret's home
3166    /// at the content's end) when it isn't.
3167    ///
3168    /// Not [`inline_delimited`](Self::inline_delimited): verbatim has no child
3169    /// nodes to recurse into — its content is its own `text` — so the fences
3170    /// bracket a [`push_text`] instead. The fences themselves keep
3171    /// `Role::Code`'s sibling treatment via [`push_delim`]'s role override.
3172    ///
3173    /// [`push_delim`]: Self::push_delim
3174    fn inline_verbatim(&self, id: usize, base: Style, out: &mut Vec<Glyph>, show: bool) {
3175        let node = &self.nodes[id];
3176        // The interior begins at `content_span.start` — past however many
3177        // backticks the fence used, which `span.start + 1` only guessed right
3178        // for a single one. Fall back to that guess if it's absent.
3179        let at = node
3180            .content_span
3181            .as_ref()
3182            .map_or(node.span.start + 1, |c| c.start);
3183        let style = base.role(Role::Code);
3184        let show = show.then(|| self.delims(id)).flatten();
3185        if let Some((open, _)) = &show {
3186            self.push_delim(out, open, style);
3187        }
3188        push_text(out, node.text.as_deref().unwrap_or(""), at, style);
3189        match &show {
3190            Some((_, close)) => self.push_delim(out, close, style),
3191            None => self.note_mark_end(id),
3192        }
3193    }
3194
3195    fn children(&self, id: usize) -> Vec<usize> {
3196        let mut out = Vec::new();
3197        let mut c = self.nodes[id].first_child;
3198        while let Some(cid) = c {
3199            out.push(cid.0 as usize);
3200            c = self.nodes[cid.0 as usize].next_sibling;
3201        }
3202        out
3203    }
3204
3205    /// Render a node's block children, a blank separator between each. `tight`
3206    /// suppresses the *fabricated* separator between adjacent children that share
3207    /// a source line boundary — a tight list item and the sub-list nested in it —
3208    /// while a real blank source line between them still opens a gap.
3209    fn blocks(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph], tight: bool) {
3210        // Frontmatter (a leading `metadata` block) is document metadata, not
3211        // prose: hide it entirely in the rich-text view. Skipping it here means
3212        // no phantom blank rows for its lines and no separator before the first
3213        // real block — the document opens straight into its content.
3214        let kids: Vec<usize> = self
3215            .children(id)
3216            .into_iter()
3217            .filter(|&c| self.nodes[c].kind != Kind::Metadata)
3218            .collect();
3219        let mut above: Option<BlockClass> = None;
3220        for child in kids {
3221            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
3222            let before_sep = self.rows.len();
3223            if let Some(above) = above {
3224                self.emit_separators_before(
3225                    self.nodes[child].span.start,
3226                    pc,
3227                    !tight,
3228                    Boundary { above, below },
3229                );
3230            }
3231            // The first *drawn* child wears the first-row prefix (a bullet, a
3232            // footnote label), not the first child: a comment opening a list
3233            // item draws nothing, and the bullet belongs to what follows it.
3234            let first = if above.is_none() { pf } else { pc };
3235            if self.block_or_hidden(child, before_sep, first, pc) {
3236                above = Some(below);
3237            }
3238        }
3239    }
3240
3241    /// Render `child` after the separator [`Builder::emit_separators_before`]
3242    /// spelled for it from row `before_sep` on, and say whether it drew
3243    /// anything.
3244    ///
3245    /// A block that draws no rows — an HTML comment, which the rich view hides
3246    /// the way it hides frontmatter — is still *there* in the source, and the
3247    /// walk has to step over it: `last_off` moves past it so the next separator
3248    /// counts the blank lines from its end, not from wherever the last drawn
3249    /// block stopped. Left where it was, the separator counted every line of the
3250    /// comment as a blank row; and the cached path, whose per-block builder
3251    /// starts at offset 0, handed back a `last_off` of 0 and counted every line
3252    /// of the *document* — one phantom blank row per source line, once per
3253    /// comment. The separator drawn for it is taken back too, so a hidden block
3254    /// leaves no gap of its own: what stands either side of it meets across one
3255    /// boundary, as if the comment were not there.
3256    fn block_or_hidden(
3257        &mut self,
3258        child: usize,
3259        before_sep: usize,
3260        pf: &[Glyph],
3261        pc: &[Glyph],
3262    ) -> bool {
3263        let after_sep = self.rows.len();
3264        self.block(child, pf, pc);
3265        if self.rows.len() > after_sep {
3266            return true;
3267        }
3268        self.rows.truncate(before_sep);
3269        let end = self.nodes[child].span.end;
3270        self.last_off = self.last_off.max(end);
3271        self.stepped_over = self.stepped_over.max(end);
3272        false
3273    }
3274
3275    /// Render an explicit, ordered list of top-level blocks — [`Builder::blocks`]
3276    /// for a walk that isn't "the children of one node". The document's top level
3277    /// no longer is: a footnote definition is a root beside `doc`, not under it,
3278    /// and [`top_level`] merges it into this list by source position.
3279    ///
3280    /// The separator between blocks is spelled by the same
3281    /// [`Builder::emit_separators_before`] the incremental top-level walk in
3282    /// [`build_cached`] uses, so the two paths can't drift on how a boundary
3283    /// looks.
3284    ///
3285    /// Returns the class of the last block that drew anything — what the
3286    /// trailing blank lines close — or `None` when nothing did.
3287    fn top_blocks(&mut self, ids: &[usize]) -> Option<BlockClass> {
3288        let mut above: Option<BlockClass> = None;
3289        for &child in ids {
3290            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
3291            let before_sep = self.rows.len();
3292            if let Some(above) = above {
3293                self.emit_separators_before(
3294                    self.nodes[child].span.start,
3295                    &[],
3296                    true,
3297                    Boundary { above, below },
3298                );
3299            }
3300            if self.block_or_hidden(child, before_sep, &[], &[]) {
3301                above = Some(below);
3302            }
3303        }
3304        above
3305    }
3306
3307    /// Emit the blank separator row(s) that sit between a block ending at the
3308    /// current `last_off` and the next block starting at `next_start`, wearing
3309    /// the continuation prefix `pc`. Shared by [`Builder::blocks`] and the
3310    /// incremental top-level walk so the two can't drift on how a boundary is
3311    /// spelled.
3312    ///
3313    /// The blank line(s) between two blocks are real caret stops, each needing
3314    /// its *own* source offset — one strictly past the previous block's content,
3315    /// else it collides with that block's last row and `pos_of_offset`
3316    /// (first-match-wins) would resolve the caret onto the wrong row, pinning
3317    /// downward motion there.
3318    ///
3319    /// One row *per* blank source line, not a single collapsed separator: an
3320    /// empty paragraph opened between two blocks (Enter in the gap,
3321    /// `…\n\n\n\n…`) must be a navigable empty row, not vanish — else the caret
3322    /// in it snaps onto the *next* block's start and Enter looks like it did
3323    /// nothing.
3324    fn emit_separators_before(
3325        &mut self,
3326        next_start: usize,
3327        pc: &[Glyph],
3328        synthetic: bool,
3329        boundary: Boundary,
3330    ) {
3331        let mut offs = self.blank_rows_between(self.last_off, next_start);
3332        if offs.is_empty() {
3333            if !synthetic {
3334                // A tight list item's own text sits directly above the sub-list
3335                // nested in it — no fabricated gap. The "breathe" row belongs
3336                // between free-standing blocks, not between an item and its
3337                // child list, which the source writes on the very next line. A
3338                // real blank source line (a loose list) still lands a gap below,
3339                // because `blank_rows_between` found it and we never reach here.
3340                return;
3341            }
3342            // A tight gap with no blank line (e.g. a heading directly above its
3343            // text): keep the one conventional separator row so blocks still
3344            // breathe, as they always have.
3345            offs.push(self.blank_line_offset(self.last_off, next_start));
3346        }
3347        let last = offs.len() - 1;
3348        for (k, end_src) in offs.into_iter().enumerate() {
3349            // Only the drawn-only rows carry the boundary: the navigable blank
3350            // lines between them (and every blank line under preserve-soft flow)
3351            // are somewhere text can go, not a gap between blocks, and a frontend
3352            // that shrank one would be shrinking a line the author is typing on.
3353            let drawn = !self.preserve_soft && (k == 0 || k == last);
3354            // The blank line a boundary is *drawn* with isn't a place text can
3355            // go. The first one closes the block above and the last one opens the
3356            // block below — with a single blank line, the usual case, doing both
3357            // at once. Typing on either just continues the paragraph it abuts,
3358            // since the blank line it would need to be a paragraph of its own is
3359            // the very line being typed on. So they're a gap, like a table's
3360            // border: drawn, clickable, never a caret's home.
3361            //
3362            // The lines *between* them are the real ones. That's what Enter
3363            // opens: it inserts a paragraph break (`\n\n`), which leaves a blank
3364            // line spare on each side and the caret on the navigable line
3365            // between them.
3366            //
3367            // Preserve flow is the exception: there a bare `\n` is a visible line
3368            // break the author edits directly, so a lone blank line *is* a caret
3369            // home — typing on it makes the soft break the mode exists to show,
3370            // and Enter at a line's end lands the caret on exactly this row. So no
3371            // separator is drawn-only; every blank line is navigable.
3372            self.rows.push(VRow {
3373                glyphs: pc.to_vec(),
3374                end_src,
3375                decoration: drawn,
3376                code: false,
3377                code_lang: None,
3378                directive: false,
3379                directive_label: None,
3380                media: None,
3381                task: None,
3382                leaf_directive: None,
3383                heading: None,
3384                align: None,
3385                line_height: None,
3386                boundary: drawn.then_some(boundary),
3387                mark_ends: Vec::new(),
3388                math: Vec::new(),
3389            });
3390        }
3391    }
3392
3393    /// One block, drawn under whatever presentation the containers around it
3394    /// impose.
3395    ///
3396    /// A container named `div` with `Element` origin is transparent already —
3397    /// its children draw as themselves — and it now also *contributes* its
3398    /// vocabulary keys to every block it holds. That is the reading side of
3399    /// twig's own rule for where a Markdown block's attributes live: there is
3400    /// no attribute syntax to put on the paragraph, so `set_block_attrs` writes
3401    /// a `<div …>` around it, and reading one back has to look through the div.
3402    /// `<div class="center">` around three paragraphs centres all three, which
3403    /// is what the author of that HTML meant, and around one is the sole-child
3404    /// shape twig writes.
3405    ///
3406    /// Saved and restored rather than pushed onto a stack, so a nested div
3407    /// reads its own keys over its parent's and the block *after* the div is
3408    /// unaffected.
3409    fn block(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
3410        if element_tag(&self.nodes[id]) == Some("div") {
3411            let saved = self.presentation;
3412            self.presentation = saved.under(&self.nodes[id].attrs, &self.faces);
3413            self.block_kind(id, pf, pc);
3414            self.presentation = saved;
3415            // Step the walk past the closing `</div>`, as the fenced-div arm
3416            // below anchors past its `:::`. The tag sits on a line of its own
3417            // after the last child and the blank line under it, and the rich
3418            // view draws nothing for it — so left where the last child ended,
3419            // the separator logic read the tag's line as a blank line between
3420            // the div and the block below, and drew a navigable empty row there
3421            // that the author never opened and Backspace could not close; and
3422            // at the end of the document the trailing count read it as an empty
3423            // paragraph the author had left. It is hidden markup the walk steps
3424            // over, which is what `stepped_over` records, so both counts start
3425            // past it.
3426            let end = self.nodes[id].span.end;
3427            self.last_off = self.last_off.max(end);
3428            self.stepped_over = self.stepped_over.max(end);
3429            return;
3430        }
3431        self.block_kind(id, pf, pc);
3432    }
3433
3434    fn block_kind(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
3435        let node = &self.nodes[id];
3436        match node.kind.as_str() {
3437            "doc" | "section" => self.blocks(id, pf, pc, false),
3438            "heading" => {
3439                // A heading whose only visible content is a single image — a
3440                // banner set in an `<h1>` (`<h1><picture><img></picture></h1>`),
3441                // or `# ![](banner.png)` — is a block picture, not text. Render
3442                // it as one; anything with real heading text falls through.
3443                if let Some((m, kind)) = self.media_only(id) {
3444                    self.block_media(m, kind, id, pf);
3445                    return;
3446                }
3447                let level = node.level.unwrap_or(1);
3448                // A `data-size` on a heading scales the *heading's* ramp, not
3449                // the body's — the role and the step compose rather than
3450                // compete, which is the same thing a colour does to a link.
3451                let pres = self.presentation.under(&node.attrs, &self.faces);
3452                let style = pres.over(heading_style(level));
3453                let mut glyphs = Vec::new();
3454                // On the revealed line the `# ` comes back as real, editable
3455                // text in front of the heading. Only the opening marker: a
3456                // closing `#`-run (`## title ##`) is covered by the same
3457                // `delims` pair, and a setext underline is excluded there for
3458                // being on another line entirely.
3459                if let Some((open, close)) =
3460                    self.revealed(&node.span).then(|| self.delims(id)).flatten()
3461                {
3462                    self.push_delim(&mut glyphs, &open, style);
3463                    glyphs.extend(self.inline_children_with_trailing(id, style));
3464                    self.push_delim(&mut glyphs, &close, style);
3465                } else {
3466                    glyphs = self.inline_children_with_trailing(id, style);
3467                }
3468                // An *empty* heading — `# ` with nothing typed after it, which is
3469                // what the toolbar's H1 leaves on a blank line — has no glyph for
3470                // its row to end on, so the fallback below is the row's whole
3471                // extent: its only caret stop, and the offset every row after it
3472                // is measured from. The block's start is the wrong answer for
3473                // both, because it sits *in front of* the `# ` the rich view
3474                // hides: the caret drew (and typed) before the hashes, and the
3475                // rows below inherited an offset short by the marker's length,
3476                // which put the caret on one of them the moment the heading grew
3477                // text. Its content's start is where the caret belongs.
3478                let home = heading_content_start(self.source, &node.span);
3479                let first = self.rows.len();
3480                self.emit_wrapped(glyphs, home, pf, pc);
3481                // Stamp the level on every row the heading just emitted — a
3482                // wrapped heading's continuation rows as much as its first, and
3483                // an empty one's single glyphless row, which is the whole point
3484                // (see [`VRow::heading`]).
3485                for row in &mut self.rows[first..] {
3486                    row.heading = Some(level.min(255) as u8);
3487                    row.align = pres.align;
3488                    row.line_height = pres.line_height;
3489                }
3490            }
3491            "block_quote" => {
3492                let (start, end) = (node.span.start, node.span.end);
3493                let gutter = synth("│ ", Role::QuoteGutter, start);
3494                let f = concat(pf, &gutter);
3495                let c = concat(pc, &gutter);
3496                // A childless quote — a bare `> ` on an otherwise blank line,
3497                // which is what the toolbar's Quote button leaves there — has no
3498                // inner block to carry the gutter or a caret home, so `blocks`
3499                // emitted *nothing at all*: the quote didn't merely draw
3500                // unstyled, it disappeared, and a document that was only `> `
3501                // rendered zero rows with the caret nowhere to stand. Emit the
3502                // gutter row itself, ending just past the marker, exactly as an
3503                // empty `list_item` emits its bare bullet.
3504                if self.children(id).is_empty() {
3505                    self.push_row_at(f, end.min(self.source.len()));
3506                } else {
3507                    self.blocks(id, &f, &c, false);
3508                    self.emit_quote_trailing_lines(&c, end);
3509                }
3510            }
3511            // A generic `:::name{.class}` fenced-div container (twig's
3512            // `directive`, container form). Core is agnostic of `name` — it's
3513            // the host app's vocabulary (diaryx's `vis` for audience
3514            // visibility, say) and isn't available here regardless: twig only
3515            // threads an `element`'s tag name through `FlatNode::name`, not a
3516            // directive's own identifier. Every row gets marked `directive` (a
3517            // frontend draws a tinted panel around each maximal run, the
3518            // `code`/`code_block` recipe) and the first row carries a label —
3519            // the way a code fence's language rides only its first row.
3520            //
3521            // The label reads BOTH attribute conventions diaryx content
3522            // actually uses: twig's own dot-prefixed classes (`{.public
3523            // .family}`, one combined `class` attr) and bare pandoc-style
3524            // words with no leading dot (`{public family}` — the syntax
3525            // `diaryx_core::visibility`'s hand-rolled publish-time filter and
3526            // apps/web's directive serializer both write; twig parses each
3527            // bare word as its own attribute with an empty value, per
3528            // `languages/markdown/attributes.zig`). Reading only `.class`
3529            // would leave every *existing* diaryx `:::vis{...}` block
3530            // unlabeled.
3531            // Only the *container* form is the panel below. A `text` directive
3532            // is inline and never reaches the block walker (see `is_inline`); a
3533            // `leaf` one is a standalone block with no body, drawn as a
3534            // placeholder the way an image is.
3535            "container"
3536                if container_is_directive(node)
3537                    && node.directive_form == Some(DirectiveForm::Leaf) =>
3538            {
3539                self.block_directive(id, pf);
3540            }
3541            // HTML and AsciiDoc spell `insert_directive`'s page break in ways
3542            // of their own — `<page-break></page-break>`, an *element* with
3543            // no form at all, and `<<<`, a directive with none — so neither
3544            // meets the arm above. Both are named `page-break` and empty, and
3545            // both draw the same placeholder, for the same reason djot's
3546            // fence below does: a frontend that paginates on the mark must
3547            // not be able to tell which format the file is in. Narrow to the
3548            // one name: an arbitrary empty custom element is not a leaf
3549            // directive.
3550            "container"
3551                if node.name.as_deref() == Some(crate::doc::PAGE_BREAK)
3552                    && node.directive_form.is_none()
3553                    && node.origin.is_some()
3554                    && self.children(id).is_empty() =>
3555            {
3556                self.block_directive(id, pf);
3557            }
3558            // djot has no *leaf* directive form. `insert_directive` spells the
3559            // same document as an empty `::: page-break` fence — a container
3560            // with nothing in it — and the name comes back as the fence's one
3561            // class rather than as the node's name, because djot's div is
3562            // anonymous. Draw it as the placeholder Markdown's `::page-break`
3563            // gets, so a frontend that paginates on a `page-break`
3564            // [`DirectiveMark`] cannot tell which format the file is in.
3565            //
3566            // Narrow on purpose: only an *anonymous* empty fence. A Markdown
3567            // `:::note` with nothing in it keeps the reading it has, because
3568            // its name is its own and nothing about it says "a block with no
3569            // body" the way djot's spelling of a leaf directive does.
3570            "container"
3571                if container_is_directive(node)
3572                    && node.directive_form == Some(DirectiveForm::Container)
3573                    && node.name.as_deref().unwrap_or_default().is_empty()
3574                    && self.children(id).is_empty()
3575                    && !leaf_directive_identity(node).0.is_empty() =>
3576            {
3577                self.block_directive(id, pf);
3578            }
3579            "container" if container_is_directive(node) => {
3580                let label = directive_attr_label(&node.attrs);
3581                let start_row = self.rows.len();
3582                self.blocks(id, pf, pc, false);
3583                for (i, row) in self.rows[start_row..].iter_mut().enumerate() {
3584                    row.directive = true;
3585                    if i == 0 {
3586                        row.directive_label = label.clone();
3587                    }
3588                }
3589                // Anchor the block's end past its closing `:::` fence, exactly as
3590                // the code-block arm anchors past its ```` ``` ````. A container's
3591                // last content row ends at its last *child*, before the fence and
3592                // the blank line under it, so the separator logic counted the
3593                // fence line as a blank row of its own and drew a second boundary
3594                // — one gap's worth of margin twice, under every fenced div.
3595                self.last_off = node.span.end;
3596            }
3597            "bullet_list" | "ordered_list" | "task_list" => {
3598                let ordered = node.kind == Kind::OrderedList;
3599                let mut item_no = 0usize;
3600                let kids = self.children(id);
3601                for (i, child) in kids.iter().copied().enumerate() {
3602                    let kind = &self.nodes[child].kind;
3603                    if *kind == Kind::ListItem || *kind == Kind::TaskListItem {
3604                        let start = self.nodes[child].span.start;
3605                        item_no += 1;
3606                        // A task item's box replaces the bullet rather than
3607                        // joining it. The `[ ] ` that spells it is markup twig
3608                        // has already consumed — the item's paragraph *content*
3609                        // starts past it — so without a drawn box a task item
3610                        // was indistinguishable from a plain bullet, ticked or
3611                        // not. `☐`/`☑` is the marker for the same reason `•` is:
3612                        // it stands where the source's own marker stands. Which
3613                        // way it faces is `checked`, straight off the node.
3614                        let checked = self.nodes[child].checked;
3615                        let marker = match (checked, ordered) {
3616                            (Some(true), _) => "☑ ".to_string(),
3617                            (Some(false), _) => "☐ ".to_string(),
3618                            (None, true) => format!("{item_no}. "),
3619                            (None, false) => "• ".to_string(),
3620                        };
3621                        let bullet = synth(&marker, Role::ListMarker, start);
3622                        let indent = synth(&" ".repeat(text_width(&marker)), Role::Body, start);
3623                        let first_row = self.rows.len();
3624                        self.block(child, &concat(pc, &bullet), &concat(pc, &indent));
3625                        // On the item's first row, the way `code_lang` rides the
3626                        // first row of its block.
3627                        if let (Some(c), Some(row)) = (checked, self.rows.get_mut(first_row)) {
3628                            row.task = Some(c);
3629                        }
3630                    } else {
3631                        // twig can nest a *following* top-level block as a direct
3632                        // child of the list rather than a sibling of it — e.g.
3633                        // `- item\n\n> quote` parses the block quote under the
3634                        // `bullet_list`. It isn't a list item, so render it de-nested:
3635                        // no bullet, at the list's own prefix, with the usual block
3636                        // separator — never `• │ quote`.
3637                        if i > 0 {
3638                            self.emit_separators_before(
3639                                self.nodes[child].span.start,
3640                                pc,
3641                                true,
3642                                Boundary {
3643                                    above: BlockClass::from_node_kind(
3644                                        &self.nodes[kids[i - 1]].kind,
3645                                    ),
3646                                    below: BlockClass::from_node_kind(&self.nodes[child].kind),
3647                                },
3648                            );
3649                        }
3650                        self.block(child, pc, pc);
3651                    }
3652                }
3653            }
3654            "list_item" | "task_list_item" => {
3655                // A childless item — the empty bullet you get the instant you
3656                // press Enter to open a new one — has no inner block to carry the
3657                // marker prefix or a caret home, so `blocks` would emit nothing
3658                // and the new bullet simply wouldn't appear until something was
3659                // typed into it. Emit the prefixed row itself, ending at a caret
3660                // stop just past the marker (the item's `span.end`), the way an
3661                // empty paragraph emits its one prefixed row via `emit_wrapped`.
3662                if self.children(id).is_empty() {
3663                    let home = self.nodes[id].span.end.min(self.source.len());
3664                    self.push_row_at(pf.to_vec(), home);
3665                } else {
3666                    // Tight: an item's text and the list nested under it butt
3667                    // together (`• a` / `  • b`), no fabricated blank row between —
3668                    // a loose item's real blank line still parts them.
3669                    self.blocks(id, pf, pc, true);
3670                }
3671            }
3672            // A footnote *definition* (`[^1]: the note`). It reaches this walker
3673            // only because [`top_level`] merges it back in — twig hangs it off no
3674            // parent at all, so a walk from `doc` never sees one and every byte
3675            // of its body used to render as nothing.
3676            //
3677            // Drawn as a hanging-indent item, the way a list item is: the marker
3678            // reads `[1] `, matching the `[1]` its references render as, so the
3679            // two can be paired by eye, and the body wraps under it. The marker
3680            // is synthetic decoration (one shared offset, never a caret stop) —
3681            // the `[^1]: ` that spells it in the source is markup, hidden like a
3682            // heading's `# `.
3683            "footnote" => {
3684                let (start, end) = (node.span.start, node.span.end);
3685                let source = self.source;
3686                let marker = format!("[{}] ", footnote_label(source, start).unwrap_or(""));
3687                let indent = " ".repeat(text_width(&marker));
3688                let f = concat(pf, &synth(&marker, Role::ListMarker, start));
3689                let c = concat(pc, &synth(&indent, Role::Body, start));
3690                if self.children(id).is_empty() {
3691                    // A definition with no body yet — the instant `[^1]: ` has
3692                    // been typed and nothing after it. `blocks` would emit
3693                    // nothing and the definition simply wouldn't appear, so emit
3694                    // the marker row itself with a caret home just past it,
3695                    // exactly as an empty list item does.
3696                    self.push_row_at(f, end.min(source.len()));
3697                } else {
3698                    self.blocks(id, &f, &c, false);
3699                }
3700            }
3701            // A link reference definition (`[foo]: /url`): resolved by label
3702            // into the links that use it, and drawn nowhere — the rich view has
3703            // no more use for its line than for a comment's. It is walked at all
3704            // (see [`top_level`]) so [`Builder::block_or_hidden`] can step the
3705            // walk past its bytes rather than count them as blank lines.
3706            "reference" => {}
3707            "table" => self.table(id, pf, pc),
3708            "code_block" => {
3709                let style = Style::default().role(Role::Code);
3710                let text = node.text.clone().unwrap_or_default();
3711                // Cut the block's *terminator*, not every trailing newline. A
3712                // block whose last line is empty spells that as a second `\n`,
3713                // and `trim_end_matches` ate it along with the terminator: the
3714                // Return that made the line got no row, so the caret placed on
3715                // it fell through to the paragraph below and typing landed
3716                // outside the block. twig's `content_span` is `text` less
3717                // exactly this one newline, so cutting one and no more is also
3718                // what keeps `code_line_offsets` lined up.
3719                let lines: Vec<&str> = text
3720                    .strip_suffix('\n')
3721                    .unwrap_or(text.as_str())
3722                    .split('\n')
3723                    .collect();
3724                // Each line at its own source offset, so the caret can walk the
3725                // code a character at a time like any other text. Where the
3726                // lines can't be lined up with the source there's no honest
3727                // offset to give, so the block maps coarsely to its start (and
3728                // stays a source-view job, as all of it once was).
3729                let offs = node
3730                    .content_span
3731                    .as_ref()
3732                    .and_then(|c| self.code_line_offsets(c, &lines));
3733                // The fence's info string, carried on the block's first row as
3734                // its language label (`None` for an indented block or a bare
3735                // fence). Kept on the row so it rides the block cache.
3736                let lang = code_language(self.source, node.span.start);
3737                // The block's syntax highlighting, a token per byte range of
3738                // each line — `None` unless the fence names a language the
3739                // grammars know (and unless the `syntax` feature is on). Done
3740                // here, once per build of the block, because the rows it
3741                // colours ride the block cache: an edit elsewhere in the
3742                // document reuses them, tokens and all.
3743                let tokens = lang.as_deref().and_then(|l| code_tokens(l, &lines));
3744                for (i, raw) in lines.iter().enumerate() {
3745                    let at = offs.as_ref().map_or(node.span.start, |o| o[i]);
3746                    // No gutter glyph: the block is set apart by the border and
3747                    // tint a frontend draws around the whole run of `code` rows,
3748                    // not by a per-line mark. Just the block prefix (a list
3749                    // indent, a quote gutter) and the code text.
3750                    let mut glyphs: Vec<Glyph> = pf.to_vec();
3751                    match tokens.as_ref().and_then(|t| t.get(i)) {
3752                        Some(spans) => push_code_text(&mut glyphs, raw, at, style, spans),
3753                        None => push_text(&mut glyphs, raw, at, style),
3754                    }
3755                    // Explicitly past the line's *text*: a blank code line has no
3756                    // glyph, and any prefix's offset would put the row's end
3757                    // inside the next line.
3758                    self.push_row_at(glyphs, at + raw.len());
3759                    if let Some(row) = self.rows.last_mut() {
3760                        row.code = true;
3761                        if i == 0 {
3762                            row.code_lang = lang.clone();
3763                        }
3764                    }
3765                }
3766                // Anchor the block's end past its closing fence. Its last content
3767                // row ends at the last code line, before the ``` and the blank
3768                // line under it; without this the separator logic would count the
3769                // closing-fence line as its own blank row and open a phantom
3770                // second gap below the block.
3771                self.last_off = node.span.end;
3772            }
3773            "thematic_break" => {
3774                let full = self.wrap.unwrap_or(UNWRAPPED_RULE_WIDTH);
3775                let w = full.saturating_sub(prefix_width(pf)).max(4);
3776                let mut glyphs = pf.to_vec();
3777                for _ in 0..w {
3778                    glyphs.push(Glyph {
3779                        ch: '─',
3780                        style: Style::default().role(Role::Rule),
3781                        src: node.span.start,
3782                        // A rule is a block the caret can sit on, as it always
3783                        // has; it maps coarsely to the block's start.
3784                        stop: true,
3785                    });
3786                }
3787                // The dashes share one caret home in front of the atomic block,
3788                // while the row's end is the second home just past its source.
3789                // Without that trailing stop a final rule made the document end
3790                // unreachable: Right could not cross it and a click in the
3791                // empty space below it snapped back before the rule.
3792                let after_line = node.span.end
3793                    + self.source[node.span.end..]
3794                        .strip_prefix("\r\n")
3795                        .map_or_else(
3796                            || usize::from(self.source[node.span.end..].starts_with('\n')),
3797                            |_| 2,
3798                        );
3799                self.push_row_at(glyphs, after_line);
3800            }
3801            // A block-level image node with no wrapping paragraph — a promoted
3802            // top-level HTML `<img>` lands as a direct `doc` child like this
3803            // (a Markdown `![](…)` comes wrapped in a `para`, handled below).
3804            "image" => self.block_media(id, MediaKind::Image, id, pf),
3805            // The same case for a promoted top-level `<video>`/`<audio>`, which
3806            // arrives as a generic `container` rather than a node kind of its
3807            // own. It can't be found by the `media_only` scan below the way a
3808            // wrapped one is: that scan looks at a wrapper's *children*, and here
3809            // the media element is itself the block.
3810            "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
3811                let kind = match element_tag(node) {
3812                    Some("audio") => MediaKind::Audio,
3813                    _ => MediaKind::Video,
3814                };
3815                self.block_media(id, kind, id, pf);
3816            }
3817            _ => {
3818                // A container of blocks, or an inline-bearing paragraph.
3819                let kids = self.children(id);
3820                // A block-level image: a paragraph (or other wrapper — a
3821                // `<picture>`, an `<h1>` banner) whose only visible content is a
3822                // single `image` node. Render it as a placeholder row + record an
3823                // [`MediaInfo`] a capable frontend replaces. An image mixed with
3824                // real text or other images on the line isn't block-level and
3825                // falls through to the inline path below, still as its alt text.
3826                if let Some((m, kind)) = self.media_only(id) {
3827                    self.block_media(m, kind, id, pf);
3828                    return;
3829                }
3830                // A display formula on lines of its own — a paragraph whose
3831                // only visible content is one `display_math` — promotes the
3832                // same way, to a placeholder row and a [`MathMark`].
3833                if let Some(m) = self.math_only(id) {
3834                    self.block_math(m, pf, pc);
3835                    return;
3836                }
3837                let inline = !kids.is_empty() && kids.iter().all(|&c| is_inline(&self.nodes[c]));
3838                if inline || kids.is_empty() {
3839                    // The block's own attributes over its containers' — the
3840                    // three run-level keys become the style its glyphs start
3841                    // from, and the two line-level ones ride every row it
3842                    // emits, a wrapped paragraph's continuations included.
3843                    let pres = self.presentation.under(&node.attrs, &self.faces);
3844                    let glyphs =
3845                        self.inline_children_with_trailing(id, pres.over(Style::default()));
3846                    if !glyphs.is_empty() {
3847                        let first = self.rows.len();
3848                        self.emit_wrapped(glyphs, node.span.start, pf, pc);
3849                        for row in &mut self.rows[first..] {
3850                            row.align = pres.align;
3851                            row.line_height = pres.line_height;
3852                        }
3853                    }
3854                } else {
3855                    self.blocks(id, pf, pc, false);
3856                }
3857            }
3858        }
3859    }
3860
3861    /// Render a table as a box-drawn grid: every column as wide as its widest
3862    /// cell, the header bold and ruled off, each cell padded to its column's
3863    /// alignment. This is the *default* monospace rendering (see
3864    /// [`VisualMap::rows`]); the same cells are also published structurally as
3865    /// [`TableInfo`], so a frontend that lays the grid out in its own units draws
3866    /// from there and skips the picture built here.
3867    ///
3868    /// The alignment comes from twig's `cell.alignment` — the delimiter row
3869    /// (`|:--|--:|`) that spells it out is consumed by the parser and leaves no
3870    /// node, so the snapshot is the only source for it.
3871    ///
3872    /// Borders and padding are *decoration*: they carry the source offset of the
3873    /// text they surround, so a click lands in that cell, but they're never
3874    /// caret stops — the caret steps cell-to-cell instead of into the box art.
3875    fn table(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
3876        let node_end = self.nodes[id].span.end;
3877        // twig's shape is `[caption, row, row, …]`: the caption is always
3878        // present (usually empty in Markdown) and is not part of the grid.
3879        let row_ids: Vec<usize> = self
3880            .children(id)
3881            .into_iter()
3882            .filter(|&c| self.nodes[c].kind == Kind::Row)
3883            .collect();
3884        if row_ids.is_empty() {
3885            return;
3886        }
3887        // Lay every cell out first — the column widths depend on all of them.
3888        let grid: Vec<Vec<TableCell>> = row_ids.iter().map(|&r| self.row_cells(r)).collect();
3889        let heads: Vec<bool> = row_ids
3890            .iter()
3891            .map(|&r| self.nodes[r].head.unwrap_or(false))
3892            .collect();
3893        let cols = grid.iter().map(|r| r.len()).max().unwrap_or(0);
3894        if cols == 0 {
3895            return;
3896        }
3897        let mut widths = vec![0usize; cols];
3898        for row in &grid {
3899            for (c, cell) in row.iter().enumerate() {
3900                widths[c] = widths[c].max(cell_width(&cell.glyphs));
3901            }
3902        }
3903        // Every column at its widest cell is only the *wish*; a grid wider than
3904        // the surface has its far side hanging off the edge where no amount of
3905        // caret motion can reach it. Cut it down to what's actually there, and
3906        // let the cells wrap into the space they're given.
3907        if let Some(w) = self.wrap {
3908            fit_widths(&mut widths, w.saturating_sub(prefix_width(pc)));
3909        }
3910
3911        // Where the picture starts, so a frontend drawing its own grid knows
3912        // which rows to skip. Recorded before the first border goes down.
3913        let rows_start = self.rows.len();
3914
3915        let anchor = grid[0].first().map(|c| c.start).unwrap_or(node_end);
3916        self.push_rule(&rule_text(&widths, '┌', '┬', '┐'), anchor, pf);
3917        for (ri, row) in grid.iter().enumerate() {
3918            self.push_table_row(row, &widths, pc);
3919            // The rule under the header: only where the head actually ends.
3920            let ends_head = heads[ri] && heads.get(ri + 1) == Some(&false);
3921            if ends_head {
3922                let next = grid[ri + 1].first().map(|c| c.start).unwrap_or(node_end);
3923                self.push_rule(&rule_text(&widths, '├', '┼', '┤'), next, pc);
3924            }
3925        }
3926        // The bottom border is the one rule the caret can rest on: its end is
3927        // the table's trailing stop, the caret home just past the block — the
3928        // peer of a block picture's second stop, and of a rule's row end. Without
3929        // it a document ending in a table ended *inside* it: nothing after the
3930        // last cell was a stop, so Right could not leave the table, and a click
3931        // in the blank space under it snapped back into the last cell — or, on a
3932        // surface that resolved the click onto the border row, to the table's
3933        // first cell, since a decoration row's only stop is the nearest one.
3934        // Typing at the stop opens a paragraph first, as at a picture's — see
3935        // `Doc::open_paragraph_at_block_edge`. The glyphs stay non-stops at
3936        // `node_end`, so a click anywhere on the border lands past the table.
3937        self.push_rule_with_home(&rule_text(&widths, '└', '┴', '┘'), node_end, pc);
3938
3939        // The same cells the picture above was drawn from, published unwrapped
3940        // and unpadded for a frontend that lays them out in pixels.
3941        self.tables.push(TableInfo {
3942            rows_span: rows_start..self.rows.len(),
3943            end_src: node_end,
3944            // The *continuation* prefix: `pf` opens the block and only its first
3945            // row wears it, but every row of a grid is a continuation of the
3946            // block the table sits in.
3947            prefix: pc.to_vec(),
3948            grid: grid
3949                .into_iter()
3950                .zip(heads)
3951                .map(|(cells, head)| TableRow { head, cells })
3952                .collect(),
3953        });
3954        // The table's own end anchors whatever separator follows it; the border
3955        // rows deliberately don't move `last_off` (they hold no content).
3956        self.last_off = node_end;
3957    }
3958
3959    /// One row of laid-out cells, in column order.
3960    fn row_cells(&self, row: usize) -> Vec<TableCell> {
3961        // A cell is one source line, so a break within it is an explicit line
3962        // break (an inline `<br>`) that must render as a line of its own — not the
3963        // flow-folding space a break is in prose.
3964        self.break_glyph.set('\n');
3965        let cells = self
3966            .children(row)
3967            .into_iter()
3968            .filter(|&c| self.nodes[c].kind == Kind::Cell)
3969            .enumerate()
3970            .map(|(col, c)| {
3971                let n = &self.nodes[c];
3972                let style = if n.head.unwrap_or(false) {
3973                    Style::default().bold()
3974                } else {
3975                    Style::default()
3976                };
3977                // Only `content_span` bounds a cell's text, and an EMPTY cell
3978                // has none at all — twig records no interior for it — so both
3979                // offsets would fall back to the cell's `span.start`: on the
3980                // pipe that opens it, or (under a twig that gave every cell
3981                // the whole row's span) the row's start, where every empty
3982                // cell collapses onto one spot before the first `│` and a
3983                // caret there types *before* the table. Derive the interior
3984                // from the span's own pipes and this cell's column instead,
3985                // so each empty cell has a distinct, editable caret home.
3986                let span = n.content_span.clone().unwrap_or_else(|| {
3987                    let off = empty_cell_offset(
3988                        &self.source[n.span.start.min(self.source.len())
3989                            ..n.span.end.min(self.source.len())],
3990                        n.span.start,
3991                        col,
3992                    );
3993                    off..off
3994                });
3995                TableCell {
3996                    glyphs: self.inline_children(c, style),
3997                    start: span.start,
3998                    end: span.end,
3999                    align: n.alignment.unwrap_or(Alignment::Default),
4000                }
4001            })
4002            .collect();
4003        self.break_glyph.set(' ');
4004        cells
4005    }
4006
4007    /// A horizontal rule between/around rows — entirely decoration.
4008    fn push_rule(&mut self, text: &str, src: usize, prefix: &[Glyph]) {
4009        self.push_rule_row(text, src, prefix, true);
4010    }
4011
4012    /// A table's bottom border: drawn like the other rules, but a row the caret
4013    /// can rest on, its end (`src`) being the table's trailing stop.
4014    fn push_rule_with_home(&mut self, text: &str, src: usize, prefix: &[Glyph]) {
4015        self.push_rule_row(text, src, prefix, false);
4016    }
4017
4018    fn push_rule_row(&mut self, text: &str, src: usize, prefix: &[Glyph], decoration: bool) {
4019        let glyphs = concat(prefix, &synth(text, Role::Rule, src));
4020        self.rows.push(VRow {
4021            glyphs,
4022            end_src: src,
4023            decoration,
4024            code: false,
4025            code_lang: None,
4026            directive: false,
4027            directive_label: None,
4028            media: None,
4029            task: None,
4030            leaf_directive: None,
4031            heading: None,
4032            align: None,
4033            line_height: None,
4034            boundary: None,
4035            mark_ends: Vec::new(),
4036            math: Vec::new(),
4037        });
4038    }
4039
4040    /// One `│ a │ b │` row of the grid: real cell text between decoration.
4041    ///
4042    /// A row of cells is not a row of the screen — a cell wrapped to its column
4043    /// spans several, each one `│`-divided across the full width so the grid
4044    /// stays square. Cells in the same row are laid out independently and run
4045    /// out at their own heights; a column that has run dry pads out as
4046    /// decoration while its neighbours keep going.
4047    fn push_table_row(&mut self, cells: &[TableCell], widths: &[usize], prefix: &[Glyph]) {
4048        let fallback = cells.last().map(|c| c.end).unwrap_or(0);
4049        let laid: Vec<Vec<Vec<Glyph>>> = cells
4050            .iter()
4051            .enumerate()
4052            .map(|(ci, c)| wrap_glyphs(&c.glyphs, widths.get(ci).copied().unwrap_or(0)))
4053            .collect();
4054        let height = laid.iter().map(|l| l.len()).max().unwrap_or(1).max(1);
4055
4056        for j in 0..height {
4057            let mut glyphs = prefix.to_vec();
4058            for (ci, &w) in widths.iter().enumerate() {
4059                let cell = cells.get(ci);
4060                let line = laid.get(ci).and_then(|l| l.get(j));
4061                // The divider before this column belongs to the cell it
4062                // introduces, so clicking it lands in that cell — on this line
4063                // of it, which is what's next to the divider being clicked.
4064                let at = line
4065                    .and_then(|l| l.first().map(|g| g.src))
4066                    .or_else(|| cell.map(|c| c.start))
4067                    .unwrap_or(fallback);
4068                glyphs.extend(synth("│", Role::Rule, at));
4069                match (cell, line) {
4070                    (Some(cell), Some(line)) => {
4071                        let pad = w.saturating_sub(glyphs_width(line));
4072                        let (lead, trail) = match cell.align {
4073                            Alignment::Right => (pad, 0),
4074                            Alignment::Center => (pad / 2, pad - pad / 2),
4075                            Alignment::Left | Alignment::Default => (0, pad),
4076                        };
4077                        // Every line renders at least one space after its text
4078                        // (the gutter before `│`), so there is always somewhere
4079                        // to put the "after the last character" caret a line
4080                        // needs. It's the one padding glyph that is a stop: on
4081                        // the cell's last line that's the cell's end, and on any
4082                        // other it's the space the wrap consumed.
4083                        let last = laid[ci].len() == j + 1;
4084                        let end = match last {
4085                            true => cell.end,
4086                            false => line
4087                                .last()
4088                                .map(|g| g.src + g.ch.len_utf8())
4089                                .unwrap_or(cell.end),
4090                        };
4091                        glyphs.extend(synth(&" ".repeat(lead + 1), Role::Body, at));
4092                        glyphs.extend(line.iter().cloned());
4093                        glyphs.push(Glyph {
4094                            ch: ' ',
4095                            style: Style::default(),
4096                            src: end,
4097                            stop: true,
4098                        });
4099                        glyphs.extend(synth(&" ".repeat(trail), Role::Body, end));
4100                    }
4101                    // A ragged row, or a column whose cell ended higher up: pad
4102                    // it out so the grid stays square.
4103                    _ => {
4104                        let at = cell.map(|c| c.end).unwrap_or(fallback);
4105                        glyphs.extend(synth(&" ".repeat(w + 2), Role::Body, at));
4106                    }
4107                }
4108            }
4109            glyphs.extend(synth("│", Role::Rule, fallback));
4110            // The row ends where its last stop does. A table row has no gap
4111            // between its final cell and the border, so inventing an end past
4112            // that would be a stop with nothing under it.
4113            let end_src = glyphs
4114                .iter()
4115                .rev()
4116                .find(|g| g.stop)
4117                .map_or(fallback, |g| g.src);
4118            let mark_ends = self.take_mark_ends(end_src);
4119            let math = self.take_math(&glyphs);
4120            self.rows.push(VRow {
4121                glyphs,
4122                end_src,
4123                decoration: false,
4124                code: false,
4125                code_lang: None,
4126                directive: false,
4127                directive_label: None,
4128                media: None,
4129                task: None,
4130                leaf_directive: None,
4131                heading: None,
4132                align: None,
4133                line_height: None,
4134                boundary: None,
4135                mark_ends,
4136                math,
4137            });
4138        }
4139    }
4140
4141    /// Render a block-level image, video, or audio as one placeholder row: the
4142    /// `🖼 alt` / `🎬 alt` / `🔊 alt` label styled [`Role::Image`], every glyph
4143    /// mapped to the media's start offset and a caret stop there (they share the
4144    /// offset, so the stop table dedups them to a single home in front of it, as
4145    /// a rule's dashes do), and the row's end stop set past it so the caret can
4146    /// also rest after it. The row carries a [`MediaMark`] so [`media_spans`]
4147    /// publishes it as a [`MediaInfo`] a capable frontend replaces with the real
4148    /// picture or player; a plain surface paints the label as-is. `pf` is the
4149    /// block prefix (a list indent, a quote gutter) the row opens with, exactly
4150    /// as every other block honours it.
4151    fn block_media(&mut self, img: usize, kind: MediaKind, wrapper: usize, pf: &[Glyph]) {
4152        let node = &self.nodes[img];
4153        let start = node.span.start;
4154        let end = node.span.end;
4155        // An `image`'s URL is twig's `destination`; a `<video>`/`<audio>` is a
4156        // generic element, so its URL is the `src` attribute — and may be absent
4157        // entirely, the element naming its candidates in child `<source>`s.
4158        let destination = match kind {
4159            MediaKind::Image => node.destination.clone().unwrap_or_default(),
4160            MediaKind::Video | MediaKind::Audio => attr_of(node, "src").unwrap_or_default(),
4161        };
4162        let poster = match kind {
4163            MediaKind::Video => attr_of(node, "poster").unwrap_or_default(),
4164            MediaKind::Image | MediaKind::Audio => String::new(),
4165        };
4166        // The `<source>`s under the media element itself, not under `wrapper`: a
4167        // `<video>` is its own container, unlike an `<img>`, whose `<picture>`
4168        // alternatives are its *siblings* and so only reachable from the wrapper.
4169        let sources = match kind {
4170            MediaKind::Image => self.media_sources(wrapper),
4171            MediaKind::Video | MediaKind::Audio => self.media_sources(img),
4172        };
4173        let alt = self.image_alt(img);
4174        let sigil = kind.sigil();
4175        let label = if alt.is_empty() {
4176            // With no alt, name the file — but a `<video>` with neither `src` nor
4177            // alt has only its `<source>`s to be named by, so fall back to the
4178            // first candidate rather than labelling the row a bare sigil.
4179            let named = if destination.is_empty() {
4180                sources
4181                    .first()
4182                    .map(|s| s.srcset.as_str())
4183                    .unwrap_or_default()
4184            } else {
4185                &destination
4186            };
4187            format!("{sigil} {}", media_label(named))
4188        } else {
4189            format!("{sigil} {alt}")
4190        };
4191        let style = Style::default().role(Role::Image);
4192        let mut glyphs = pf.to_vec();
4193        for ch in label.chars() {
4194            glyphs.push(Glyph {
4195                ch,
4196                style,
4197                src: start,
4198                stop: true,
4199            });
4200        }
4201        // How many rows the frontend wants for this picture: the label row plus
4202        // the blank fillers below it. Absent (a GUI that lays images out in
4203        // pixels, an image that didn't resolve, or a plain surface) means the
4204        // bare one-row placeholder.
4205        let rows = self
4206            .surface
4207            .media_rows
4208            .get(&destination)
4209            .copied()
4210            .unwrap_or(1)
4211            .max(1);
4212        // End past the image so the caret has a stop after it: the last glyph's
4213        // offset is the image *start*, not its extent, so `push_row`'s
4214        // last-glyph rule would strand the end stop inside the markup.
4215        self.push_row_at(glyphs, end);
4216        if let Some(row) = self.rows.last_mut() {
4217            row.media = Some(MediaMark {
4218                kind,
4219                destination,
4220                sources,
4221                alt,
4222                poster,
4223                rows,
4224            });
4225        }
4226        // Reserve the picture's remaining height as blank `decoration` rows: drawn
4227        // (so the frontend has the vertical room to paint the raster over them),
4228        // but holding no caret and contributing no stops — vertical motion steps
4229        // over them and the caret's only homes stay the stop in front of the image
4230        // and the one just past it, both on the label row above. They anchor at the
4231        // image's end offset so a click on the picture's lower half lands after it,
4232        // the nearest caret home. Mirrors how a table's box-rule rows reserve space
4233        // without ever holding the caret.
4234        for _ in 1..rows {
4235            self.rows.push(VRow {
4236                glyphs: Vec::new(),
4237                end_src: end,
4238                decoration: true,
4239                code: false,
4240                code_lang: None,
4241                directive: false,
4242                directive_label: None,
4243                media: None,
4244                task: None,
4245                leaf_directive: None,
4246                heading: None,
4247                align: None,
4248                line_height: None,
4249                boundary: None,
4250                mark_ends: Vec::new(),
4251                math: Vec::new(),
4252            });
4253        }
4254        self.last_off = end;
4255    }
4256
4257    /// The `<picture>` alternatives inside block-image `wrapper`, in document
4258    /// order — every `<source>` element in its subtree. Empty when there's no
4259    /// `<picture>`. Each is a `<source>`'s `media` + `srcset`; core keeps them
4260    /// verbatim and picks none (see [`MediaSource`]). A `<source>` with no
4261    /// `srcset` is dropped (nothing to load); its `media` may be empty (an
4262    /// unconditional override), which a frontend treats as always-matching.
4263    ///
4264    /// It scans the wrapper's whole subtree (via the forward `first_child` /
4265    /// `next_sibling` links, the reliable ones) rather than the `<img>`'s parent,
4266    /// for two reasons. A `<picture>` reaches core in two shapes: twig promotes a
4267    /// block `<picture>` to an `element(picture)` wrapping `[source, img]`, but
4268    /// leaves an inline one's tags as raw siblings — `[raw "<picture>", source,
4269    /// img, raw "</picture>"]` — so the `<source>`s sit at different depths in
4270    /// the two. And the editor's flat arena leaves a promoted inline node's
4271    /// `parent` back-pointer dangling on a phantom root, so only the wrapper
4272    /// (known at the call site) is a trustworthy anchor. A block image is the
4273    /// sole visible content of its wrapper, so every `<source>` under it is its
4274    /// picture's.
4275    fn media_sources(&self, wrapper: usize) -> Vec<MediaSource> {
4276        let mut out = Vec::new();
4277        self.collect_sources(wrapper, &mut out);
4278        out
4279    }
4280
4281    fn collect_sources(&self, id: usize, out: &mut Vec<MediaSource>) {
4282        for c in self.children(id) {
4283            let node = &self.nodes[c];
4284            if node.name.as_deref() == Some("source") {
4285                // `<picture>` spells its candidate `srcset`, `<video>`/`<audio>`
4286                // spell it `src`. Both mean "the URL to load", so they normalise
4287                // onto one field; `srcset` wins where (illegally) both appear.
4288                let url = attr_of(node, "srcset").or_else(|| attr_of(node, "src"));
4289                if let Some(srcset) = url {
4290                    out.push(MediaSource {
4291                        media: attr_of(node, "media").unwrap_or_default(),
4292                        srcset,
4293                        mime: attr_of(node, "type").unwrap_or_default(),
4294                    });
4295                }
4296            }
4297            self.collect_sources(c, out);
4298        }
4299    }
4300
4301    /// The single block-level media `id`'s subtree resolves to, or `None`.
4302    ///
4303    /// A wrapper is a block picture when the only *visible* thing under it is one
4304    /// image: whitespace-only text and structure-only elements (a `<picture>`'s
4305    /// `<source>`, which declares an alternate but paints nothing) don't count,
4306    /// and the search descends through wrapping elements (`<picture>`, a linking
4307    /// `<a>`). This is what makes `<p><img></p>`, a bare `<img>`, and
4308    /// `<h1><picture>…<img></picture></h1>` all render as one framed picture.
4309    /// Any real text, or a second image, means it isn't image-only — it falls
4310    /// back to inline rendering, where the image still shows as its alt text.
4311    ///
4312    /// [`FlatNode`]'s snapshot doesn't carry an element's tag name, so a
4313    /// `<source>` can't be skipped by name — but it needs no special case:
4314    /// contributing no image and no text, it's simply invisible to the scan.
4315    fn media_only(&self, id: usize) -> Option<(usize, MediaKind)> {
4316        let mut found = None;
4317        let mut count = 0usize;
4318        let mut has_text = false;
4319        self.scan_visual(id, &mut found, &mut count, &mut has_text);
4320        (count == 1 && !has_text).then(|| found.unwrap())
4321    }
4322
4323    /// Walk `id`'s subtree tallying visible leaves for [`media_only`]: each
4324    /// image, `<video>`, or `<audio>` (remembering the last, counting the total)
4325    /// and whether any non-whitespace text appears. Media isn't descended into —
4326    /// an image's inline children are alt text, and a `<video>`'s are its
4327    /// no-support fallback and its `<source>` declarations, none of which is
4328    /// document content.
4329    ///
4330    /// [`media_only`]: Self::media_only
4331    fn scan_visual(
4332        &self,
4333        id: usize,
4334        found: &mut Option<(usize, MediaKind)>,
4335        count: &mut usize,
4336        has_text: &mut bool,
4337    ) {
4338        for c in self.children(id) {
4339            let node = &self.nodes[c];
4340            match node.kind.as_str() {
4341                "image" => {
4342                    *found = Some((c, MediaKind::Image));
4343                    *count += 1;
4344                }
4345                // A `<video>`/`<audio>` reaches core as a generic `container`
4346                // (twig gives neither a semantic node, so `html_elements`
4347                // promotion leaves the tag name on `name`). Counted as media and
4348                // *not* descended into, so its `<source>` children and its
4349                // "your browser does not support…" fallback text neither add a
4350                // second count nor make the block look like text.
4351                "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
4352                    let kind = match element_tag(node) {
4353                        Some("audio") => MediaKind::Audio,
4354                        _ => MediaKind::Video,
4355                    };
4356                    *found = Some((c, kind));
4357                    *count += 1;
4358                }
4359                // Text leaves: only non-whitespace counts as visible content.
4360                // (Twig keeps the whitespace `str`s between HTML tags — the
4361                // newlines and indentation inside a `<picture>` — as real nodes.)
4362                "str" | "smart_punctuation" | "verbatim" | "inline_math" | "display_math" => {
4363                    if node.text.as_deref().is_some_and(|t| !t.trim().is_empty()) {
4364                        *has_text = true;
4365                    }
4366                }
4367                // Structural breaks carry no visible glyph of their own.
4368                "soft_break" | "hard_break" | "non_breaking_space" => {}
4369                // Any other wrapper (emphasis, a link, a `<picture>`) is
4370                // transparent to the scan — descend into it.
4371                _ => self.scan_visual(c, found, count, has_text),
4372            }
4373        }
4374    }
4375
4376    /// The single `display_math` that is all of `id`'s visible content, or
4377    /// `None` — [`media_only`](Self::media_only) for a formula. Whitespace-only
4378    /// text around it does not count (twig keeps the newlines either side of a
4379    /// `$$` on its own lines as `str`s); any other text, or a second formula,
4380    /// means the paragraph is prose with math in it, and falls through to the
4381    /// inline path.
4382    fn math_only(&self, id: usize) -> Option<usize> {
4383        let mut found = None;
4384        let mut count = 0usize;
4385        for c in self.children(id) {
4386            let node = &self.nodes[c];
4387            match node.kind.as_str() {
4388                "display_math" => {
4389                    found = Some(c);
4390                    count += 1;
4391                }
4392                "str" | "smart_punctuation" => {
4393                    if node.text.as_deref().is_some_and(|t| !t.trim().is_empty()) {
4394                        return None;
4395                    }
4396                }
4397                "soft_break" | "hard_break" | "non_breaking_space" => {}
4398                _ => return None,
4399            }
4400        }
4401        (count == 1).then(|| found.unwrap())
4402    }
4403
4404    /// A display formula on lines of its own, drawn on
4405    /// [`block_media`](Self::block_media)'s recipe: one placeholder row —
4406    /// `∑` and the TeX on one line, every glyph [`Role::Math`] at the
4407    /// formula's start and a caret stop there, the row ending past the
4408    /// formula so the caret can rest after it too — carrying a [`MathMark`]
4409    /// for [`math_spans`] to publish, and under it as many blank decoration
4410    /// rows as the frontend said the picture is tall
4411    /// ([`Surface::math_rows`]).
4412    ///
4413    /// On the caret's line the block is its source instead: the `$$`
4414    /// delimiters in [`Role::Delimiter`] and the TeX between them in
4415    /// [`Role::Code`], line for line, the way a fence draws — so a formula is
4416    /// edited where it stands and folds back to its picture when the caret
4417    /// leaves. That is the same rule an inline formula follows, and it is
4418    /// what makes a block-level formula need no equivalent of
4419    /// [`VisualMap::block_media_stop`]: both of the placeholder's caret homes
4420    /// are on the formula's own lines, and standing on either reveals it.
4421    fn block_math(&mut self, math: usize, pf: &[Glyph], pc: &[Glyph]) {
4422        self.saw_math.set(true);
4423        let node = &self.nodes[math];
4424        let (start, end) = (node.span.start, node.span.end);
4425        let tex = node.text.clone().unwrap_or_default();
4426        if self.math_revealed(&node.span) {
4427            let mut glyphs = Vec::new();
4428            self.inline_verbatim(math, Style::default(), &mut glyphs, true);
4429            self.emit_wrapped(glyphs, start, pf, pc);
4430            self.last_off = end;
4431            return;
4432        }
4433        let style = Style::default().role(Role::Math);
4434        let mut glyphs = pf.to_vec();
4435        // One line of label: the TeX with its newlines folded, so the row
4436        // reads as one thing however the source laid it out.
4437        let label: String = tex.split_whitespace().collect::<Vec<_>>().join(" ");
4438        for ch in format!("{MATH_ATOM} {label}").chars() {
4439            glyphs.push(Glyph {
4440                ch,
4441                style,
4442                src: start,
4443                stop: true,
4444            });
4445        }
4446        let rows = self
4447            .surface
4448            .math_rows
4449            .get(&tex)
4450            .copied()
4451            .unwrap_or(1)
4452            .max(1);
4453        self.push_row_at(glyphs, end);
4454        if let Some(row) = self.rows.last_mut() {
4455            row.math = vec![MathMark {
4456                tex,
4457                display: true,
4458                glyph: None,
4459                rows,
4460            }];
4461        }
4462        for _ in 1..rows {
4463            self.rows.push(VRow {
4464                glyphs: Vec::new(),
4465                end_src: end,
4466                decoration: true,
4467                code: false,
4468                code_lang: None,
4469                directive: false,
4470                directive_label: None,
4471                media: None,
4472                task: None,
4473                leaf_directive: None,
4474                heading: None,
4475                align: None,
4476                line_height: None,
4477                boundary: None,
4478                mark_ends: Vec::new(),
4479                math: Vec::new(),
4480            });
4481        }
4482        self.last_off = end;
4483    }
4484
4485    /// A leaf directive (`::name{…}`) as one placeholder row — the
4486    /// [`block_media`](Self::block_media) recipe, for the same reason: it is a
4487    /// block that renders as *a thing*, not as text, and the frontend paints
4488    /// whatever the host app's vocabulary makes of it.
4489    ///
4490    /// The row's glyphs are a `⧉ label` (or `⧉ name`) stand-in a plain surface
4491    /// paints as-is, every glyph anchored at the directive's start with a caret
4492    /// stop there, and the row ending past it so the caret can also rest after
4493    /// it. It carries a [`DirectiveMark`] for [`directive_spans`], and is marked
4494    /// [`directive`](VRow::directive) so a frontend already drawing the
4495    /// container form's panel frames this one identically for free.
4496    ///
4497    /// Before this, a leaf directive emitted no rows at all: it was invisible,
4498    /// held no caret, and vertical motion crossed a void where it stood.
4499    fn block_directive(&mut self, id: usize, pf: &[Glyph]) {
4500        let node = &self.nodes[id];
4501        let (start, end) = (node.span.start, node.span.end);
4502        let (name, attrs) = leaf_directive_identity(node);
4503        let label = self.image_alt(id); // its `[label]` children, flattened
4504        let shown = if label.is_empty() { &name } else { &label };
4505        let style = Style::default().role(Role::Image);
4506        let mut glyphs = pf.to_vec();
4507        for ch in format!("⧉ {shown}").chars() {
4508            glyphs.push(Glyph {
4509                ch,
4510                style,
4511                src: start,
4512                stop: true,
4513            });
4514        }
4515        // End past the directive so the caret has a stop after it — the same
4516        // reason `block_media` anchors its row at the image's end.
4517        self.push_row_at(glyphs, end);
4518        if let Some(row) = self.rows.last_mut() {
4519            row.directive = true;
4520            row.leaf_directive = Some(DirectiveMark {
4521                name,
4522                attrs,
4523                label,
4524                rows: 1,
4525            });
4526        }
4527        self.last_off = end;
4528    }
4529
4530    /// An image's alt text: the flattened text of its inline descendants (an
4531    /// image's children *are* its alt content), empty when it has none. Also a
4532    /// leaf directive's `[label]`, which is the same shape — inline children
4533    /// standing for the block.
4534    fn image_alt(&self, id: usize) -> String {
4535        let mut out = String::new();
4536        self.collect_text(id, &mut out);
4537        out
4538    }
4539
4540    /// Append every descendant's `text` to `out`, in document order. Inline text
4541    /// (`str`) nodes are leaves, so a node never contributes both its own text and
4542    /// a child's — no double counting.
4543    fn collect_text(&self, id: usize, out: &mut String) {
4544        for c in self.children(id) {
4545            if let Some(t) = &self.nodes[c].text {
4546                out.push_str(t);
4547            }
4548            self.collect_text(c, out);
4549        }
4550    }
4551
4552    fn inline_children(&self, id: usize, base: Style) -> Vec<Glyph> {
4553        let mut out = Vec::new();
4554        for c in self.children(id) {
4555            self.inline(c, base, &mut out);
4556        }
4557        out
4558    }
4559
4560    /// [`inline_children`](Self::inline_children) plus any trailing whitespace the
4561    /// block carries past its inline content (see [`trailing_ws_glyphs`]). Used
4562    /// for the leaf inline blocks — paragraphs and headings — whose own `span`
4563    /// bounds exactly one line of text, so the trailing gap is theirs. *Not* for
4564    /// a table cell, whose `span` is the whole row and would swallow the
4565    /// delimiters and neighbours between it and the row's end.
4566    ///
4567    /// [`trailing_ws_glyphs`]: Self::trailing_ws_glyphs
4568    fn inline_children_with_trailing(&self, id: usize, base: Style) -> Vec<Glyph> {
4569        let mut out = self.inline_children(id, base);
4570        out.extend(self.trailing_ws_glyphs(id, base));
4571        out
4572    }
4573
4574    /// Glyphs for whatever trailing whitespace a block's source carries past its
4575    /// last inline node — the space(s) at the end of `hello ` that Markdown and
4576    /// Djot drop from the `str` node as insignificant. twig still records them:
4577    /// a block's `content_span` ends at its last meaningful character while its
4578    /// `span` runs to the end of the line's text (before the terminating
4579    /// newline), so the gap between the two *is* that trailing whitespace.
4580    ///
4581    /// Emitting it as real caret-stop glyphs is what lets the caret be drawn
4582    /// past the last visible character. Without it, typing a space at the end of
4583    /// a paragraph moved the caret in the source but not on screen — the caret
4584    /// stuck on the last glyph until the next visible character reparsed the
4585    /// space into an interior `str` node that finally carried it.
4586    ///
4587    /// Restricted to spaces: only they are safe to synthesize one-cell-per-byte,
4588    /// and only they are what the parser silently strips. Anything else in the
4589    /// gap means the span accounting isn't what this assumes, so it's left alone.
4590    fn trailing_ws_glyphs(&self, id: usize, style: Style) -> Vec<Glyph> {
4591        let node = &self.nodes[id];
4592        let Some(content) = &node.content_span else {
4593            return Vec::new();
4594        };
4595        let (from, to) = (content.end, node.span.end);
4596        let Some(slice) = (from < to).then(|| self.source.get(from..to)).flatten() else {
4597            return Vec::new();
4598        };
4599        if slice.is_empty() || slice.bytes().any(|b| b != b' ') {
4600            return Vec::new();
4601        }
4602        slice
4603            .bytes()
4604            .enumerate()
4605            .map(|(i, _)| Glyph {
4606                ch: ' ',
4607                style,
4608                src: from + i,
4609                stop: true,
4610            })
4611            .collect()
4612    }
4613
4614    fn inline(&self, id: usize, base: Style, out: &mut Vec<Glyph>) {
4615        let node = &self.nodes[id];
4616        match node.kind.as_str() {
4617            "str" | "smart_punctuation" => push_escaped_text(
4618                out,
4619                node.text.as_deref().unwrap_or(""),
4620                node.span.clone(),
4621                self.source,
4622                base,
4623            ),
4624            "soft_break" | "hard_break" | "non_breaking_space" => {
4625                // A break renders as a real, caret-navigable glyph — but twig
4626                // gives it no span of its own (`0..0`), so the offset comes from
4627                // the text in front of it: one *past* the last glyph, which is
4628                // the newline the break stands for. Past, not on: sharing the
4629                // previous glyph's offset would put two stops on one byte, and a
4630                // caret that can't change offset can't move.
4631                let src = if node.span.start != 0 {
4632                    node.span.start
4633                } else {
4634                    out.last().map(|g| g.src + g.ch.len_utf8()).unwrap_or(0)
4635                };
4636                // A *hard* break renders as this run's break glyph — a newline
4637                // inside a table cell (its own line), the same space in prose the
4638                // frontend re-wraps. A soft break normally folds into a space;
4639                // under `LineFlow::Preserve` it renders as a `'\n'` too, so the
4640                // author's line break shows where it was written. Never inside a
4641                // cell (`break_glyph` is `'\n'` there): a cell is one line and
4642                // folds its own soft breaks regardless.
4643                let ch = if node.kind == Kind::HardBreak {
4644                    self.break_glyph.get()
4645                } else if node.kind == Kind::SoftBreak
4646                    && self.preserve_soft
4647                    && self.break_glyph.get() == ' '
4648                {
4649                    '\n'
4650                } else {
4651                    ' '
4652                };
4653                out.push(Glyph {
4654                    ch,
4655                    style: base,
4656                    src,
4657                    stop: true,
4658                });
4659            }
4660            // A cell's only spelling for an in-line break is a raw `<br>`; read it
4661            // back as one (outside a cell it stays the literal text it falls to
4662            // below). The tag's bytes carry no stop of their own — the line it
4663            // ends stops just before it, the next just after.
4664            "raw_inline" if self.break_glyph.get() == '\n' && is_br(node.text.as_deref()) => {
4665                out.push(Glyph {
4666                    ch: '\n',
4667                    style: base,
4668                    src: node.span.start,
4669                    stop: true,
4670                });
4671            }
4672            "emph" => self.inline_delimited(id, base.italic(), out),
4673            "strong" => self.inline_delimited(id, base.bold(), out),
4674            // A coloured highlight's emoji is spelling, not content: twig strips
4675            // it and records the colour on the node, so the glyphs are the
4676            // author's words and the colour rides the role. Revealed markup
4677            // still shows the emoji, because `delims` reads the source bytes
4678            // between the span and the content span — which is exactly the
4679            // `==🔴 ` the author typed.
4680            "mark" => {
4681                let color = MarkColor::from_attrs(&node.attrs);
4682                self.inline_delimited(id, base.role(Role::Mark(color)), out)
4683            }
4684            "insert" => self.inline_delimited(id, base.underline(), out),
4685            "delete" => self.inline_delimited(id, base.strikethrough(), out),
4686            // The one pair whose whole meaning is *where the glyphs sit*. Drawn
4687            // in the surrounding style otherwise, so `^**2**^` stays bold and a
4688            // superscript inside a heading keeps the heading's role — which is
4689            // exactly why this is a `Baseline` and not a `Role`.
4690            "superscript" => self.inline_delimited(id, base.baseline(Baseline::Super), out),
4691            "subscript" => self.inline_delimited(id, base.baseline(Baseline::Sub), out),
4692            "verbatim" => self.inline_verbatim(id, base, out, self.revealed(&node.span)),
4693            // A formula in a line. Three renderings, in order of preference:
4694            //
4695            // - On the caret's line it is its TeX in the code style with its
4696            //   delimiters shown — in *every* markup mode, because the
4697            //   content is not the picture and hiding the `$` alone would
4698            //   leave nothing to edit. `math_revealed` is `revealed` without
4699            //   the mode gate.
4700            // - On a surface that paints pictures in a line it is one atom
4701            //   glyph, `stop: true` at the formula's start, standing for the
4702            //   whole thing; the [`MathMark`] drained onto the row by
4703            //   [`take_math`](Self::take_math) says what the frontend draws
4704            //   there. The caret has the stop on the atom and the next glyph's
4705            //   past it, and nothing inside the markup.
4706            // - Elsewhere — a terminal — it is the code-styled TeX with the
4707            //   delimiters hidden, exactly the verbatim treatment, and what
4708            //   `inline_math` rendered as before there was anything else.
4709            //   `display_math` had no arm at all and fell to the default one,
4710            //   which pushed its text at the *node's* start, three bytes short
4711            //   of where the text sits.
4712            "inline_math" | "display_math" => {
4713                self.saw_math.set(true);
4714                if self.math_revealed(&node.span) {
4715                    self.inline_verbatim(id, base, out, true);
4716                } else if self.surface.inline_pictures {
4717                    let tex = node.text.clone().unwrap_or_default();
4718                    self.pending_math.borrow_mut().push((
4719                        node.span.start,
4720                        MathMark {
4721                            tex,
4722                            display: node.kind == Kind::DisplayMath,
4723                            glyph: None,
4724                            rows: 1,
4725                        },
4726                    ));
4727                    out.push(Glyph {
4728                        ch: MATH_ATOM,
4729                        style: base.role(Role::Math),
4730                        src: node.span.start,
4731                        stop: true,
4732                    });
4733                } else {
4734                    self.inline_verbatim(id, base, out, false);
4735                }
4736            }
4737            // An attributed span — the run-level half of the presentation
4738            // vocabulary. djot's `[text]{…}`, AsciiDoc's `[.a]#text#`, HTML's
4739            // and Markdown's `<span …>`: one node with a name twig hands back
4740            // for two of the four (see [`is_run_span`]), all four carrying the
4741            // author's `data-size`, `data-font` and `data-color` on the run
4742            // they cover.
4743            //
4744            // The keys are written over the surrounding style rather than
4745            // replacing it, so a span inside a block that names its own size
4746            // wins on size and keeps the block's face — the nearest-wins rule
4747            // the block walker applies through a `div`. A key the span does not
4748            // name is one the block still says.
4749            //
4750            // A `data-color` here is the text's *foreground*, where the same key
4751            // on a `mark` is a highlight's background: same vocabulary, same
4752            // enum, and no collision, because a `mark` is a `mark` and a span is
4753            // a span.
4754            //
4755            // Otherwise this is the plain `recurse` an anonymous container has
4756            // always had — no delimiters, because the `{…}` is markup and the
4757            // span's text is the author's words.
4758            "container" if is_run_span(node) && !self.children(id).is_empty() => {
4759                self.recurse(id, run_style(node, base, &self.faces), out)
4760            }
4761            // A text directive (`:name[label]{…}`) — the inline form of a generic
4762            // directive. Its `[label]` children are the visible text; the name and
4763            // the `{…}` attributes are the host app's vocabulary (diaryx's
4764            // `:vis[…]`) and stay hidden markup, exactly as a link's `](dest)` is.
4765            // Drawn in the surrounding style: a role of its own would need one
4766            // every frontend maps, and the bug this fixes is that the text was
4767            // invisible, not that it was unstyled.
4768            "container" if container_is_directive(node) && !self.children(id).is_empty() => {
4769                self.recurse(id, base, out)
4770            }
4771            // No `[label]`, so there are no children to render and recursing
4772            // emitted *nothing*: the directive's bytes vanished from the document
4773            // and left no caret stop behind. What to draw instead turns on
4774            // whether the syntax looks deliberate.
4775            //
4776            // Bare `:word` almost never is. twig matches a colon followed by any
4777            // letter-led word (`scanTextDirective`, deliberately matching remark),
4778            // so ordinary prose is full of them — `:see below`, a `:smile:`
4779            // shortcode, a stray colon before a word. Those are prose, and prose
4780            // renders as itself: every byte visible, every byte a caret stop, so a
4781            // colon typed by accident can be seen and deleted. Hiding them behind
4782            // a placeholder would be the invisible-and-unreachable failure this
4783            // arm exists to fix, just wearing a nicer glyph.
4784            "container" if container_is_directive(node) && node.attrs.is_empty() => {
4785                let span = node.span.clone();
4786                push_text(
4787                    out,
4788                    self.source.get(span.clone()).unwrap_or(""),
4789                    span.start,
4790                    base,
4791                );
4792            }
4793            // `{…}` attributes, though, are unmistakably deliberate — nobody
4794            // types `:vis{.family}` by accident, and diaryx writes exactly that
4795            // inline. So an attribute-bearing directive with no label draws as a
4796            // chip on `block_directive`'s recipe (`⧉ name attrs`, `Role::Image`),
4797            // the inline peer of the leaf form's placeholder row.
4798            //
4799            // Only the first glyph is a caret stop, and the whole chip shares the
4800            // directive's start offset: the caret treats it as one atomic thing
4801            // rather than walking hidden markup a byte at a time, and a paragraph
4802            // holding nothing but a chip still has a stop to be navigated to.
4803            "container" if container_is_directive(node) => {
4804                let start = node.span.start;
4805                let name = node.name.clone().unwrap_or_default();
4806                let shown = match directive_attr_label(&node.attrs) {
4807                    Some(attrs) if !name.is_empty() => format!("⧉ {name} {attrs}"),
4808                    Some(attrs) => format!("⧉ {attrs}"),
4809                    None => format!("⧉ {name}"),
4810                };
4811                let style = base.role(Role::Image);
4812                for (i, ch) in shown.chars().enumerate() {
4813                    out.push(Glyph {
4814                        ch,
4815                        style,
4816                        src: start,
4817                        stop: i == 0,
4818                    });
4819                }
4820            }
4821            // A footnote reference (`[^1]`). The label bracketed is what a reader
4822            // needs — bare, `note1` reads as a typo rather than a reference — so
4823            // the `^` is hidden as the spelling artefact it is (a link's
4824            // `](dest)` goes the same way) and the brackets are kept as
4825            // decoration: one shared offset, never a caret stop, like a table's
4826            // borders, so the caret walks the label alone.
4827            //
4828            // Styled `Role::Link`: a reference *is* a link to its definition, and
4829            // every frontend already paints that role. A role of its own would
4830            // need one in each of them, and what a frontend needs to tell the two
4831            // apart is not a paint colour but an answer to "what does clicking
4832            // here do" — which is [`Doc::footnote_at_caret`]'s job, not a glyph's.
4833            //
4834            // Raised, though, because that a reference is *set* differently from
4835            // the prose it interrupts is exactly what makes it read as a
4836            // reference. `[1]` at body size reads as bracketed text.
4837            "footnote_reference" => {
4838                let style = base.role(Role::Link);
4839                // Revealed, the reference is just its source bytes: the `^` that
4840                // is normally elided comes back and every byte becomes a real
4841                // stop, so the brackets stop being decoration and start being
4842                // text. That's the whole point of the mode, and it replaces the
4843                // hand-built chip below rather than decorating it — including the
4844                // raised baseline, since what's on screen there is source, and
4845                // source is set as prose.
4846                if self.revealed(&node.span) {
4847                    self.push_delim(out, &node.span, style);
4848                    return;
4849                }
4850                let style = style.baseline(Baseline::Super);
4851                // The label's own span, so its glyphs map to their true bytes.
4852                // Absent one, it starts past the `[^` that opens the reference.
4853                let (label, at) = match &node.content_span {
4854                    Some(c) => (self.source.get(c.clone()).unwrap_or(""), c.start),
4855                    None => (node.text.as_deref().unwrap_or(""), node.span.start + 2),
4856                };
4857                out.push(Glyph {
4858                    ch: '[',
4859                    style,
4860                    src: node.span.start,
4861                    stop: false,
4862                });
4863                push_text(out, label, at, style);
4864                out.push(Glyph {
4865                    ch: ']',
4866                    style,
4867                    src: node.span.end.saturating_sub(1),
4868                    stop: false,
4869                });
4870            }
4871            "link" | "url" | "email" => {
4872                let style = base.role(Role::Link);
4873                if self.children(id).is_empty() {
4874                    // A bare autolink (`<a@b.c>`, a naked URL): the destination
4875                    // *is* the visible text, so there is nothing elided to
4876                    // reveal and both modes draw the same thing.
4877                    push_text(
4878                        out,
4879                        node.destination
4880                            .as_deref()
4881                            .or(node.text.as_deref())
4882                            .unwrap_or("link"),
4883                        node.span.start,
4884                        style,
4885                    );
4886                } else {
4887                    // An inline link reveals asymmetrically — `[` before the
4888                    // label, `](dest)` after it — which the generic
4889                    // span-minus-content derivation already produces.
4890                    self.inline_delimited(id, style, out);
4891                }
4892            }
4893            _ => {
4894                if self.children(id).is_empty() {
4895                    if let Some(t) = &node.text {
4896                        push_text(out, t, node.span.start, base);
4897                    }
4898                } else {
4899                    self.recurse(id, base, out);
4900                }
4901            }
4902        }
4903    }
4904
4905    fn recurse(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
4906        for c in self.children(id) {
4907            self.inline(c, style, out);
4908        }
4909    }
4910
4911    /// Lay a block's inline `glyphs` into visual rows, prefixing the first with
4912    /// `pf` and the rest with `pc`. A preserved soft break arrives as a `'\n'`
4913    /// glyph (see the `soft_break` arm): a hard row boundary that splits the
4914    /// glyphs so each run lays out on its own and the author's line structure
4915    /// shows on screen. The `'\n'` is dropped from the row it closes and its
4916    /// source offset becomes that row's end stop — exactly how a table cell's
4917    /// in-line `<br>` is handled — so the caret can rest at the line's end
4918    /// without a zero-width control char leaking into what the frontends render.
4919    /// With no `'\n'` present (the folding default, and every build that isn't
4920    /// `LineFlow::Preserve`) there is one run and this is byte-identical to
4921    /// laying the glyphs out directly.
4922    fn emit_wrapped(&mut self, glyphs: Vec<Glyph>, block_start: usize, pf: &[Glyph], pc: &[Glyph]) {
4923        if !glyphs.iter().any(|g| g.ch == '\n') {
4924            self.emit_line(glyphs, block_start, pf, pc, None);
4925            return;
4926        }
4927        // Each run up to a '\n' is a line of its own: the first wears the block's
4928        // opening prefix, every later one the continuation prefix, and the break's
4929        // own offset ends the run's last row. The break glyph is dropped. A
4930        // trailing '\n' flushes its run and leaves nothing behind, so no spurious
4931        // blank row follows it.
4932        let mut run: Vec<Glyph> = Vec::new();
4933        let mut first = true;
4934        for g in glyphs {
4935            if g.ch == '\n' {
4936                let lead = if first { pf } else { pc };
4937                self.emit_line(std::mem::take(&mut run), block_start, lead, pc, Some(g.src));
4938                first = false;
4939            } else {
4940                run.push(g);
4941            }
4942        }
4943        if !run.is_empty() {
4944            let lead = if first { pf } else { pc };
4945            self.emit_line(run, block_start, lead, pc, None);
4946        }
4947    }
4948
4949    /// Word-wrap a single line of `glyphs` (no interior line breaks) to the
4950    /// available width and push the visual rows, prefixing the first with `pf`
4951    /// and the rest with `pc`. `end`, when set, is the source offset that ends
4952    /// the line's final row — the offset of the break that terminated it, which
4953    /// the caller has already stripped from `glyphs`; when `None` the row ends
4954    /// just past its last glyph, as an unbroken block's does.
4955    fn emit_line(
4956        &mut self,
4957        glyphs: Vec<Glyph>,
4958        block_start: usize,
4959        pf: &[Glyph],
4960        pc: &[Glyph],
4961        end: Option<usize>,
4962    ) {
4963        // The line's final row ends at `end` when a break gave one, else just
4964        // past its last glyph (`push_row`'s default).
4965        let push_last = |b: &mut Self, row: Vec<Glyph>| match end {
4966            Some(e) => b.push_row_at(row, e),
4967            None => b.push_row(row, block_start),
4968        };
4969
4970        // No column budget: emit the whole line as one row and let the frontend
4971        // wrap it at its own (pixel) width.
4972        let Some(width) = self.wrap else {
4973            let row = if glyphs.is_empty() {
4974                pf.to_vec()
4975            } else {
4976                concat(pf, &glyphs)
4977            };
4978            push_last(self, row);
4979            return;
4980        };
4981
4982        // Split into words (maximal non-space runs), each carrying the space
4983        // glyph that followed it (so its source offset is preserved).
4984        let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
4985        let mut word: Vec<Glyph> = Vec::new();
4986        for g in glyphs {
4987            if g.ch == ' ' {
4988                words.push((std::mem::take(&mut word), Some(g)));
4989            } else {
4990                word.push(g);
4991            }
4992        }
4993        if !word.is_empty() {
4994            words.push((word, None));
4995        }
4996        if words.is_empty() {
4997            // An empty block (or an empty preserved line) still occupies one
4998            // (prefixed) row.
4999            push_last(self, pf.to_vec());
5000            return;
5001        }
5002
5003        let mut line: Vec<Glyph> = Vec::new();
5004        let mut used = 0usize;
5005        let mut first = true;
5006        for (w, space) in words {
5007            let avail = width
5008                .saturating_sub(prefix_width(if first { pf } else { pc }))
5009                .max(1);
5010            let cells = glyphs_width(&w);
5011            if used > 0 && used + cells > avail {
5012                let row = concat(if first { pf } else { pc }, &line);
5013                self.push_row(row, block_start);
5014                line = Vec::new();
5015                used = 0;
5016                first = false;
5017            }
5018            used += cells;
5019            line.extend(w);
5020            if let Some(sp) = space {
5021                used += 1;
5022                line.push(sp);
5023            }
5024        }
5025        let row = concat(if first { pf } else { pc }, &line);
5026        push_last(self, row);
5027    }
5028
5029    /// The source offset of each line of a code block's `text`.
5030    ///
5031    /// `content` is the block's `content_span` — where twig says the body lives
5032    /// in the source, fences already excluded. Its lines run 1:1 with the
5033    /// rendered `text` lines, so no search is needed; each is anchored at the
5034    /// *end* of its source line, which places it past whatever indent `text` had
5035    /// stripped (a fenced block's fences, an indented one's leading spaces)
5036    /// without having to know how much there was.
5037    ///
5038    /// `None` when the body and the rendered lines don't line up — a coarse
5039    /// fallback the caller turns into the block's start offset.
5040    fn code_line_offsets(&self, content: &Range<usize>, lines: &[&str]) -> Option<Vec<usize>> {
5041        let mut src_lines: Vec<(usize, &str)> = Vec::new();
5042        let mut at = content.start;
5043        for l in self.source.get(content.start..content.end)?.split('\n') {
5044            src_lines.push((at, l));
5045            at += l.len() + 1;
5046        }
5047        if src_lines.len() != lines.len() {
5048            return None;
5049        }
5050        Some(
5051            lines
5052                .iter()
5053                .zip(&src_lines)
5054                .map(|(l, (start, sl))| start + sl.len().saturating_sub(l.len()))
5055                .collect(),
5056        )
5057    }
5058
5059    fn push_row(&mut self, glyphs: Vec<Glyph>, fallback: usize) {
5060        // Step past the character the *source* holds at the last glyph's offset,
5061        // not past the glyph's own `ch`. The two agree for ordinary text, but a
5062        // glyph is not always the character it stands on: `synth` decoration and
5063        // a substituted run (an image's `⧉ label`) share one offset by design.
5064        // Trusting `ch` there yields an offset inside a multi-byte character,
5065        // which every later slice of `source` panics on.
5066        let end_src = glyphs
5067            .last()
5068            .map(|g| {
5069                let at = g.src.min(self.source.len());
5070                at + self.source[at..].chars().next().map_or(0, char::len_utf8)
5071            })
5072            .unwrap_or(fallback);
5073        self.push_row_at(glyphs, end_src);
5074    }
5075
5076    /// Push a row with an explicit end stop, for content that knows its own
5077    /// extent better than its last glyph does.
5078    fn push_row_at(&mut self, glyphs: Vec<Glyph>, end_src: usize) {
5079        self.last_off = end_src;
5080        let mark_ends = self.take_mark_ends(end_src);
5081        let math = self.take_math(&glyphs);
5082        self.rows.push(VRow {
5083            glyphs,
5084            end_src,
5085            decoration: false,
5086            code: false,
5087            code_lang: None,
5088            directive: false,
5089            directive_label: None,
5090            media: None,
5091            task: None,
5092            leaf_directive: None,
5093            heading: None,
5094            align: None,
5095            line_height: None,
5096            boundary: None,
5097            mark_ends,
5098            math,
5099        });
5100    }
5101
5102    /// The quote's own trailing marker lines: the `>` / `> ` lines that lie past
5103    /// its last child but inside its span, one gutter row each.
5104    ///
5105    /// Pressing Enter at the end of `> a` writes `> a\n>\n> \n` — twig's
5106    /// spelling, and the right one. Those last two lines hold no block (a
5107    /// `block_quote`'s `content_span` still stops at its last child) so the
5108    /// children walk never reaches them, and they used to fall all the way to
5109    /// the document-level [`Builder::emit_trailing_blank_lines`], which knows no
5110    /// prefix: the gutter simply stopped, and a writer adding a line to a quote
5111    /// watched it draw as plain prose.
5112    ///
5113    /// This is only answerable since twig 3.2.0, where a Markdown `block_quote`'s
5114    /// span covers its own trailing marker lines (it reported `0..3` for that
5115    /// source and now reports `0..8`). Before that the lines belonged to no node
5116    /// at any level, and the only way to draw them was to sniff `>` off the raw
5117    /// source and re-derive the nesting depth by counting markers — format
5118    /// inference this crate exists to keep out of the render path.
5119    ///
5120    /// Each row is a real caret home rather than a decoration gap: the writer
5121    /// spelled every one of these lines with a marker of its own, so each is a
5122    /// line of the quote to stand on, not the spacing between two blocks (which
5123    /// is [`Builder::emit_separators_before`]'s, and falls *between* children
5124    /// where this never looks).
5125    fn emit_quote_trailing_lines(&mut self, pc: &[Glyph], end: usize) {
5126        let end = end.min(self.source.len());
5127        let mut at = self.rows.last().map_or(0, |r| r.end_src);
5128        // Walk line by line from the last child's end to the quote's, taking each
5129        // line's *end* as the row's offset — the caret home at the end of a line
5130        // is where one on an empty quoted line belongs, and it keeps every row's
5131        // offset distinct from its neighbours'.
5132        while at < end {
5133            let Some(k) = self.source[at..end].find('\n') else {
5134                break;
5135            };
5136            let line_start = at + k + 1;
5137            let line_end = self.source[line_start..end]
5138                .find('\n')
5139                .map_or(end, |i| line_start + i);
5140            self.push_row_at(pc.to_vec(), line_end);
5141            at = line_end;
5142        }
5143    }
5144
5145    /// The source offset the caret rests at on the blank line separating a block
5146    /// that ends at `prev_end` from the next block starting at `next_start`:
5147    /// just past the newline that terminates the previous block, but kept
5148    /// strictly before the next block so the offset is unique to this row.
5149    fn blank_line_offset(&self, prev_end: usize, next_start: usize) -> usize {
5150        let after_nl = self.source[prev_end..]
5151            .find('\n')
5152            .map_or(prev_end, |p| prev_end + p + 1);
5153        after_nl.min(next_start.saturating_sub(1)).max(prev_end)
5154    }
5155
5156    /// The source offset of each blank row between a block ending at `prev_end`
5157    /// and content starting at `next_start` — one per blank source line. The
5158    /// first newline terminates the previous block's line; every line it opens up
5159    /// to (but not including) the line that holds `next_start` is a blank row the
5160    /// caret can occupy. Offsets are unique and ascending so `pos_of_offset`
5161    /// resolves each to its own row. Empty when the two blocks are tight (no
5162    /// blank line between them).
5163    fn blank_rows_between(&self, prev_end: usize, next_start: usize) -> Vec<usize> {
5164        // Spans aren't always in tidy source order (e.g. a block after
5165        // frontmatter can start *before* the previous block's rendered content
5166        // ends). There's no blank line to place then — fall back to the clamped
5167        // single separator (an empty return) rather than slicing an inverted
5168        // range.
5169        if next_start <= prev_end {
5170            return Vec::new();
5171        }
5172        let gap = &self.source[prev_end..next_start];
5173        let Some(nl) = gap.find('\n') else {
5174            return Vec::new();
5175        };
5176        // The line holding `next_start` belongs to the next block; blank rows
5177        // stop before it.
5178        let next_line_start = self.source[..next_start].rfind('\n').map_or(0, |p| p + 1);
5179        let mut offs = Vec::new();
5180        let mut start = prev_end + nl + 1;
5181        while start < next_line_start {
5182            offs.push(start);
5183            match self.source[start..next_start].find('\n') {
5184                Some(k) => start += k + 1,
5185                None => break,
5186            }
5187        }
5188        offs
5189    }
5190
5191    /// Blank lines the user typed past the end of the last block (e.g. two
5192    /// `Enter`s to open a fresh paragraph) leave no AST node, so nothing renders
5193    /// and the caret appears stuck on the old line. Reconstruct one empty row
5194    /// per extra trailing newline from the source, each at its own offset, so
5195    /// the caret rides down onto the new line the moment it's created.
5196    ///
5197    /// `above` is the class of the last block in the document — the one this gap
5198    /// closes. A document with no blocks at all has nothing above these rows, and
5199    /// [`BlockClass::Paragraph`] is the honest answer there too: what they are is
5200    /// empty paragraphs, on both sides of the gap.
5201    fn emit_trailing_blank_lines(&mut self, above: BlockClass, hidden_end: usize) {
5202        // With no rows at all the count starts past any hidden frontmatter, not
5203        // at 0: its newlines are not trailing blank lines, and counting them
5204        // opened phantom rows *inside* the metadata for a frontmatter-only file.
5205        //
5206        // Or past the last hidden block, if that is later: a closing comment
5207        // draws no row, and its lines are not blank lines the author opened.
5208        //
5209        // Or past the last byte of content, if *that* is later: a fenced code
5210        // block's last row ends at its last line of code, and the closing
5211        // fence under it is markup with no row of its own — so counted from
5212        // the row, the fence's own line and terminator read as two blank lines
5213        // and opened a phantom empty paragraph whose offset was *inside* the
5214        // fence. Typing on it broke the fence. (A setext heading's underline
5215        // was the same shape.) Trailing whitespace is not content, so a line
5216        // of spaces still counts as the blank line it looks like.
5217        let last_end = self
5218            .rows
5219            .last()
5220            .map_or(hidden_end, |r| r.end_src)
5221            .max(self.stepped_over)
5222            .max(self.source.trim_end().len());
5223        if last_end >= self.source.len() {
5224            return;
5225        }
5226        // The first newline after the last content just terminates that line, so
5227        // a lone trailing `\n` (an ordinary file ending) opens no blank row. A
5228        // *second* newline opens an empty paragraph: render it the way a block
5229        // boundary is rendered — a blank spacer row, then the empty paragraph row
5230        // the caret rests on — so the just-pressed-Enter view already shows the
5231        // gap it will keep once text is typed, and typing doesn't shift the line
5232        // down. One row per trailing newline (each its own caret offset), the
5233        // last landing at the document end where the caret sits.
5234        let extra = self.source[last_end..].matches('\n').count();
5235        if extra < 2 {
5236            return;
5237        }
5238        for k in 1..=extra {
5239            self.rows.push(VRow {
5240                glyphs: Vec::new(),
5241                end_src: last_end + k,
5242                // As between two blocks: the first blank row is the gap that
5243                // closes the block above, not somewhere to type. Nothing follows
5244                // to need a gap of its own, though, so every row after it is a
5245                // real empty paragraph — the end of the document bounds the last
5246                // one the way a following block would. Preserve flow makes even
5247                // that first row navigable, as it does every blank line.
5248                decoration: !self.preserve_soft && k == 1,
5249                code: false,
5250                code_lang: None,
5251                directive: false,
5252                directive_label: None,
5253                media: None,
5254                task: None,
5255                leaf_directive: None,
5256                heading: None,
5257                align: None,
5258                line_height: None,
5259                // The one drawn row here is a block boundary like any other —
5260                // "rendered the way a block boundary is rendered" is the whole
5261                // point of it — so it says so, and a frontend spacing boundaries
5262                // spaces this one the same. The rows below it are navigable empty
5263                // paragraphs, not gaps.
5264                boundary: (!self.preserve_soft && k == 1).then_some(Boundary {
5265                    above,
5266                    below: BlockClass::Paragraph,
5267                }),
5268                mark_ends: Vec::new(),
5269                math: Vec::new(),
5270            });
5271        }
5272    }
5273}
5274
5275// ── display width ────────────────────────────────────────────────────────────
5276//
5277// Two things a row can be counted in, and they are not the same number:
5278//
5279//   *glyphs*, one per codepoint — how the text is stored here, and what an
5280//   index into `VRow::glyphs` means; and
5281//   *columns*, one per terminal cell — where the text is drawn, and what every
5282//   `col` in this crate means.
5283//
5284// `你` is one glyph in two columns. Counting columns with `glyphs.len()` (or,
5285// in the source view, `chars().count()`) is the same number only for the ASCII
5286// that most fixtures are written in, and drifts one cell per wide character
5287// everywhere else — the caret drawn a column short of the text it types into.
5288// Everything below converts between the two; nothing else should have to.
5289
5290/// The display width of `s` in terminal cells.
5291///
5292/// Measured per grapheme cluster, because that is the unit a surface advances
5293/// by: `👨‍👩‍👧` is five codepoints measuring 2 + 0 + 2 + 0 + 2 cells one at a
5294/// time, but the character they spell is drawn in 2. Both frontends already
5295/// measure it that way — ratatui asks `unicode-width` per cluster, and the GUI
5296/// asks its own text system — so the caret only lands where the text is if this
5297/// agrees with them.
5298pub fn text_width(s: &str) -> usize {
5299    UnicodeWidthStr::width(s)
5300}
5301
5302/// One grapheme cluster of a laid-out row: the glyphs that spell it, and the
5303/// cells it is drawn in.
5304///
5305/// The cluster, not the glyph, is what has a width. A row's glyphs are one per
5306/// codepoint, so an accented letter or an emoji is several of them drawn in one
5307/// character's worth of cells — the glyph that opens the cluster claims those
5308/// cells, and the ones continuing it are drawn *inside* them rather than beside
5309/// them. It's the same cluster the stop table is built on: the opening glyph is
5310/// the one a caret can rest on, and so the only one whose column it can be
5311/// drawn at.
5312struct Cluster {
5313    /// Index of the glyph that opens it.
5314    glyph: usize,
5315    /// The display column it starts at.
5316    col: usize,
5317    /// How many cells it is drawn in. Zero for a cluster with no width of its
5318    /// own (a lone joiner), which therefore sits at no column at all.
5319    cells: usize,
5320}
5321
5322/// Walk a row's glyphs as the clusters they spell, in column order.
5323fn clusters(glyphs: &[Glyph]) -> Vec<Cluster> {
5324    let text: String = glyphs.iter().map(|g| g.ch).collect();
5325    let mut out = Vec::new();
5326    let (mut glyph, mut col) = (0, 0);
5327    for cluster in text.graphemes(true) {
5328        let cells = text_width(cluster);
5329        out.push(Cluster { glyph, col, cells });
5330        // One glyph per codepoint, so a cluster spans exactly its own.
5331        glyph += cluster.chars().count();
5332        col += cells;
5333    }
5334    out
5335}
5336
5337/// The display width of a run of glyphs.
5338fn glyphs_width(glyphs: &[Glyph]) -> usize {
5339    clusters(glyphs).last().map_or(0, |c| c.col + c.cells)
5340}
5341
5342/// A cell's display width — the widest of its lines, since an in-cell `\n` break
5343/// splits it into several. Sizes the column that must hold every line.
5344fn cell_width(glyphs: &[Glyph]) -> usize {
5345    glyphs
5346        .split(|g| g.ch == '\n')
5347        .map(glyphs_width)
5348        .max()
5349        .unwrap_or(0)
5350}
5351
5352/// Whether a raw inline HTML tag is a line break (`<br>`, `<br/>`, `<br />`,
5353/// case-insensitively) — the one tag a table cell reads as an in-cell break.
5354fn is_br(text: Option<&str>) -> bool {
5355    let Some(t) = text else { return false };
5356    matches!(
5357        t.trim().to_ascii_lowercase().replace(' ', "").as_str(),
5358        "<br>" | "<br/>"
5359    )
5360}
5361
5362impl VRow {
5363    /// The row's width in display columns — and so the column of the caret
5364    /// placed past its last glyph, which is the rightmost column it can occupy.
5365    fn width(&self) -> usize {
5366        glyphs_width(&self.glyphs)
5367    }
5368
5369    /// The display column glyph `i` is drawn at. Glyphs continuing a cluster
5370    /// report the column of the glyph that opened it, since that is where they
5371    /// are drawn; none of them is ever a stop, so no caret is placed by it.
5372    fn col_of_glyph(&self, i: usize) -> usize {
5373        clusters(&self.glyphs)
5374            .iter()
5375            .rev()
5376            .find(|c| c.glyph <= i)
5377            .map_or(0, |c| c.col)
5378    }
5379
5380    /// The glyph drawn at display column `col`, or `None` past the row's last
5381    /// cell.
5382    ///
5383    /// A column landing on the *second* cell of a wide glyph resolves to that
5384    /// glyph: half a character is not a place to be, so clicking either cell of
5385    /// `你` means `你`, and the caret comes to rest at its start — the column it
5386    /// would be drawn at anyway. That rule is what makes the mapping invertible:
5387    /// every offset has one column, and every column has one offset.
5388    fn glyph_at_col(&self, col: usize) -> Option<usize> {
5389        clusters(&self.glyphs)
5390            .into_iter()
5391            .find(|c| col < c.col + c.cells)
5392            .map(|c| c.glyph)
5393    }
5394}
5395
5396// ── helpers ──────────────────────────────────────────────────────────────────
5397
5398/// The caret home inside an *empty* table cell (`col`, 0-based) whose node
5399/// `span` is `src` starting at byte `start`. twig gives an empty cell no
5400/// `content_span`, so its interior is read from the pipes: the home is one
5401/// space past the pipe that opens the cell — mimicking the `| ` padding a
5402/// filled cell has — and never at or past the pipe that closes it. So
5403/// `|  |  |` gives the two cells distinct, editable homes instead of both
5404/// collapsing onto the row's start.
5405///
5406/// Two shapes of span are read. A twig from 3.3.3 gave every cell of a row
5407/// the *row's* span, so the cell's own pipes are the `col`-th and
5408/// `col+1`-th unescaped `|` in it; a later twig spans a cell from the pipe
5409/// that opens it to the one that closes it, exclusive, so the span holds at
5410/// most that one pipe, at its start, and the closing one is the byte past
5411/// its end. The two are told apart by the pipes the span holds — a row's
5412/// span has several, or one that is not at its start.
5413fn empty_cell_offset(src: &str, start: usize, col: usize) -> usize {
5414    let bytes = src.as_bytes();
5415    let mut pipes = Vec::new();
5416    for (i, &b) in bytes.iter().enumerate() {
5417        if b == b'|' && (i == 0 || bytes[i - 1] != b'\\') {
5418            pipes.push(i);
5419        }
5420    }
5421    let whole_row = pipes.len() > 1 || pipes.first().is_some_and(|&i| i != 0);
5422    let (open, close) = if whole_row {
5423        (pipes.get(col).copied(), pipes.get(col + 1).copied())
5424    } else {
5425        (pipes.first().copied(), Some(src.len()))
5426    };
5427    match (open, close) {
5428        (Some(open), Some(close)) => {
5429            let lo = open + 1; // just inside the opening pipe
5430            let hi = close.saturating_sub(1); // just inside the closing pipe
5431            let inside = if hi < lo {
5432                lo
5433            } else {
5434                (open + 2).clamp(lo, hi)
5435            };
5436            start + inside
5437        }
5438        (Some(open), None) => start + open + 1,
5439        _ => start,
5440    }
5441}
5442
5443/// One laid-out table cell: its rendered text, the source range that text
5444/// occupies (`start`/`end` are the caret anchors decoration points at), and the
5445/// column alignment its padding honours.
5446///
5447/// `glyphs` is the cell's inline content *unwrapped* — the box-drawn rows wrap
5448/// it to a column width, but a frontend laying the grid out itself needs the
5449/// text before that decision was made.
5450#[derive(Clone)]
5451pub struct TableCell {
5452    pub glyphs: Vec<Glyph>,
5453    pub start: usize,
5454    pub end: usize,
5455    pub align: Alignment,
5456}
5457
5458/// One row of a table's grid, as the document spells it — not as it's drawn.
5459#[derive(Clone)]
5460pub struct TableRow {
5461    /// A header row: drawn bold, and ruled off from the body below it.
5462    pub head: bool,
5463    pub cells: Vec<TableCell>,
5464}
5465
5466/// A table's structure, published alongside the box-drawn rows that spell it.
5467///
5468/// The rows in [`VisualMap::rows`] are the *default monospace* picture of a
5469/// table: every border a `│`, every column a whole number of character cells.
5470/// That picture is exactly right on any monospace surface, and unfixable off one
5471/// — in a proportional font the `│`s of two rows land at different x and the grid
5472/// shears. So a frontend that draws its own geometry reads this instead: the
5473/// cells, their alignment, and which rows are the head, with no opinion about
5474/// how wide a column is or what a border looks like.
5475///
5476/// Both are always built. The TUI paints `rows` and ignores this; the GUI skips
5477/// `rows` for the span in `rows_span` and draws from here. They describe the
5478/// same cells, so the caret lands on the same offsets either way.
5479#[derive(Clone)]
5480pub struct TableInfo {
5481    /// The `VisualMap::rows` this table's picture occupies, borders included —
5482    /// what a frontend drawing its own table skips over.
5483    pub rows_span: Range<usize>,
5484    /// The end of the table node's source span, and the offset its trailing
5485    /// caret stop sits at — the one caret home past the last cell, held by the
5486    /// bottom border row's end. Typing there opens a paragraph under the table
5487    /// rather than joining the block; see `Doc::open_paragraph_at_block_edge`.
5488    pub end_src: usize,
5489    /// The block prefix every row of this table carries — a blockquote's `│ `
5490    /// gutter, a list item's indent. Empty for a table at the top level.
5491    ///
5492    /// A frontend drawing its own grid has to render this and start the table
5493    /// past it, exactly as the picture does; a table nested in a quote that
5494    /// draws flush at the left margin has left the quote.
5495    pub prefix: Vec<Glyph>,
5496    pub grid: Vec<TableRow>,
5497}
5498
5499/// A fenced or indented code block, named by the [`VisualMap::rows`] it occupies.
5500///
5501/// Unlike a table, the rows *are* the block's content — a frontend still paints
5502/// them, it just draws a border and a tinted background around the whole span
5503/// and lets the code inside scroll horizontally instead of wrapping. So this
5504/// carries only the row range; there's no structural alternative to the picture
5505/// the way [`TableInfo`] is one. Derived from [`VRow::code`] — see
5506/// [`code_block_spans`].
5507#[derive(Clone, Debug, PartialEq, Eq)]
5508pub struct CodeBlockInfo {
5509    /// The contiguous run of [`VisualMap::rows`] this code block spans, blank
5510    /// code lines included.
5511    pub rows_span: Range<usize>,
5512    /// The block's language, from a fenced block's info string — what a frontend
5513    /// paints as a small label on the box (`` ```rust `` → `Some("rust")`).
5514    /// `None` for a fence written without one, or an indented block. Editing it
5515    /// goes through [`crate::Doc::set_code_language`], which re-finds the fence
5516    /// in the AST, so this stays a display string.
5517    pub lang: Option<String>,
5518}
5519
5520/// A block-level image (`![alt](url)` on its own line), named by the single
5521/// [`VisualMap::rows`] row it occupies.
5522///
5523/// Like [`CodeBlockInfo`], the row *is* the block's default rendering — a plain
5524/// surface paints the `🖼 alt` placeholder glyphs as-is. An image-capable
5525/// frontend instead **skips the row in `rows_span`** and paints the resolved
5526/// picture there, exactly as it skips a [`TableInfo`]'s box-drawn rows. Derived
5527/// from [`VRow::media`] by [`media_spans`], so it survives the row reuse of
5528/// [`BlockCache`] and [`build_spliced`].
5529#[derive(Clone, Debug, PartialEq, Eq)]
5530pub struct MediaInfo {
5531    /// The [`VisualMap::rows`] rows this media's placeholder occupies — what a
5532    /// capable frontend replaces with the picture or player.
5533    pub rows_span: Range<usize>,
5534    /// Whether this is a picture, a movie, or a sound — which widget the
5535    /// frontend builds over [`rows_span`](MediaInfo::rows_span). A frontend that
5536    /// handles only some kinds leaves the rest as core's placeholder rows, which
5537    /// already read sensibly on their own.
5538    pub kind: MediaKind,
5539    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
5540    /// the AST. A frontend resolves a relative path against the document's own
5541    /// directory; core does no I/O. For a `<picture>` this is the `<img>`
5542    /// fallback — the source used when no [`sources`](MediaInfo::sources) media
5543    /// query matches (or the frontend has no theme). Empty when a `<video>`/
5544    /// `<audio>` carries no `src` and names its candidates in `<source>`s
5545    /// instead; [`resolve`](MediaInfo::resolve) already accounts for that.
5546    pub destination: String,
5547    /// The `<source>` alternatives in document order, or empty for a plain
5548    /// image. See [`MediaSource`]; a theme- or codec-aware frontend picks one and
5549    /// otherwise loads [`destination`](MediaInfo::destination).
5550    pub sources: Vec<MediaSource>,
5551    /// The media's alt text, flattened from its inline children (empty when it
5552    /// has none).
5553    pub alt: String,
5554    /// A `<video poster="…">`'s still frame, or empty when there is none — an
5555    /// image destination, resolved exactly as [`destination`] is.
5556    ///
5557    /// [`destination`]: MediaInfo::destination
5558    pub poster: String,
5559}
5560
5561/// One leaf directive (`::name{…}`) as a frontend sees it: which rows its
5562/// placeholder occupies, its type, and its attributes. A plain surface paints
5563/// the `⧉ name` placeholder glyphs as-is; a frontend that knows the host app's
5564/// vocabulary **skips the rows in `rows_span`** and paints the real thing there,
5565/// exactly as an image-capable one does with [`MediaInfo`]. Derived from
5566/// [`VRow::leaf_directive`] by [`directive_spans`].
5567///
5568/// Core resolves nothing here — it has no idea what an `embed` or a `toc` is,
5569/// and deliberately so: the directive vocabulary belongs to the app on top.
5570#[derive(Clone, Debug, PartialEq, Eq)]
5571pub struct DirectiveInfo {
5572    /// The [`VisualMap::rows`] rows this directive's placeholder occupies — the
5573    /// label row plus any blank fillers under it.
5574    pub rows_span: Range<usize>,
5575    /// The directive's type (`embed`, `toc`, `vis`), no leading colons.
5576    pub name: String,
5577    /// Its `{…}` attributes in source order; a bare one has a `None` value.
5578    pub attrs: Vec<(String, Option<String>)>,
5579    /// Its `[label]` text, flattened from its inline children (empty when it has
5580    /// none) — what the placeholder row shows.
5581    pub label: String,
5582}
5583
5584/// One formula as a frontend sees it: where its picture goes, and the TeX to
5585/// typeset for it. Two shapes, told apart by [`glyph`](MathInfo::glyph):
5586///
5587/// - An **inline atom** — `$E = mc^2$` in a line of prose — is one
5588///   [`Role::Math`] glyph on `row` at index `glyph`, standing for the whole
5589///   formula. A frontend that paints pictures in a line typesets the TeX at
5590///   the run's font size and draws the picture in the glyph's place, as wide
5591///   as the picture is and with the text baseline through it at its height —
5592///   a run delegate on Apple, an inline element on the web. The glyph is a
5593///   caret stop at the formula's start; the stop after it is the next glyph's.
5594/// - A **display block** — a paragraph holding nothing but `$$…$$` — is the
5595///   placeholder row (`∑ tex`, every glyph at the formula's start) plus the
5596///   blank fillers `rows_span` reserves under it, exactly a [`MediaInfo`]'s
5597///   shape. A frontend skips those rows and paints the picture there, centred
5598///   on the measure.
5599///
5600/// Either way the frontend supplies the *width*: core lays out in glyphs and
5601/// cannot know how wide a typeset formula is, which is why an inline atom is
5602/// one glyph and not a run of them. Only in a **column-wrapped** build does
5603/// that matter to the wrap: a terminal never asks for atoms (see
5604/// [`Surface::inline_pictures`]), and the web re-fits a row the picture
5605/// overflows.
5606///
5607/// A plain surface paints the glyphs as they are — `∑` for an atom, the
5608/// labelled row for a block — and needs none of this. Derived from
5609/// [`VRow::math`] by [`math_spans`], so it survives the row reuse of
5610/// [`BlockCache`] and [`build_spliced`].
5611#[derive(Clone, Debug, PartialEq, Eq)]
5612pub struct MathInfo {
5613    /// The [`VisualMap::rows`] rows this formula occupies: `row..row + 1` for
5614    /// an atom, the placeholder row and its fillers for a block.
5615    pub rows_span: Range<usize>,
5616    /// The row the atom glyph, or the block's placeholder label, is on.
5617    pub row: usize,
5618    /// The atom's index into that row's glyphs, or `None` for a block.
5619    pub glyph: Option<usize>,
5620    /// The TeX between the delimiters, verbatim.
5621    pub tex: String,
5622    /// Display style rather than text style — see [`MathMark::display`].
5623    pub display: bool,
5624    /// The formula's source start: where a click on its picture lands the
5625    /// caret, and the same offset every placeholder glyph carries.
5626    pub src: usize,
5627}
5628
5629impl DirectiveInfo {
5630    /// The value of attribute `key`, if it has one with a value. The convenience
5631    /// a frontend reaches for first (`info.attr("src")`), since almost every
5632    /// directive that draws as something real is pointed at by one attribute.
5633    pub fn attr(&self, key: &str) -> Option<&str> {
5634        self.attrs
5635            .iter()
5636            .find(|(k, _)| k == key)
5637            .and_then(|(_, v)| v.as_deref())
5638    }
5639}
5640
5641impl MediaInfo {
5642    /// The image URL to load under `scheme`: the first [`sources`] `<source>`
5643    /// whose media query matches, else the [`destination`] `<img>` fallback. The
5644    /// pick is a `<source>`'s first `srcset` URL or the destination — a frontend
5645    /// resolves whichever it gets against the document directory exactly as it
5646    /// resolves `destination`, and reserves/keys the picture under `destination`
5647    /// regardless, so a theme switch just re-picks without disturbing the layout.
5648    ///
5649    /// Only `prefers-color-scheme` is understood (that's what a light/dark banner
5650    /// uses); a `<source>` with any other media query is skipped, and one with no
5651    /// media at all always matches (an unconditional override). With no matching
5652    /// source — including every frontend that can't/doesn't theme and passes
5653    /// [`ColorScheme::Light`] to a dark-only picture — it's the plain `<img>`.
5654    ///
5655    /// [`sources`]: MediaInfo::sources
5656    /// [`destination`]: MediaInfo::destination
5657    pub fn resolve(&self, scheme: ColorScheme) -> &str {
5658        if let Some(url) = self
5659            .sources
5660            .iter()
5661            .find(|s| media_matches(&s.media, scheme))
5662            .and_then(|s| first_srcset_url(&s.srcset))
5663        {
5664            return url;
5665        }
5666        // A `<video>`/`<audio>` may carry no `src` of its own, naming its
5667        // candidates only in child `<source>`s — none of which matched above,
5668        // because a codec-typed `<source>` has no media query and core judges no
5669        // MIME types. Falling through to an empty destination would hand the
5670        // frontend nothing to load, so take the first candidate URL instead and
5671        // let the frontend reject it if it can't decode it. An `<img>` never
5672        // reaches this: its `src` is the picture.
5673        if self.destination.is_empty()
5674            && let Some(url) = self
5675                .sources
5676                .iter()
5677                .find_map(|s| first_srcset_url(&s.srcset))
5678        {
5679            return url;
5680        }
5681        &self.destination
5682    }
5683
5684    /// The **still picture** that stands for this media under `scheme`, for a
5685    /// frontend that can rasterize an image but not play a movie — a terminal, or
5686    /// a GUI still growing its player. `None` when there is no picture to draw,
5687    /// which is the honest answer for audio and for a poster-less video: the
5688    /// caller leaves core's labelled placeholder row, which already reads as
5689    /// *a thing that isn't text*.
5690    ///
5691    /// This exists so those frontends never hand a `.mp4` to an image decoder.
5692    /// That fails harmlessly today (a failed decode falls back to the same
5693    /// placeholder), but it spends a file read and a decode attempt per frame to
5694    /// arrive where this gets in one match.
5695    pub fn still(&self, scheme: ColorScheme) -> Option<&str> {
5696        match self.kind {
5697            MediaKind::Image => Some(self.resolve(scheme)),
5698            // A `poster` is an image destination, so it resolves the same way —
5699            // but it is named directly and has no `<source>` alternatives of its
5700            // own, so it needs no theme matching.
5701            MediaKind::Video if !self.poster.is_empty() => Some(&self.poster),
5702            MediaKind::Video | MediaKind::Audio => None,
5703        }
5704    }
5705}
5706
5707/// A frontend's active color scheme — what a `<picture>`'s `prefers-color-scheme`
5708/// `<source>`s are matched against by [`MediaInfo::resolve`]. A frontend with no
5709/// notion of theme passes [`Light`](ColorScheme::Light), the web's own default.
5710#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5711pub enum ColorScheme {
5712    Light,
5713    Dark,
5714}
5715
5716/// Whether a `<source media="…">` query applies under `scheme`. Empty media is
5717/// an unconditional `<source>` (always matches); otherwise only a
5718/// `prefers-color-scheme: dark|light` feature is understood — anything else
5719/// (a width query, `print`, …) doesn't match, so resolution falls through to the
5720/// next source or the `<img>`. Deliberately lax about the surrounding syntax
5721/// (`(prefers-color-scheme: dark)`, `screen and (prefers-color-scheme:dark)`):
5722/// it keys off the feature and its value, which is all the theme case needs.
5723fn media_matches(media: &str, scheme: ColorScheme) -> bool {
5724    let media = media.trim();
5725    if media.is_empty() {
5726        return true;
5727    }
5728    let lower = media.to_ascii_lowercase();
5729    let Some(after) = lower
5730        .split_once("prefers-color-scheme")
5731        .map(|(_, rest)| rest)
5732    else {
5733        return false;
5734    };
5735    // Skip the `:` and any spaces to reach the value word.
5736    let value = after.trim_start_matches([':', ' ', '\t']);
5737    let wanted = match scheme {
5738        ColorScheme::Light => "light",
5739        ColorScheme::Dark => "dark",
5740    };
5741    value.starts_with(wanted)
5742}
5743
5744/// The first URL in a `srcset`: its first comma-separated candidate, before any
5745/// `1x`/`2x`/width descriptor. The theme case only ever puts one URL per
5746/// `<source>`, so the first candidate is the picture.
5747fn first_srcset_url(srcset: &str) -> Option<&str> {
5748    let first = srcset.split(',').next()?.trim();
5749    first.split_whitespace().next().filter(|u| !u.is_empty())
5750}
5751
5752/// The narrowest a column may be squeezed. Below a few characters a column
5753/// stops carrying text and just shreds it one letter per line, which is worse
5754/// than letting the grid run wide.
5755const MIN_COL_WIDTH: usize = 3;
5756
5757/// Shrink `widths` until the grid fits `avail` screen columns, taking from the
5758/// widest column each time so the loss is shared out rather than falling on
5759/// whichever column happens to be last. No column goes below
5760/// [`MIN_COL_WIDTH`]; a table with more columns than the surface has room for
5761/// still overflows, which is the honest outcome — there's nothing left to give.
5762fn fit_widths(widths: &mut [usize], avail: usize) {
5763    // Chrome: each column is its content plus a gutter either side, and every
5764    // column is closed by a `│` — with one more opening the row.
5765    let budget = avail.saturating_sub(3 * widths.len() + 1);
5766    while widths.iter().sum::<usize>() > budget {
5767        let Some(w) = widths.iter_mut().filter(|w| **w > MIN_COL_WIDTH).max() else {
5768            return;
5769        };
5770        *w -= 1;
5771    }
5772}
5773
5774/// Word-wrap `glyphs` into lines of at most `width` columns, hard-breaking any
5775/// single word too long to fit.
5776///
5777/// Unlike a paragraph — where an overlong word just trails off the end of the
5778/// line — a table column is a hard boundary: a glyph past it lands on top of
5779/// the border, or on the next cell. So the width here is a promise, and a word
5780/// that won't keep it is broken.
5781///
5782/// The space at a break is dropped rather than hung past the edge. Its offset
5783/// isn't lost: the caller gives every line an end stop just past its last
5784/// glyph, which is exactly where that space was.
5785///
5786/// `width` is in display columns, and a break only ever falls between grapheme
5787/// clusters. Both matter to more than the picture: the caller anchors each
5788/// line's end stop just past its last glyph, so a line cut mid-cluster would
5789/// put a caret stop inside a character — reachable by Down or a click, and the
5790/// next Backspace would take the cluster apart from the middle.
5791///
5792/// An explicit in-cell break (a `\n` glyph, from a `<br>`) is a hard boundary:
5793/// each run between the breaks wraps on its own and the results stack. The break
5794/// glyphs are dropped — the caller's per-line end stop already sits exactly where
5795/// each break was, so no offset is lost.
5796fn wrap_glyphs(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
5797    if glyphs.iter().any(|g| g.ch == '\n') {
5798        return glyphs
5799            .split(|g| g.ch == '\n')
5800            .flat_map(|seg| wrap_segment(seg, width))
5801            .collect();
5802    }
5803    wrap_segment(glyphs, width)
5804}
5805
5806/// [`wrap_glyphs`] for a run with no explicit breaks — the word-wrap proper.
5807fn wrap_segment(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
5808    let width = width.max(1);
5809    // Words are maximal non-space runs, each carrying the space that followed it
5810    // — which survives only if the next word joins it on this line.
5811    let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
5812    let mut word: Vec<Glyph> = Vec::new();
5813    for g in glyphs {
5814        if g.ch == ' ' {
5815            words.push((std::mem::take(&mut word), Some(g.clone())));
5816        } else {
5817            word.push(g.clone());
5818        }
5819    }
5820    if !word.is_empty() {
5821        words.push((word, None));
5822    }
5823
5824    let mut lines: Vec<Vec<Glyph>> = Vec::new();
5825    let mut line: Vec<Glyph> = Vec::new();
5826    let mut used = 0usize;
5827    let mut gap: Option<Glyph> = None;
5828    for (word, space) in words {
5829        for chunk in hard_break(&word, width) {
5830            let sep = gap.is_some() as usize;
5831            let cells = glyphs_width(chunk);
5832            if !line.is_empty() && used + sep + cells > width {
5833                lines.push(std::mem::take(&mut line));
5834                used = 0;
5835                gap = None; // the break swallows the space
5836            }
5837            if let Some(sp) = gap.take() {
5838                line.push(sp);
5839                used += 1;
5840            }
5841            line.extend_from_slice(chunk);
5842            used += cells;
5843        }
5844        gap = space;
5845    }
5846    // An empty cell is still one (empty) line — it has an end the caret can
5847    // sit at, which is how you type into it.
5848    if !line.is_empty() || lines.is_empty() {
5849        lines.push(line);
5850    }
5851    lines
5852}
5853
5854/// Break a single word into pieces of at most `width` columns, cutting only
5855/// between grapheme clusters — the replacement for slicing it into fixed runs
5856/// of glyphs, which measures a wide character as one column and can cut an
5857/// emoji in half.
5858///
5859/// A cluster wider than the whole column still gets a piece to itself: there is
5860/// nowhere legal to cut it, and overflowing by a cell is better than splitting a
5861/// character. An empty word yields no pieces at all, which is what keeps a
5862/// double space from opening a line of its own.
5863fn hard_break(word: &[Glyph], width: usize) -> Vec<&[Glyph]> {
5864    let mut out = Vec::new();
5865    if word.is_empty() {
5866        return out;
5867    }
5868    let (mut start, mut used) = (0usize, 0usize);
5869    for c in clusters(word) {
5870        if used > 0 && used + c.cells > width {
5871            out.push(&word[start..c.glyph]);
5872            start = c.glyph;
5873            used = 0;
5874        }
5875        used += c.cells;
5876    }
5877    out.push(&word[start..]);
5878    out
5879}
5880
5881/// A table rule spanning `widths`, e.g. `┌──────┬─────┐`. Each column is its
5882/// content width plus the one-space gutter on either side.
5883fn rule_text(widths: &[usize], left: char, mid: char, right: char) -> String {
5884    let mut s = String::new();
5885    s.push(left);
5886    for (i, w) in widths.iter().enumerate() {
5887        if i > 0 {
5888            s.push(mid);
5889        }
5890        for _ in 0..w + 2 {
5891            s.push('─');
5892        }
5893    }
5894    s.push(right);
5895    s
5896}
5897
5898/// Push real document text: each glyph maps to its own source byte, and the one
5899/// that opens a grapheme cluster is the caret stop for the whole cluster.
5900///
5901/// Per cluster rather than per codepoint because a cluster is the character the
5902/// user sees, and it's the unit backspace and delete already step by. A stop
5903/// inside 👨‍👩‍👧 — five codepoints strung together with joiners — is a caret
5904/// parked in the middle of a character: one press of Right lands there, and the
5905/// next Backspace severs a joiner from what it joined, leaving a dangling ZWJ in
5906/// the source. The rest of the cluster still gets its glyph (it has to be
5907/// drawn); it just isn't somewhere to stand.
5908fn push_text(out: &mut Vec<Glyph>, text: &str, base_src: usize, style: Style) {
5909    for (gi, cluster) in text.grapheme_indices(true) {
5910        for (ci, ch) in cluster.char_indices() {
5911            out.push(Glyph {
5912                ch,
5913                style,
5914                src: base_src + gi + ci,
5915                stop: ci == 0,
5916            });
5917        }
5918    }
5919}
5920
5921/// [`push_text`] for one line of a highlighted code block: the same glyphs at
5922/// the same offsets, each additionally carrying the [`Token`] of the span it
5923/// falls in — `spans` being the line's entry from [`code_tokens`], ascending
5924/// byte ranges *into `text`*. A byte between spans keeps `style` as it is.
5925///
5926/// Offsets are what matters here: a token changes how a glyph is painted and
5927/// nothing about where it is or which source byte it stands on, so a caret
5928/// walks a highlighted block exactly as it walks an unhighlighted one.
5929fn push_code_text(
5930    out: &mut Vec<Glyph>,
5931    text: &str,
5932    base_src: usize,
5933    style: Style,
5934    spans: &[(Range<usize>, Token)],
5935) {
5936    let mut spans = spans.iter().peekable();
5937    for (gi, cluster) in text.grapheme_indices(true) {
5938        // Spans are ascending, so the one covering this cluster's first byte
5939        // is at or after the one that covered the last; step past those ended.
5940        while spans.peek().is_some_and(|(r, _)| r.end <= gi) {
5941            spans.next();
5942        }
5943        let token = spans
5944            .peek()
5945            .filter(|(r, _)| r.contains(&gi))
5946            .map(|(_, t)| *t);
5947        // A cluster is classed whole, by its first byte: a grammar that split
5948        // an emoji's scalars between two tokens would otherwise split the
5949        // glyph, and no grammar means to.
5950        let style = style.token(token);
5951        for (ci, ch) in cluster.char_indices() {
5952            out.push(Glyph {
5953                ch,
5954                style,
5955                src: base_src + gi + ci,
5956                stop: ci == 0,
5957            });
5958        }
5959    }
5960}
5961
5962/// One line's highlighting — `crate::syntax::LineTokens`, spelled here so the
5963/// shape exists whether or not the feature that fills it does.
5964type LineTokens = Vec<(Range<usize>, Token)>;
5965
5966/// The syntax highlighting for a code block's lines, or `None` when the fence's
5967/// language is not one the grammars know. Without the `syntax` feature nothing
5968/// is known, and every code glyph draws in the plain code colour.
5969#[cfg(feature = "syntax")]
5970fn code_tokens(lang: &str, lines: &[&str]) -> Option<Vec<LineTokens>> {
5971    crate::syntax::highlight(lang, lines)
5972}
5973
5974#[cfg(not(feature = "syntax"))]
5975fn code_tokens(_lang: &str, _lines: &[&str]) -> Option<Vec<LineTokens>> {
5976    None
5977}
5978
5979/// Emit an inline `str`/`smart_punctuation` run, mapping every visible char back
5980/// to its *true* source byte even when the source carries backslash escapes the
5981/// parsed `text` dropped (`\*` → `*`). The naive `span.start + text_offset`
5982/// mapping [`push_text`] uses drifts by one byte after each escape, so a caret or
5983/// click past an escaped `*` would land on the wrong character; walking the text
5984/// against its source keeps them aligned, and the hidden escape backslash gets no
5985/// glyph of its own (it is a spelling artefact, not something the caret lands on).
5986fn push_escaped_text(
5987    out: &mut Vec<Glyph>,
5988    text: &str,
5989    span: Range<usize>,
5990    source: &str,
5991    style: Style,
5992) {
5993    let end = span.end.min(source.len());
5994    let src = source.get(span.start..end).unwrap_or("");
5995    // Fast path — no dropped bytes, so text and source align 1:1 (the common
5996    // case: prose with no escapes). Byte lengths equal ⇒ no backslash was eaten.
5997    if src.len() == text.len() {
5998        push_text(out, text, span.start, style);
5999        return;
6000    }
6001    // Slow path: some `\` was consumed. Walk char-by-char, skipping a backslash
6002    // in the source exactly when it escapes the next visible char (a real escape),
6003    // never when it is a literal backslash the parse kept (that case has equal
6004    // lengths and takes the fast path above).
6005    let sb = src.as_bytes();
6006    let mut si = 0usize;
6007    'text: for (_, cluster) in text.grapheme_indices(true) {
6008        for (ci, ch) in cluster.char_indices() {
6009            // The text outlasted the source it is being mapped onto. In a
6010            // consistent document that cannot happen on this path: the slow path
6011            // is only entered when the two lengths differ, and everything that
6012            // makes them differ makes the *source* the longer one — an escape
6013            // backslash the parse ate, or source folded into a neighbouring node.
6014            // A `smart_punctuation` node reports its canonical ASCII spelling
6015            // (`--`, `...`, `"`), which is never longer than what was written.
6016            //
6017            // So reaching here means `span` was measured against a document that
6018            // `source` is no longer, and there is no honest offset left to give
6019            // the remaining characters. Stop: the row comes out short, which is
6020            // a wrong picture of a document that is already inconsistent. The
6021            // alternative was `si` stepping past the end and the slice below
6022            // panicking — which is what it did, in a paint loop.
6023            if si >= sb.len() {
6024                break 'text;
6025            }
6026            // Advance to the source character this one came from, stepping over
6027            // whatever the parse dropped on the way. An escape backslash is the
6028            // common case, but not the only one: a span can cover source that
6029            // was folded into a neighbouring node (smart punctuation next to a
6030            // bracket gives `text: "]"` over a source span of `"…]"`). Advancing
6031            // by the *text* character's length assumed escapes were the only
6032            // divergence, so one dropped multi-byte character desynchronized
6033            // every glyph after it — placing `]` inside the `…` before it.
6034            while si < sb.len() && !src[si..].starts_with(ch) {
6035                si += src[si..].chars().next().map_or(1, char::len_utf8);
6036            }
6037            out.push(Glyph {
6038                ch,
6039                style,
6040                src: span.start + si.min(src.len()),
6041                stop: ci == 0,
6042            });
6043            si += src[si..]
6044                .chars()
6045                .next()
6046                .map_or(ch.len_utf8(), char::len_utf8);
6047        }
6048    }
6049}
6050
6051/// Build synthetic decoration glyphs (a bullet, a gutter) all pointing at `src`,
6052/// each carrying `role` so the frontend can style it (`Role::Body` for plain
6053/// padding). Synthetic glyphs are never caret stops — they share one offset, so
6054/// the caret steps over them (a click still lands at `src`).
6055fn synth(text: &str, role: Role, src: usize) -> Vec<Glyph> {
6056    let style = Style::default().role(role);
6057    text.chars()
6058        .map(|ch| Glyph {
6059            ch,
6060            style,
6061            src,
6062            stop: false,
6063        })
6064        .collect()
6065}
6066
6067fn concat(a: &[Glyph], b: &[Glyph]) -> Vec<Glyph> {
6068    let mut v = a.to_vec();
6069    v.extend_from_slice(b);
6070    v
6071}
6072
6073/// The columns a row's prefix (a bullet, a quote gutter, an indent) takes up
6074/// before the text it introduces — what the wrap budget has left to spend.
6075fn prefix_width(prefix: &[Glyph]) -> usize {
6076    glyphs_width(prefix)
6077}
6078
6079/// The label shown for an image with no alt text: the final path segment of its
6080/// destination (`img/cat.png` → `cat.png`), the whole destination when it has no
6081/// separator, and `"image"` when it's empty. A `data:` URI (which has no useful
6082/// tail) shows its scheme so the placeholder isn't a wall of base64.
6083fn media_label(dest: &str) -> String {
6084    if dest.is_empty() {
6085        return "image".to_string();
6086    }
6087    if dest.starts_with("data:") {
6088        return "data:…".to_string();
6089    }
6090    // Trim a query/fragment so a URL's `?v=2#frag` doesn't ride along.
6091    let clean = dest.split(['?', '#']).next().unwrap_or(dest);
6092    let tail = clean
6093        .trim_end_matches('/')
6094        .rsplit(['/', '\\'])
6095        .next()
6096        .unwrap_or(clean);
6097    if tail.is_empty() {
6098        dest.to_string()
6099    } else {
6100        tail.to_string()
6101    }
6102}
6103
6104/// A directive's attributes read as a human label — what a frontend puts on a
6105/// container's tinted panel, and what an attribute-bearing inline directive
6106/// shows in its chip.
6107///
6108/// Reads BOTH conventions diaryx content actually uses: twig's own dot-prefixed
6109/// classes (`{.public .family}`, arriving as one combined `class` attr) and bare
6110/// pandoc-style words with no leading dot (`{public family}` — what
6111/// `diaryx_core::visibility`'s publish-time filter and apps/web's directive
6112/// serializer both write, and which twig parses as one valueless attribute
6113/// each). Reading only `.class` would leave every *existing* diaryx `:::vis{…}`
6114/// block unlabeled. A `key=value` attr is configuration rather than a name, so
6115/// it contributes nothing. `None` when nothing readable is left.
6116fn directive_attr_label(attrs: &[(String, Option<String>)]) -> Option<String> {
6117    let mut parts: Vec<String> = Vec::new();
6118    for (k, v) in attrs {
6119        if k == "class" {
6120            if let Some(v) = v
6121                && !v.is_empty()
6122            {
6123                parts.push(v.clone());
6124            }
6125        } else if v.as_deref().unwrap_or("").is_empty() {
6126            parts.push(k.clone());
6127        }
6128    }
6129    (!parts.is_empty()).then(|| parts.join(" "))
6130}
6131
6132fn heading_style(level: u32) -> Style {
6133    // Just the role — a frontend decides how a heading of this level *looks*
6134    // (the terminal cycles a color and bolds it, the GUI scales the font). The
6135    // author wrote no emphasis here, so core records none. `level as u8` is safe:
6136    // Markdown/Djot cap headings at 6.
6137    Style::default().role(Role::Heading(level.min(255) as u8))
6138}
6139
6140/// Is this `container` node a *directive* (`:::note{…}`, `::embed{…}`,
6141/// `:vis[…]`) rather than an HTML element (`<video>`, `<picture>`, `<div>`)?
6142///
6143/// twig 2.8 folded `div`/`span`/`directive`/`element` into one `container` kind,
6144/// and left nothing that separated them: `kind`, `name` and `directive_form` all
6145/// agree, field for field, on an HTML `<div>` and a Markdown `:::div`. Leaf
6146/// answered it by sniffing the span for whichever of `:` or `<` came first.
6147/// twig 3.0 records the answer at parse time as [`ContainerOrigin`], so this is
6148/// now the parser's own knowledge rather than a guess rebuilt from the bytes it
6149/// consumed.
6150pub(crate) fn container_is_directive(node: &FlatNode) -> bool {
6151    node.origin == Some(ContainerOrigin::Directive)
6152}
6153
6154/// The tag a `container` node carries when it is an HTML element rather than a
6155/// directive — `Some("video")` for a promoted `<video>`, `None` for a `:::note`
6156/// or for any node that is not a container at all.
6157pub(crate) fn element_tag(node: &FlatNode) -> Option<&str> {
6158    (node.origin == Some(ContainerOrigin::Element))
6159        .then_some(node.name.as_deref())
6160        .flatten()
6161}
6162
6163/// A leaf directive's name and whatever attributes are not part of spelling
6164/// it — the two things a [`DirectiveMark`] carries, which twig hands back
6165/// differently per format and which a frontend must not be able to tell apart.
6166///
6167/// Markdown's `::page-break` is a `Leaf`-form directive *named* `page-break`
6168/// with no attributes, and this returns it verbatim. Djot has no leaf form:
6169/// `insert_directive` writes the same document as an empty `::: page-break`
6170/// fence, whose container is anonymous (a djot div carries no name) and whose
6171/// name arrives as the fence's one class. So where the node has no name of its
6172/// own the first `class` token *is* the name, and whatever else the class said
6173/// — an author's `::: page-break {.wide}` — stays an attribute.
6174fn leaf_directive_identity(node: &FlatNode) -> (String, Vec<(String, Option<String>)>) {
6175    let named = node.name.clone().unwrap_or_default();
6176    if !named.is_empty() {
6177        return (named, node.attrs.clone());
6178    }
6179    let class = node
6180        .attrs
6181        .iter()
6182        .find(|(k, _)| k == "class")
6183        .and_then(|(_, v)| v.as_deref())
6184        .unwrap_or_default();
6185    let mut tokens = class.split_whitespace();
6186    let Some(name) = tokens.next().map(str::to_string) else {
6187        return (named, node.attrs.clone());
6188    };
6189    let rest = tokens.collect::<Vec<_>>().join(" ");
6190    let attrs = node
6191        .attrs
6192        .iter()
6193        .filter_map(|(k, v)| {
6194            if k != "class" {
6195                return Some((k.clone(), v.clone()));
6196            }
6197            (!rest.is_empty()).then(|| (k.clone(), Some(rest.clone())))
6198        })
6199        .collect();
6200    (name, attrs)
6201}
6202
6203/// Is this inline `container` an **attributed span** — the node leaf's run-level
6204/// vocabulary rides — rather than a named directive?
6205///
6206/// The four formats spell one span four ways and twig hands the name back for
6207/// two of them: HTML's and Markdown's `<span …>` arrive named `span` with
6208/// `Element` origin, while djot's `[text]{…}` and AsciiDoc's `[.a]#text#`
6209/// arrive anonymous (an empty name) with `Directive` origin. All four are the
6210/// same node to `wrap_range_attrs`, which is what writes them, so they are the
6211/// same node here.
6212///
6213/// A *named* directive is not one, whatever its name: a Markdown `:span[…]{…}`
6214/// is a directive the parser read as a directive, twig's own
6215/// `wrap_range_attrs` says so, and it keeps the handling it has.
6216///
6217/// **Anonymous is not enough**, and the form is what finishes the question:
6218/// a djot fenced div (`{.center}` / `:::` / … / `:::`) is anonymous too, with
6219/// the same `Directive` origin, and is a *block* — `Container` form against the
6220/// span's `Text`. Reading one as a span made every gesture and every query lie
6221/// about it: `set_text_color` over a word inside such a div copied the whole
6222/// div's attribute set — its `id` along with the rest — onto the new span, and
6223/// `alignment_at_caret` reported the div's `.center` as a *run's* answer while
6224/// the walker drew none. So the anonymous arm asks the form [`is_inline`] asks.
6225pub(crate) fn is_run_span(node: &FlatNode) -> bool {
6226    if node.kind != Kind::Container {
6227        return false;
6228    }
6229    match node.name.as_deref() {
6230        None | Some("") => node.directive_form == Some(DirectiveForm::Text),
6231        Some("span") => node.origin == Some(ContainerOrigin::Element),
6232        Some(_) => false,
6233    }
6234}
6235
6236/// `base` with an attributed span's three run-level keys written over it — the
6237/// nearest-wins fold [`is_run_span`] describes, for one span. `faces` is the
6238/// build's intern table, as it is for [`Presentation::under`].
6239fn run_style(node: &FlatNode, base: Style, faces: &RefCell<FaceTable>) -> Style {
6240    Style {
6241        size: FontSize::from_attrs(&node.attrs).or(base.size),
6242        font: faces
6243            .borrow_mut()
6244            .face_from_attrs(&node.attrs)
6245            .or(base.font),
6246        color: TextColor::from_attrs(&node.attrs).or(base.color),
6247        ..base
6248    }
6249}
6250
6251pub(crate) fn is_inline(node: &FlatNode) -> bool {
6252    // A directive is inline only in its `text` form (`:name[label]{…}`); the
6253    // `leaf` and `container` forms are blocks. All three report the same `kind`,
6254    // so the form is the only thing telling them apart — and getting it wrong
6255    // costs a whole paragraph: a text directive misread as a block makes its
6256    // paragraph fail the "all children inline" test in `block`, and the line is
6257    // then walked as a container of blocks, rendering as empty rows with no
6258    // caret home at all.
6259    //
6260    // An HTML element shares the `container` kind, and twig sets the same form
6261    // on the two tags the lightweight formats have a generic spelling for: a
6262    // `<span>` is `Text` and a `<div>` is `Container`, while a `<video>` or a
6263    // `<picture>` has no form at all. So the form answers for an element as it
6264    // answers for a directive, and the origin is not consulted — which is what
6265    // makes a `<span …>` inside a paragraph an inline node.
6266    //
6267    // It has to. `wrap_range_attrs` spells an attributed run as exactly that
6268    // span in Markdown and HTML, and a paragraph holding one whose kids were
6269    // not all inline failed the test below and was walked as a container of
6270    // blocks: the text either side of the span rendered as nothing at all.
6271    if node.kind == Kind::Container {
6272        return node.directive_form == Some(DirectiveForm::Text);
6273    }
6274    is_inline_kind(&node.kind)
6275}
6276
6277/// [`is_inline`] by kind alone — for the ancestor walks, whose `QueryMatch`es
6278/// carry no `directive_form`. It answers `false` for every directive, which its
6279/// callers must (and do) reconcile: they pair it with `is_block_container`,
6280/// which claims every directive, so the pair's verdict is the same one a form
6281/// would have given. Anything looking at a *directive itself* wants [`is_inline`]
6282/// and a real node.
6283pub(crate) fn is_inline_kind(kind: &Kind) -> bool {
6284    matches!(
6285        kind,
6286        Kind::Str
6287            | Kind::SoftBreak
6288            | Kind::HardBreak
6289            | Kind::NonBreakingSpace
6290            | Kind::Emph
6291            | Kind::Strong
6292            | Kind::Mark
6293            | Kind::Insert
6294            | Kind::Delete
6295            | Kind::Verbatim
6296            | Kind::InlineMath
6297            | Kind::DisplayMath
6298            | Kind::Url
6299            | Kind::Email
6300            | Kind::Link
6301            | Kind::Image
6302            | Kind::SmartPunctuation
6303            | Kind::Superscript
6304            | Kind::Subscript
6305            | Kind::FootnoteReference
6306    )
6307}
6308
6309/// Assert two maps are identical down to every glyph, stop, and table span — the
6310/// contract `build_cached` and `build_spliced` must hold against `build`. Lives
6311/// at module scope (not in `mod tests`) so the Doc-driven differential test in
6312/// `doc.rs` can reach it and the private `stops` field it compares.
6313#[cfg(test)]
6314pub(crate) fn assert_maps_eq(a: &VisualMap, b: &VisualMap, ctx: &str) {
6315    assert_eq!(a.rows.len(), b.rows.len(), "row count ({ctx})");
6316    for (i, (ra, rb)) in a.rows.iter().zip(&b.rows).enumerate() {
6317        assert_eq!(ra.end_src, rb.end_src, "row {i} end_src ({ctx})");
6318        assert_eq!(ra.decoration, rb.decoration, "row {i} decoration ({ctx})");
6319        // The incremental walk labels a boundary from a query match's kind
6320        // string and the whole-arena walk from a `FlatNode`'s; this is what says
6321        // the two doors reach the same answer.
6322        assert_eq!(ra.boundary, rb.boundary, "row {i} boundary ({ctx})");
6323        assert_eq!(ra.code, rb.code, "row {i} code ({ctx})");
6324        assert_eq!(ra.code_lang, rb.code_lang, "row {i} code_lang ({ctx})");
6325        assert_eq!(ra.align, rb.align, "row {i} align ({ctx})");
6326        assert_eq!(
6327            ra.line_height, rb.line_height,
6328            "row {i} line_height ({ctx})"
6329        );
6330        assert_eq!(
6331            ra.glyphs.len(),
6332            rb.glyphs.len(),
6333            "row {i} glyph count ({ctx})"
6334        );
6335        for (j, (ga, gb)) in ra.glyphs.iter().zip(&rb.glyphs).enumerate() {
6336            assert_eq!(
6337                (ga.ch, ga.src, ga.stop, ga.style),
6338                (gb.ch, gb.src, gb.stop, gb.style),
6339                "row {i} glyph {j} ({ctx})"
6340            );
6341        }
6342    }
6343    assert_eq!(a.content_start, b.content_start, "content_start ({ctx})");
6344    assert_eq!(a.stops, b.stops, "stops ({ctx})");
6345    assert_eq!(a.mark_ends, b.mark_ends, "mark_ends ({ctx})");
6346    assert_eq!(a.tables.len(), b.tables.len(), "table count ({ctx})");
6347    for (i, (ta, tb)) in a.tables.iter().zip(&b.tables).enumerate() {
6348        assert_eq!(ta.rows_span, tb.rows_span, "table {i} rows_span ({ctx})");
6349        assert_eq!(ta.end_src, tb.end_src, "table {i} end_src ({ctx})");
6350    }
6351    assert_eq!(a.code_blocks, b.code_blocks, "code_blocks ({ctx})");
6352    assert_eq!(a.media, b.media, "images ({ctx})");
6353}
6354
6355#[cfg(test)]
6356mod tests {
6357    use super::*;
6358    use crate::style::{FontFamily, LineSpacing, SizeStep};
6359    use twig::{Editor, Format, NodeId};
6360
6361    fn map(src: &str) -> VisualMap {
6362        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6363        build_t(&ed.nodes().unwrap(), src, Some(80))
6364    }
6365
6366    /// [`map`] over a Djot source. Djot is the format that spells superscript
6367    /// and subscript at all — Markdown has no syntax for either.
6368    fn map_djot(src: &str) -> VisualMap {
6369        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
6370        build_t(&ed.nodes().unwrap(), src, Some(80))
6371    }
6372
6373    /// The baseline every glyph spelling `ch` was built with, in row order —
6374    /// how a test reads a raised or lowered run off the map without caring
6375    /// which row it landed on.
6376    fn baselines_of(m: &VisualMap, ch: char) -> Vec<Baseline> {
6377        m.rows
6378            .iter()
6379            .flat_map(|r| r.glyphs.iter())
6380            .filter(|g| g.ch == ch)
6381            .map(|g| g.style.baseline)
6382            .collect()
6383    }
6384
6385    /// [`map`] at a chosen wrap width.
6386    fn map_at(src: &str, wrap: Option<usize>) -> VisualMap {
6387        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6388        build_t(&ed.nodes().unwrap(), src, wrap)
6389    }
6390
6391    /// [`map`], but with twig's `directives` extension on (off by twig's own
6392    /// default) — the `:::name{.class}` fenced-div containers leaf-core's
6393    /// `"directive"` wysiwyg arm renders.
6394    fn map_directives(src: &str) -> VisualMap {
6395        let mut ed = Editor::new_ext(
6396            src.as_bytes(),
6397            Format::Markdown,
6398            twig::MarkdownExtensions {
6399                directives: true,
6400                ..Default::default()
6401            },
6402        )
6403        .unwrap();
6404        build_t(&ed.nodes().unwrap(), src, Some(80))
6405    }
6406
6407    /// [`map`] in `format`, parsed the way every leaf document is — the
6408    /// extensions [`crate::doc::parse_extensions`] turns on, which is what
6409    /// pairs a Markdown `<div …>` with its `</div>` into a container and makes
6410    /// `::page-break` a directive rather than a paragraph of colons.
6411    fn map_leaf(src: &str, format: Format) -> VisualMap {
6412        let mut ed =
6413            Editor::new_ext(src.as_bytes(), format, crate::doc::parse_extensions()).unwrap();
6414        build_t(&ed.nodes().unwrap(), src, Some(80))
6415    }
6416
6417    /// The alignment and line spacing of every row that draws text, in order —
6418    /// how a test reads a block property off the map.
6419    fn line_facts(m: &VisualMap) -> Vec<(Option<Align>, Option<LineHeight>)> {
6420        m.rows
6421            .iter()
6422            .filter(|r| r.glyphs.iter().any(|g| !g.ch.is_whitespace()))
6423            .map(|r| (r.align, r.line_height))
6424            .collect()
6425    }
6426
6427    /// The style of the glyph spelling `ch`, first occurrence — how a test reads
6428    /// a run property off the map.
6429    fn style_of(m: &VisualMap, ch: char) -> Style {
6430        m.rows
6431            .iter()
6432            .flat_map(|r| r.glyphs.iter())
6433            .find(|g| g.ch == ch)
6434            .unwrap_or_else(|| panic!("no glyph {ch:?} in the map"))
6435            .style
6436    }
6437
6438    /// [`map`] with soft breaks preserved (`LineFlow::Preserve`).
6439    fn map_preserve(src: &str, wrap: Option<usize>) -> VisualMap {
6440        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6441        build(
6442            &ed.nodes().unwrap(),
6443            src,
6444            wrap,
6445            true,
6446            &Surface::default(),
6447            None,
6448        )
6449    }
6450
6451    /// The cache-free reference [`build`], with no per-image height overrides —
6452    /// every block image stays its default one-row placeholder. The tests that
6453    /// need a taller image drive it through [`crate::Doc::set_media_rows`] instead.
6454    fn build_t(nodes: &[FlatNode], src: &str, wrap: Option<usize>) -> VisualMap {
6455        build(nodes, src, wrap, false, &Surface::default(), None)
6456    }
6457
6458    /// An arena and a string that disagree — spans reaching past the source they
6459    /// are built against.
6460    ///
6461    /// [`crate::Doc`] keeps the two in step, so this is a "cannot happen" that
6462    /// nonetheless *did*: `examples/bench` timed a loop of `edit_range` and then
6463    /// went on handing the grown editor's spans to a builder holding the string
6464    /// from before it, and every run ended in a slice panic rather than a
6465    /// number. `push_escaped_text` was already written to survive the mismatch —
6466    /// it clamps the span's end and falls back to an empty slice — and this is
6467    /// the half of that intent it did not carry through.
6468    ///
6469    /// Rendering the wrong thing is the acceptable answer here; panicking in a
6470    /// paint loop is not.
6471    #[test]
6472    fn a_source_shorter_than_the_arena_built_over_it_renders_rather_than_panicking() {
6473        // An escape puts the run on `push_escaped_text`'s slow path — the fast
6474        // path is a length comparison that a truncated source fails anyway.
6475        let src = "alpha \\*beta\\* gamma delta epsilon\n";
6476        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6477        let nodes = ed.nodes().unwrap();
6478
6479        // Every truncation of it, so the cut lands before, inside and after the
6480        // escaped run rather than only where one hand-picked index put it.
6481        for cut in 0..=src.len() {
6482            if !src.is_char_boundary(cut) {
6483                continue;
6484            }
6485            let map = build_t(&nodes, &src[..cut], Some(80));
6486            for row in &map.rows {
6487                for g in &row.glyphs {
6488                    assert!(
6489                        g.src <= src.len(),
6490                        "cut {cut}: glyph {:?} points past the source at {}",
6491                        g.ch,
6492                        g.src
6493                    );
6494                }
6495            }
6496        }
6497    }
6498
6499    fn rendered(m: &VisualMap) -> String {
6500        m.rows
6501            .iter()
6502            .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
6503            .collect::<Vec<_>>()
6504            .join("\n")
6505    }
6506
6507    /// Render a source both ways: `build` over the whole marshalled arena (the
6508    /// reference), and `build_cached` driven the way [`crate::Doc`] drives it —
6509    /// top-level blocks from `child_spans`, per-block subtrees on a miss.
6510    fn render_both(
6511        ed: &mut Editor,
6512        src: &str,
6513        wrap: Option<usize>,
6514        cache: &mut BlockCache,
6515    ) -> (VisualMap, VisualMap) {
6516        let all = ed.nodes().unwrap();
6517        let surface = Surface::default();
6518        let plain = build(&all, src, wrap, false, &surface, None);
6519        let top = top_blocks(ed);
6520        let cached = build_cached(&top, src, wrap, false, &surface, None, cache, |id| {
6521            ed.subtree(NodeId(id)).unwrap_or_default()
6522        });
6523        (plain, cached)
6524    }
6525
6526    /// The whole correctness claim of the block cache: `build_cached` produces a
6527    /// byte-identical map to `build`, on a fresh cache *and* — the case that
6528    /// actually exercises reuse-and-shift plus per-block subtree marshalling — on
6529    /// a warm cache after the source has been edited underneath it.
6530    /// **Every glyph must stand on the character it claims.** A row's source
6531    /// extent is computed from its last glyph's offset, so a glyph carrying an
6532    /// offset that is not its own character's start yields a row end inside a
6533    /// multi-byte character — and every later slice of the source panics on it.
6534    ///
6535    /// Reproduces a real crash from a journal entry: a bracketed elision inside
6536    /// a blockquote (`[…]`) gave the closing bracket a `text` of `"]"` over a
6537    /// source span covering `"…]"`, because the parse folded the ellipsis into a
6538    /// neighbouring node. `push_escaped_text` walked that span assuming a
6539    /// dropped backslash was the only way text and source could diverge, so the
6540    /// `]` landed on the `…`'s first byte:
6541    /// `byte index 1236 is not a char boundary; it is inside '…'`.
6542    #[test]
6543    fn a_glyph_never_lands_inside_the_character_before_it() {
6544        let src = "> engage with it rather than look away. […]\n>\n> The through-line\n";
6545        let vmap = map(src);
6546        for (r, row) in vmap.rows.iter().enumerate() {
6547            assert!(
6548                src.is_char_boundary(row.end_src.min(src.len())),
6549                "row {r} ends at {} — inside a character",
6550                row.end_src
6551            );
6552            for g in &row.glyphs {
6553                assert!(
6554                    src.is_char_boundary(g.src.min(src.len())),
6555                    "row {r} has {:?} at {}, which is inside a character",
6556                    g.ch,
6557                    g.src
6558                );
6559            }
6560        }
6561        // The elision survives, and its bracket sits on the real `]`.
6562        let text: String = vmap
6563            .rows
6564            .iter()
6565            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
6566            .collect();
6567        assert!(text.contains("[…]"), "the elision should render: {text:?}");
6568        let close = vmap
6569            .rows
6570            .iter()
6571            .flat_map(|r| r.glyphs.iter())
6572            .find(|g| g.ch == ']')
6573            .expect("a closing bracket");
6574        assert_eq!(
6575            src[close.src..].chars().next(),
6576            Some(']'),
6577            "the bracket glyph should stand on the source's own `]`"
6578        );
6579    }
6580
6581    #[test]
6582    fn build_cached_matches_build() {
6583        let docs = [
6584            "# Title\n\nThe quick brown fox.\n\nAnother paragraph here.\n",
6585            "## H\n\n- one\n- two\n- three\n\n> a quote\n> continued\n",
6586            "para one\n\n```\ncode\nlines\n```\n\nafter code\n",
6587            "| a | b |\n|---|---|\n| 1 | 2 |\n\ntext after a table\n",
6588            "line\n- \nsetext?\n\nreal para\n\n\n\ntrailing blanks\n",
6589            "> quote with **bold** and a [link](https://x.dev)\n>\n> - item\n> - item2\n\ntail\n",
6590            "intro\n\n![a cat](img/cat.png)\n\nbetween\n\n![](https://x.dev/logo.svg)\n\nend\n",
6591            "- text item\n- ![alt](pic.png)\n- more text\n",
6592            // Footnotes: twig parses each definition as a root beside `doc`, so
6593            // these are the docs where the reference build and the incremental
6594            // one could disagree about what the top-level blocks even are.
6595            "A claim[^1] and another[^src].\n\n[^1]: First note.\n\n[^src]: Second.\n\ntail\n",
6596            "note[^a]\n\n[^a]: body **bold**\n    wrapped on\n    three lines\n\nafter\n",
6597            // No trailing newline. twig closes the document's last block on the
6598            // virtual newline it supplies at EOF, so that block's `span.end` is
6599            // `source.len() + 1` — a range that slices no bytes at all. Keying
6600            // the block cache off such a slice made every last block hash alike;
6601            // see [`block_bytes`].
6602            "# Title\n\nThe quick brown fox.\n\nA tail with no newline",
6603            "A claim[^1] and another[^src].\n\n[^1]: First note.\n[^src]: Second, ending the file.",
6604            // Comments draw nothing. The per-block builder the cached path
6605            // renders one with starts at offset 0 and, drawing nothing, never
6606            // moved — so the walk went on from 0 and spelled every line of the
6607            // document as a blank row. One at the start, one between blocks,
6608            // one at the end, so each position is covered.
6609            "<!-- lead -->\n\npara\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n\n<!-- trail -->\n",
6610            // A Markdown `<div>` ends with a hidden `</div>` line the walk
6611            // steps over — between blocks and closing the file, so both the
6612            // separator after it and the trailing count are covered.
6613            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
6614            "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n",
6615            // Link reference definitions: roots beside `doc` like footnotes,
6616            // but drawing nothing. Alone between blocks, glued under a
6617            // paragraph, and closing the file under a comment — the README
6618            // shape.
6619            "see [a] and [b]\n\n[a]: /a\n\nmid\n[b]: /b \"bee\"\n\nend [c]\n\n<!-- links -->\n[c]: /c\n",
6620        ];
6621        for wrap in [None, Some(80usize), Some(20)] {
6622            for src in docs {
6623                let ctx = format!("wrap={wrap:?} src={src:?}");
6624                let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6625                let mut cache = BlockCache::default();
6626
6627                // 1) Fresh cache equals the cache-free build.
6628                let (plain, cached) = render_both(&mut ed, src, wrap, &mut cache);
6629                assert_maps_eq(&plain, &cached, &format!("fresh {ctx}"));
6630
6631                // 2) Type a char mid-document, reparse, rebuild with the now-warm
6632                //    cache: the edited block is re-marshalled and re-rendered,
6633                //    every block below it is reused shifted, and the result must
6634                //    still match a from-scratch build.
6635                let at = (src.len() / 2..=src.len())
6636                    .find(|&i| src.is_char_boundary(i))
6637                    .unwrap();
6638                ed.edit_range(at, at, "Z").unwrap();
6639                let src2 = ed.source_str().unwrap();
6640                let (plain2, cached2) = render_both(&mut ed, &src2, wrap, &mut cache);
6641                assert_maps_eq(&plain2, &cached2, &format!("after insert {ctx}"));
6642
6643                // 3) Delete it again: offsets shift back the other way, and the
6644                //    warm cache must not hand back stale shifted rows.
6645                ed.edit_range(at, at + 1, "").unwrap();
6646                let src3 = ed.source_str().unwrap();
6647                let (plain3, cached3) = render_both(&mut ed, &src3, wrap, &mut cache);
6648                assert_maps_eq(&plain3, &cached3, &format!("after delete {ctx}"));
6649            }
6650        }
6651    }
6652
6653    /// A document that does not end in a newline is the one place twig hands
6654    /// leaf a top-level span that addresses no source: the last block is closed
6655    /// on the virtual newline the parser supplies at EOF, so its `span.end` is
6656    /// `source.len() + 1`. The block cache keys on the bytes under that span, and
6657    /// reading the out-of-range slice as *no bytes* broke it two ways at once —
6658    /// [`block_bytes`] has the full account. Both ways are checked here, because
6659    /// they fail independently.
6660    #[test]
6661    fn a_block_running_past_the_last_byte_still_keys_the_cache_by_its_own_bytes() {
6662        // One: two overrunning blocks collide. A footnote definition is a root
6663        // beside `doc` that [`top_blocks`] merges into the top level, while the
6664        // `section` above it spans the definition's bytes too — so when the
6665        // definition ends the file, both blocks end past it. The second was
6666        // served the first's rows, and the definition rendered as a copy of the
6667        // heading.
6668        let src = "A claim[^1] worth checking.\n\n# A heading with a reference[^1] in it\n\n[^1]: The first note.\n[^note]: A note with a word for a label.";
6669        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
6670        let (plain, cached) = render_both(&mut ed, src, Some(80), &mut BlockCache::default());
6671        assert_maps_eq(&plain, &cached, "a definition ending the file");
6672        let text = rendered(&cached);
6673        assert!(
6674            text.ends_with("[note] A note with a word for a label."),
6675            "the last definition should render itself: {text:?}"
6676        );
6677        assert_eq!(
6678            text.matches("A heading with a reference").count(),
6679            1,
6680            "the heading should render exactly once: {text:?}"
6681        );
6682
6683        // Two: one overrunning block goes stale. Its bytes are its cache key, so
6684        // a block that keeps hashing the same however it is edited is served the
6685        // rows built before the edit — the whole last line frozen as the user
6686        // types in it.
6687        let mut cache = BlockCache::default();
6688        let first = "first para\n\n# A heading\n\nlast para with no newline";
6689        let mut ed = Editor::new_str(first, Format::Djot).unwrap();
6690        let (_, warm) = render_both(&mut ed, first, Some(80), &mut cache);
6691        assert!(rendered(&warm).ends_with("last para with no newline"));
6692
6693        let second = "first para\n\n# A heading\n\nDIFFERENT text without a newline";
6694        let mut ed = Editor::new_str(second, Format::Djot).unwrap();
6695        let (plain, cached) = render_both(&mut ed, second, Some(80), &mut cache);
6696        assert_maps_eq(&plain, &cached, "edited last block, warm cache");
6697        let text = rendered(&cached);
6698        assert!(
6699            text.ends_with("DIFFERENT text without a newline"),
6700            "the warm cache served the pre-edit rows: {text:?}"
6701        );
6702    }
6703
6704    #[test]
6705    fn resolves_markup_to_plain_text() {
6706        let text = rendered(&map("# Title\n\na **bold** word\n"));
6707        assert!(!text.contains('#'), "heading marker shown: {text:?}");
6708        assert!(!text.contains("**"), "strong delimiters shown: {text:?}");
6709        assert!(text.contains("Title") && text.contains("bold word"));
6710    }
6711
6712    #[test]
6713    fn every_glyph_points_at_its_source_byte() {
6714        let src = "a **bold** c\n";
6715        let m = map(src);
6716        for row in &m.rows {
6717            for g in &row.glyphs {
6718                // A real (non-synthetic) glyph's source byte is the glyph's char.
6719                if g.src < src.len()
6720                    && src.is_char_boundary(g.src)
6721                    && let Some(sc) = src[g.src..].chars().next()
6722                    && sc == g.ch
6723                {
6724                    continue;
6725                }
6726                // Synthetic prefixes (none here) would be the only exceptions.
6727                panic!("glyph {:?} at src {} doesn't match source", g.ch, g.src);
6728            }
6729        }
6730    }
6731
6732    #[test]
6733    fn offset_and_position_round_trip_on_visible_text() {
6734        let m = map("hello world\n");
6735        let (r, c) = m.pos_of_offset(6); // the 'w'
6736        assert_eq!(m.offset_of_pos(r, c), 6);
6737    }
6738
6739    #[test]
6740    fn visible_utf16_indices_count_the_text_the_system_sees() {
6741        // Hidden delimiters, a two-unit emoji, and a block gap — every way the
6742        // visible text's UTF-16 length parts company with a source byte count.
6743        let src = "a **b\u{1F600}** c\n\nd\n";
6744        let m = map(src);
6745        let end = m.snap_to_stop(src.len());
6746        let text = m.visible_text(0, end);
6747        assert_eq!(text, "a b\u{1F600} c\nd");
6748
6749        // Forward: the index of each offset is where that character sits in
6750        // the visible string, in UTF-16 units.
6751        for (i, (src_off, _)) in m.visible_items(0, end).iter().enumerate() {
6752            let expect: usize = text.chars().take(i).map(char::len_utf16).sum();
6753            assert_eq!(
6754                m.visible_utf16_len(0, *src_off),
6755                expect,
6756                "utf16 index of source offset {src_off}"
6757            );
6758            // And back: the index resolves to the offset it came from.
6759            assert_eq!(m.offset_at_visible_utf16(end, expect), Some(*src_off));
6760        }
6761        // Inside the emoji's surrogate pair resolves to the emoji.
6762        let emoji_src = src.find('\u{1F600}').unwrap();
6763        let emoji_idx = m.visible_utf16_len(0, emoji_src);
6764        assert_eq!(
6765            m.offset_at_visible_utf16(end, emoji_idx + 1),
6766            Some(emoji_src)
6767        );
6768        // At or past the end is nobody's character.
6769        let total = m.visible_utf16_len(0, end);
6770        assert_eq!(total, text.encode_utf16().count());
6771        assert_eq!(m.offset_at_visible_utf16(end, total), None);
6772    }
6773
6774    /// The documents the lookups are checked against their reference scans
6775    /// on: every shape that puts rows out of source order or a stop out of
6776    /// step with a glyph. A wrapped table, whose cells' second lines sit
6777    /// below the next column's first; a wide grapheme and an emoji outside
6778    /// the BMP; hidden delimiters and a link's hidden destination; a list
6779    /// with synthetic markers; a code block; an image row whose label glyphs
6780    /// all share one offset; an empty paragraph, a heading, and a wrapped
6781    /// paragraph — at a narrow width so the table and the prose both wrap,
6782    /// and unwrapped, which is how a GUI builds it.
6783    fn lookup_maps() -> Vec<(String, VisualMap)> {
6784        let table = "| left cell that wraps | right |\n|---|---|\n| a longer cell than the column can hold | b |\n| `k` | 你好 |\n\n";
6785        let srcs = [
6786            "hello world\n",
6787            "a **b\u{1F600}** c\n\nd\n",
6788            "- one *two*\n- three\n\n\n# Title\n\nend [link](https://e.org/x) tail\n",
6789            &format!("{table}```\nx\ny\n```\n\n![alt](a.png)\n\ntail 你好 **bold** here\n"),
6790            "one two three four five six seven eight nine ten eleven twelve thirteen\n\n| a | b |\n|-|-|\n| c d e f g h | i |\n",
6791        ];
6792        let mut out = Vec::new();
6793        for src in srcs {
6794            for wrap in [Some(14), None] {
6795                out.push((format!("{src:?} at {wrap:?}"), map_at(src, wrap)));
6796            }
6797        }
6798        out
6799    }
6800
6801    /// `pos_of_offset` as it was written before the walk learnt to dismiss a
6802    /// row from its ends: every row read through, the nearest stop kept.
6803    fn pos_of_offset_by_scan(m: &VisualMap, off: usize) -> (usize, usize) {
6804        let mut best: Option<(usize, usize, usize)> = None;
6805        for (r, row) in m.rows.iter().enumerate() {
6806            if row.decoration {
6807                continue;
6808            }
6809            let cand = row
6810                .glyphs
6811                .iter()
6812                .enumerate()
6813                .find(|(_, g)| g.stop && g.src >= off)
6814                .map(|(i, g)| (g.src, r, row.col_of_glyph(i)))
6815                .or_else(|| (row.end_src >= off).then_some((row.end_src, r, row.width())));
6816            if let Some(c) = cand
6817                && best.is_none_or(|b| c.0 <= b.0)
6818            {
6819                best = Some(c);
6820            }
6821        }
6822        match best {
6823            Some((_, r, c)) => (r, c),
6824            None => {
6825                let r = m.last_stop_row();
6826                (r, m.row_width(r))
6827            }
6828        }
6829    }
6830
6831    /// `visible_items` as it was written before the spelling was tabulated:
6832    /// every stop glyph in the range gathered, sorted, and paired up.
6833    fn visible_items_by_scan(m: &VisualMap, from: usize, to: usize) -> Vec<(usize, Option<char>)> {
6834        let (lo, hi) = m.visible_span(from, to);
6835        let from = m.snap_to_glyph_stop(from);
6836        let mut glyphs: Vec<(usize, char)> = m
6837            .rows
6838            .iter()
6839            .filter(|r| !r.decoration)
6840            .flat_map(|r| r.glyphs.iter())
6841            .filter(|g| g.stop && g.src >= from && g.src < to)
6842            .map(|g| (g.src, g.ch))
6843            .collect();
6844        glyphs.sort_by_key(|&(src, _)| src);
6845        glyphs.dedup_by_key(|&mut (src, _)| src);
6846        let cell_ends: Vec<usize> = m
6847            .tables
6848            .iter()
6849            .flat_map(|t| t.grid.iter())
6850            .flat_map(|r| r.cells.iter())
6851            .map(|c| c.end)
6852            .collect();
6853        m.stops[lo..hi]
6854            .iter()
6855            .map(|&s| {
6856                let ch = glyphs
6857                    .iter()
6858                    .find(|&&(src, _)| src == s)
6859                    .filter(|_| !cell_ends.contains(&s))
6860                    .map(|&(_, ch)| ch);
6861                (s, ch)
6862            })
6863            .collect()
6864    }
6865
6866    #[test]
6867    fn pos_of_offset_agrees_with_reading_every_row_through() {
6868        for (name, m) in lookup_maps() {
6869            let len = m.rows.iter().map(|r| r.end_src).max().unwrap_or(0) + 2;
6870            for off in 0..=len {
6871                assert_eq!(
6872                    m.pos_of_offset(off),
6873                    pos_of_offset_by_scan(&m, off),
6874                    "offset {off} of {name}"
6875                );
6876            }
6877        }
6878    }
6879
6880    #[test]
6881    fn the_tabulated_spelling_agrees_with_gathering_the_glyphs() {
6882        for (name, m) in lookup_maps() {
6883            let end = m.stops.last().copied().unwrap_or(0);
6884            // Whole text, and every window a frontend might ask for.
6885            let mut spans = vec![(0, end)];
6886            for &a in m.stops.iter().step_by(3) {
6887                spans.push((a, end));
6888                spans.push((0, a));
6889                spans.push((a, (a + 5).min(end)));
6890            }
6891            for (from, to) in spans {
6892                let items = visible_items_by_scan(&m, from, to);
6893                assert_eq!(
6894                    m.visible_items(from, to),
6895                    items,
6896                    "items {from}..{to} of {name}"
6897                );
6898                let utf16: usize = items
6899                    .iter()
6900                    .map(|(_, ch)| ch.map_or(1, char::len_utf16))
6901                    .sum();
6902                assert_eq!(
6903                    m.visible_utf16_len(from, to),
6904                    utf16,
6905                    "utf16 {from}..{to} of {name}"
6906                );
6907            }
6908            // And back: every UTF-16 index in the text resolves to the stop
6909            // that spells it, as the scan would have found it.
6910            let items = visible_items_by_scan(&m, 0, end);
6911            let mut seen = 0;
6912            for (src, ch) in &items {
6913                for u in seen..seen + ch.map_or(1, char::len_utf16) {
6914                    assert_eq!(
6915                        m.offset_at_visible_utf16(end, u),
6916                        Some(*src),
6917                        "index {u} of {name}"
6918                    );
6919                }
6920                seen += ch.map_or(1, char::len_utf16);
6921            }
6922            assert_eq!(
6923                m.offset_at_visible_utf16(end, seen),
6924                None,
6925                "past the end of {name}"
6926            );
6927        }
6928    }
6929
6930    #[test]
6931    fn visible_text_spends_exactly_one_character_on_every_stop() {
6932        // A list (whose items' ends no gap row follows), a table (whose cells'
6933        // ends draw a gutter space), and a code block (one row per line):
6934        // every place the text used to part company with the stop count, in
6935        // both directions. `UITextInput`'s tokenizer indexes this text by
6936        // that count, so the two must agree exactly between any two stops.
6937        let src = "- one\n- two\n\n| a | b |\n| - | - |\n| c | d |\n\n```\nx\ny\n```\n\nend\n";
6938        let m = map(src);
6939        let end = m.snap_to_stop(src.len());
6940        // The table's trailing stop draws no glyph, so it is spelled as a line
6941        // end too: to the system the table ends on a blank line, which is
6942        // where the caret past it stands.
6943        assert_eq!(m.visible_text(0, end), "one\ntwo\na\nb\nc\nd\n\nx\ny\nend");
6944        // Between any two stops, one character per hop.
6945        let first = m.snap_to_glyph_stop(0);
6946        let stops: Vec<usize> = std::iter::successors(Some(first), |&o| m.stop_after(o)).collect();
6947        for (i, &a) in stops.iter().enumerate() {
6948            for (j, &b) in stops.iter().enumerate().skip(i) {
6949                assert_eq!(
6950                    m.visible_text(a, b).chars().count(),
6951                    j - i,
6952                    "text between stops {a} and {b}"
6953                );
6954            }
6955        }
6956        // A cell's end is spelled as a line end, not the space it draws, so a
6957        // tap landing past `a`'s last letter has nothing to step over into `b`.
6958        let a_end = src.find("a |").unwrap() + 1;
6959        assert_eq!(m.visible_text(a_end, a_end + 1), "\n");
6960    }
6961
6962    #[test]
6963    fn unwrapped_mode_emits_one_row_per_paragraph() {
6964        // A long paragraph that would wrap under a column budget stays a single
6965        // row when wrap is None (the GUI wraps it at pixel width instead).
6966        let long = "one two three four five six seven eight nine ten eleven twelve\n";
6967        let mut ed = Editor::new_str(long, Format::Markdown).unwrap();
6968        let wrapped = build_t(&ed.nodes().unwrap(), long, Some(12));
6969        let unwrapped = build_t(&ed.nodes().unwrap(), long, None);
6970        assert!(wrapped.num_rows() > 1, "narrow column should wrap");
6971        assert_eq!(unwrapped.num_rows(), 1, "no budget should keep it one row");
6972        // Every glyph's source byte is preserved in the single row.
6973        let text: String = unwrapped.rows[0].glyphs.iter().map(|g| g.ch).collect();
6974        assert_eq!(text.trim_end(), long.trim_end());
6975    }
6976
6977    fn line_texts(m: &VisualMap) -> Vec<String> {
6978        m.rows
6979            .iter()
6980            .map(|r| {
6981                // Trim the trailing whitespace a row may carry — the zero-width
6982                // '\n' that closes a preserved line, and any space glyph left at
6983                // a wrap boundary (both real caret stops, neither visible text).
6984                r.glyphs
6985                    .iter()
6986                    .map(|g| g.ch)
6987                    .collect::<String>()
6988                    .trim_end()
6989                    .to_string()
6990            })
6991            .collect()
6992    }
6993
6994    #[test]
6995    fn preserve_lays_each_soft_break_on_its_own_row() {
6996        // A soft break (a bare newline inside a paragraph) folds into a space by
6997        // default — the whole paragraph is one reflowed row...
6998        let src = "one two\nthree four\n";
6999        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7000        let folded = build_t(&ed.nodes().unwrap(), src, None);
7001        assert_eq!(folded.num_rows(), 1, "fold: one reflowed row");
7002        assert_eq!(
7003            line_texts(&folded),
7004            vec!["one two three four"],
7005            "break folded to a space"
7006        );
7007
7008        // ...and under Preserve it renders where it was written, a row per line.
7009        let kept = map_preserve(src, None);
7010        assert_eq!(
7011            line_texts(&kept),
7012            vec!["one two", "three four"],
7013            "preserve: a row per line"
7014        );
7015    }
7016
7017    #[test]
7018    fn a_preserved_break_keeps_the_newline_offset_as_a_caret_stop() {
7019        // The break must leave a caret stop at the newline byte, or the caret
7020        // could not rest at the end of the first line. The '\n' glyph is dropped
7021        // from the row (so nothing stray renders); its offset (7 here) becomes the
7022        // row's end stop instead — the same offset the folded space would carry.
7023        let src = "one two\nthree four\n";
7024        let m = map_preserve(src, None);
7025        assert!(
7026            !m.rows[0].glyphs.iter().any(|g| g.ch == '\n'),
7027            "the break glyph is dropped"
7028        );
7029        assert_eq!(
7030            m.rows[0].end_src, 7,
7031            "the first row ends at the newline byte"
7032        );
7033        assert!(m.is_stop(7), "the newline offset is a caret stop");
7034        // Row end offsets stay strictly ascending — no two rows pin one offset.
7035        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
7036        assert!(
7037            offs.windows(2).all(|w| w[0] < w[1]),
7038            "offsets not unique: {offs:?}"
7039        );
7040    }
7041
7042    #[test]
7043    fn preserved_lines_wrap_independently() {
7044        // Each preserved line wraps to the column on its own; the break between
7045        // them is hard, so a word never crosses it — "gamma" and "delta" could
7046        // share a row on width alone but the soft break keeps them apart.
7047        let src = "alpha beta gamma\ndelta epsilon\n";
7048        let m = map_preserve(src, Some(12));
7049        assert_eq!(
7050            line_texts(&m),
7051            vec!["alpha beta", "gamma", "delta", "epsilon"],
7052            "each source line wraps on its own"
7053        );
7054    }
7055
7056    #[test]
7057    fn an_empty_paragraph_between_blocks_renders_its_own_rows() {
7058        // "A", then two blank lines (an empty paragraph opened with Enter), then
7059        // "B": the empty paragraph must be navigable rows, not collapsed onto B.
7060        // Rows: "A", spacer, empty-paragraph, spacer, "B" — each blank row a
7061        // distinct source offset.
7062        let m = map("A\n\n\n\nB\n");
7063        let text: Vec<String> = m
7064            .rows
7065            .iter()
7066            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7067            .collect();
7068        assert_eq!(text, vec!["A", "", "", "", "B"], "got {text:?}");
7069        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
7070        // Strictly ascending — no two rows share an offset (else the caret pins).
7071        assert!(
7072            offs.windows(2).all(|w| w[0] < w[1]),
7073            "offsets not unique: {offs:?}"
7074        );
7075    }
7076
7077    #[test]
7078    fn a_tight_block_boundary_still_gets_one_separator() {
7079        // A heading directly above text (no blank line between) keeps the single
7080        // conventional separator row, as before.
7081        let m = map("# H\ntext\n");
7082        let text: Vec<String> = m
7083            .rows
7084            .iter()
7085            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7086            .collect();
7087        assert_eq!(text, vec!["H", "", "text"], "got {text:?}");
7088    }
7089
7090    #[test]
7091    fn an_escaped_delimiter_renders_without_its_backslash_and_maps_true_offsets() {
7092        // `a\*b` renders the three visible chars `a * b` — the escape backslash
7093        // is hidden — and every glyph points at its real source byte, so a caret
7094        // past the escape lands right (the `*` at source 2, `b` at source 3, not
7095        // the drifted 1/2 the naive text-offset mapping gave).
7096        let m = map("a\\*b\n");
7097        let row: Vec<(char, usize)> = m.rows[0].glyphs.iter().map(|g| (g.ch, g.src)).collect();
7098        assert_eq!(row, vec![('a', 0), ('*', 2), ('b', 3)], "got {row:?}");
7099    }
7100
7101    #[test]
7102    fn an_escaped_hash_stays_a_paragraph_and_shows_the_hash() {
7103        // `\# hi` is a paragraph beginning with a literal `#`, not a heading —
7104        // the backslash is hidden, the `#` shown at its true offset.
7105        let m = map("\\# hi\n");
7106        let text: String = m.rows[0].glyphs.iter().map(|g| g.ch).collect();
7107        assert_eq!(text, "# hi");
7108        assert_eq!(
7109            m.rows[0].glyphs[0].src, 1,
7110            "the # is at source byte 1, past the \\"
7111        );
7112    }
7113
7114    #[test]
7115    fn a_tight_nested_list_hangs_its_sublist_directly_under_the_item() {
7116        // A list item's own text and the sub-list nested under it are written on
7117        // adjacent source lines, so the rich view butts them together — no
7118        // fabricated blank row. Regression: the synthetic "breathe" separator
7119        // used to open a gap between `• a` and its `  • b`.
7120        assert_eq!(rendered(&map("- a\n  - b\n")), "• a\n  • b");
7121    }
7122
7123    #[test]
7124    fn a_loose_nested_list_keeps_its_real_blank_line() {
7125        // A genuine blank source line (a loose list) still parts the item from
7126        // its sub-list — only the *fabricated* separator is suppressed, never a
7127        // real one the author typed. The gap row wears the item's continuation
7128        // prefix (the two-space indent), so it renders as "  ", not empty.
7129        assert_eq!(rendered(&map("- a\n\n  - b\n")), "• a\n  \n  • b");
7130    }
7131
7132    #[test]
7133    fn frontmatter_is_hidden_and_the_document_opens_into_its_content() {
7134        // Leading YAML frontmatter renders nothing — no phantom blank rows for
7135        // its lines, no leading gap — and `content_start` points at the first
7136        // real block so the caret floor can keep out of the hidden metadata.
7137        let fm = "---\nconfig: prov.yaml\ncontents:\n- '[Sample](sample.md)'\n---\n";
7138        let src = format!("{fm}# leaf\n\nA line.\n");
7139        let m = map(&src);
7140        let text = rendered(&m);
7141        assert!(
7142            !text.contains("config"),
7143            "frontmatter body leaked: {text:?}"
7144        );
7145        assert!(!text.contains("prov"), "frontmatter body leaked: {text:?}");
7146        assert_eq!(
7147            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7148            "leaf"
7149        );
7150        assert_eq!(
7151            m.content_start,
7152            fm.len(),
7153            "floor should be the first real block"
7154        );
7155    }
7156
7157    #[test]
7158    fn a_frontmatter_only_document_puts_the_floor_after_the_frontmatter() {
7159        // Nothing to render, so the caret floor is the end of the hidden
7160        // frontmatter — not 0, which is *before* the opening `---` and made the
7161        // first keystroke in a fresh metadata-only note land ahead of it. And
7162        // the frontmatter's own newlines are not trailing blank lines: they used
7163        // to open phantom rows at offsets 1..4, inside the metadata.
7164        let src = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
7165        let m = map(src);
7166        assert_eq!(m.content_start, src.len(), "floor must clear the metadata");
7167        assert!(
7168            m.rows.is_empty(),
7169            "frontmatter must render no rows: {:?}",
7170            rendered(&m)
7171        );
7172        assert!(
7173            m.stops.is_empty(),
7174            "no stop may sit inside the metadata: {:?}",
7175            m.stops
7176        );
7177    }
7178
7179    #[test]
7180    fn a_frontmatter_only_document_still_counts_its_real_blank_lines() {
7181        // Two blank lines after the frontmatter are the author's empty paragraph
7182        // and still render, counted from the metadata's end rather than from 0.
7183        let fm = "---\ntitle: n\n---\n";
7184        let m = map(&format!("{fm}\n\n"));
7185        assert_eq!(m.content_start, fm.len());
7186        assert_eq!(m.rows.len(), 2, "the two trailing newlines each open a row");
7187        assert!(
7188            m.rows.iter().all(|r| r.end_src > fm.len()),
7189            "rows must sit past the frontmatter"
7190        );
7191    }
7192
7193    #[test]
7194    fn a_document_without_frontmatter_has_a_zero_floor() {
7195        let m = map("# leaf\n\nbody\n");
7196        assert_eq!(m.content_start, 0);
7197    }
7198
7199    #[test]
7200    fn trailing_spaces_become_caret_stops_so_the_caret_can_be_drawn_past_them() {
7201        // Markdown/Djot drop the trailing space in `hello ` from the `str` node,
7202        // so without help the row would end at `hello` and the caret couldn't be
7203        // drawn past column 5 — typing a space at a line's end wouldn't move it
7204        // on screen until the next visible character reparsed the space into an
7205        // interior node. The builder recovers it from the block's span/content_span
7206        // gap and emits it as a real, caret-stoppable glyph.
7207        let m = map("hello \n");
7208        assert_eq!(
7209            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7210            "hello "
7211        );
7212        assert_eq!(
7213            m.rows[0].end_src, 6,
7214            "the row now ends past the trailing space"
7215        );
7216        // The caret can rest both on and past the space.
7217        assert_eq!(m.pos_of_offset(5), (0, 5), "between 'o' and the space");
7218        assert_eq!(m.pos_of_offset(6), (0, 6), "past the space");
7219        // Two trailing spaces, both stops.
7220        let m = map("hello  \n");
7221        assert_eq!(
7222            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7223            "hello  "
7224        );
7225        assert_eq!(m.pos_of_offset(7), (0, 7));
7226    }
7227
7228    #[test]
7229    fn a_headings_trailing_space_is_a_caret_stop_too() {
7230        // The hidden `# ` marker means `# hi ` renders as `hi ` in three columns;
7231        // the caret past the trailing space lands on the third.
7232        let m = map("# hi \n");
7233        assert_eq!(
7234            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7235            "hi "
7236        );
7237        assert_eq!(m.pos_of_offset(5), (0, 3));
7238    }
7239
7240    #[test]
7241    fn a_table_cells_trailing_padding_is_not_mistaken_for_block_trailing_space() {
7242        // A cell's own `span` is the whole row, so the trailing-whitespace
7243        // recovery must not run for cells or it would swallow the `│` delimiters
7244        // and neighbours between the cell text and the row's end. The grid stays
7245        // exactly as before.
7246        let text = rendered(&map(TABLE));
7247        assert!(
7248            text.contains("│ Pear │   3 │"),
7249            "cell padding disturbed:\n{text}"
7250        );
7251    }
7252
7253    #[test]
7254    fn a_click_below_the_last_row_lands_on_the_last_stop_not_offset_zero() {
7255        // A drag into the empty space under a short document used to resolve to
7256        // offset 0 — the wrong direction, and not even a caret stop when the
7257        // document opens on hidden frontmatter (its `content_start` floor is not
7258        // a stop), which crashed the caret invariant. It now lands on the last
7259        // stop: the end of the document, where dragging downward should reach.
7260        let fm = "---\ntitle: n\n---\n";
7261        let m = map(&format!("{fm}# Hi\n\nbody\n"));
7262        let below = m.num_rows() + 5;
7263        let off = m.offset_of_pos(below, 0);
7264        assert!(
7265            m.is_stop(off),
7266            "offset {off} from a below-content click is not a stop"
7267        );
7268        assert_eq!(
7269            off,
7270            m.stops.last().copied().unwrap(),
7271            "should be the document's last stop"
7272        );
7273        assert!(
7274            off > fm.len(),
7275            "must not fall onto the hidden frontmatter floor"
7276        );
7277    }
7278
7279    #[test]
7280    fn offset_of_pos_is_a_stop_for_every_row_including_past_the_end() {
7281        // The invariant the caret motion asserts: whatever cell a click names,
7282        // the offset it resolves to is one the caret can actually rest at.
7283        for src in [
7284            "hello \n",
7285            "# A heading here \n\nbody text goes on \n",
7286            "---\nk: v\n---\n# Title\n\nprose here that wraps a bit \n",
7287        ] {
7288            let m = map(src);
7289            for row in 0..m.num_rows() + 3 {
7290                for col in 0..30 {
7291                    let off = m.offset_of_pos(row, col);
7292                    assert!(
7293                        m.is_stop(off),
7294                        "row {row} col {col} → {off} is not a stop in {src:?}"
7295                    );
7296                }
7297            }
7298        }
7299    }
7300
7301    /// `| Name | Qty |` with Name left-aligned and Qty right-aligned.
7302    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
7303
7304    #[test]
7305    fn a_table_renders_as_an_aligned_grid() {
7306        let text = rendered(&map(TABLE));
7307        assert_eq!(
7308            text,
7309            "┌──────┬─────┐\n\
7310             │ Name │ Qty │\n\
7311             ├──────┼─────┤\n\
7312             │ Pear │   3 │\n\
7313             │ Fig  │  12 │\n\
7314             └──────┴─────┘",
7315            "got:\n{text}"
7316        );
7317    }
7318
7319    #[test]
7320    fn table_columns_honour_their_alignment() {
7321        // Centre and default(left) come straight from twig's cell.alignment —
7322        // the delimiter row it's spelled in is consumed and has no node.
7323        let text = rendered(&map("| A | Bee |\n| --- | :---: |\n| x | y |\n"));
7324        assert!(text.contains("│ x │  y  │"), "centred column: {text:?}");
7325    }
7326
7327    #[test]
7328    fn table_borders_are_decoration_the_caret_never_lands_on() {
7329        let m = map(TABLE);
7330        // The top and header rules are whole decoration rows.
7331        for r in [0, 2] {
7332            assert!(m.rows[r].decoration, "row {r} should be a decoration rule");
7333            assert!(
7334                !m.rows[r].glyphs.iter().any(|g| g.stop),
7335                "row {r} has a stop"
7336            );
7337        }
7338        // The bottom border is the exception: no glyph of it is a stop, but
7339        // its end is the table's trailing caret home — the one place the caret
7340        // can stand past the last cell.
7341        let bottom = &m.rows[5];
7342        assert!(
7343            !bottom.decoration,
7344            "the bottom border holds the trailing stop"
7345        );
7346        assert!(
7347            !bottom.glyphs.iter().any(|g| g.stop),
7348            "the bottom border's glyphs are not stops"
7349        );
7350        assert!(m.is_stop(bottom.end_src), "the trailing stop is a stop");
7351        assert!(m.table_end_stop(bottom.end_src));
7352        assert_eq!(
7353            bottom.end_src,
7354            TABLE.trim_end_matches('\n').len(),
7355            "the trailing stop is the table's own end, before its newline"
7356        );
7357        assert!(
7358            !m.table_end_stop(TABLE.rfind("12").unwrap() + 2),
7359            "a cell's end is not the trailing stop"
7360        );
7361        // A content row's `│` and padding are decoration; only the cell text
7362        // and each cell's one end-stop are stops.
7363        let header = &m.rows[1];
7364        assert!(!header.decoration);
7365        for g in &header.glyphs {
7366            if g.ch == '│' {
7367                assert!(!g.stop, "a border is not a caret stop");
7368            }
7369        }
7370        let stops: String = header
7371            .glyphs
7372            .iter()
7373            .filter(|g| g.stop)
7374            .map(|g| g.ch)
7375            .collect();
7376        assert_eq!(stops, "Name Qty ", "cell text plus one end-stop space each");
7377    }
7378
7379    #[test]
7380    fn a_cell_maps_to_its_own_source_text() {
7381        let m = map(TABLE);
7382        // "Pear" starts at byte 32 in TABLE; the caret there draws on the 'P'.
7383        let pear = TABLE.find("Pear").unwrap();
7384        let (r, c) = m.pos_of_offset(pear);
7385        assert_eq!(m.rows[r].glyphs[c].ch, 'P');
7386        assert_eq!(m.offset_of_pos(r, c), pear, "round trips");
7387    }
7388
7389    #[test]
7390    fn a_wide_table_is_cut_to_fit_and_its_cells_wrap() {
7391        // Columns wider than the surface used to run off the right edge, where
7392        // nothing could reach them. They're cut to the budget instead, and the
7393        // text wraps down inside the column — the header rule stays put, and
7394        // an alignment holds on every line of a wrapped cell, not just the first.
7395        let src = "| Ingredient | Notes |\n|---|---:|\n\
7396                   | flour milled coarse | sift it twice |\n| salt | a pinch |\n";
7397        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7398        let m = build_t(&ed.nodes().unwrap(), src, Some(30));
7399        let text = rendered(&m);
7400        assert_eq!(
7401            text,
7402            "┌──────────────┬─────────────┐\n\
7403             │ Ingredient   │       Notes │\n\
7404             ├──────────────┼─────────────┤\n\
7405             │ flour milled │     sift it │\n\
7406             │ coarse       │       twice │\n\
7407             │ salt         │     a pinch │\n\
7408             └──────────────┴─────────────┘",
7409            "got:\n{text}"
7410        );
7411        for (r, row) in m.rows.iter().enumerate() {
7412            assert!(
7413                row.glyphs.len() <= 30,
7414                "row {r} overflows: {}",
7415                row.glyphs.len()
7416            );
7417        }
7418    }
7419
7420    #[test]
7421    fn a_column_too_narrow_for_a_word_breaks_it_rather_than_spilling() {
7422        // A paragraph lets an overlong word trail off the end of the line; a
7423        // table column can't — a glyph past the border lands on the border.
7424        let src = "| A | B |\n|---|---|\n| antidisestablishmentarianism | x |\n";
7425        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7426        let m = build_t(&ed.nodes().unwrap(), src, Some(20));
7427        for (r, row) in m.rows.iter().enumerate() {
7428            assert!(
7429                row.glyphs.len() <= 20,
7430                "row {r} overflows: {}",
7431                row.glyphs.len()
7432            );
7433        }
7434        // Broken across lines, but whole: every letter is still drawn, at its
7435        // own source byte, where the caret can reach it.
7436        let word = "antidisestablishmentarianism";
7437        let at = src.find(word).unwrap();
7438        for (i, ch) in word.char_indices() {
7439            assert!(
7440                m.rows
7441                    .iter()
7442                    .flat_map(|r| r.glyphs.iter())
7443                    .any(|g| g.stop && g.src == at + i && g.ch == ch),
7444                "{ch:?} at {} was lost to the break",
7445                at + i
7446            );
7447        }
7448    }
7449
7450    #[test]
7451    fn a_code_block_maps_each_line_to_its_own_source_text() {
7452        // Every glyph used to point at the block's start, which made the whole
7453        // block one offset — visible, but impossible to put a caret inside.
7454        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
7455        let m = map(src);
7456        for row in &m.rows {
7457            for g in row.glyphs.iter().filter(|g| g.stop) {
7458                assert_eq!(
7459                    src[g.src..].chars().next(),
7460                    Some(g.ch),
7461                    "glyph {:?} at {} isn't the source byte it claims",
7462                    g.ch,
7463                    g.src
7464                );
7465            }
7466        }
7467    }
7468
7469    #[test]
7470    fn an_indented_code_block_maps_past_its_stripped_indent() {
7471        // twig strips the four-space indent, so `text` isn't a source slice and
7472        // the lines have to be re-found. Offsets land on the code, not the indent.
7473        let src = "    indented\n    code\n";
7474        let m = map(src);
7475        let stops: Vec<(char, usize)> = m
7476            .rows
7477            .iter()
7478            .flat_map(|r| r.glyphs.iter().filter(|g| g.stop).map(|g| (g.ch, g.src)))
7479            .collect();
7480        assert_eq!(
7481            stops[0],
7482            ('i', 4),
7483            "first line should start past the indent"
7484        );
7485        assert!(
7486            stops.contains(&('c', 17)),
7487            "second line misplaced: {stops:?}"
7488        );
7489    }
7490
7491    #[test]
7492    fn a_fenced_block_whose_code_echoes_its_info_string_maps_to_the_code() {
7493        // The one case that defeats a forward search: the opening fence
7494        // ```` ```rust ```` ends with the same text as the code under it.
7495        let src = "```rust\nrust\n```\n";
7496        let m = map(src);
7497        let first = m.rows[0].glyphs.iter().find(|g| g.stop).unwrap();
7498        assert_eq!(first.src, 8, "matched the info string, not the code");
7499    }
7500
7501    #[test]
7502    fn a_code_block_carries_no_gutter_and_is_published_as_a_row_span() {
7503        // The old `▏ ` gutter is gone: a code row is the block prefix (none, at
7504        // the top level) plus the code text, and the whole run is named in
7505        // `code_blocks` so a frontend can box it.
7506        let src = "para\n\n```\ncode\nlines\n```\n\nafter\n";
7507        let m = map(src);
7508        assert_eq!(m.code_blocks.len(), 1, "one code block");
7509        let span = m.code_blocks[0].rows_span.clone();
7510        let rows: Vec<String> = m.rows[span.clone()]
7511            .iter()
7512            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7513            .collect();
7514        assert_eq!(rows, vec!["code".to_string(), "lines".to_string()]);
7515        assert!(!rendered(&m).contains('▏'), "gutter still drawn");
7516        assert!(
7517            m.rows[span].iter().all(|r| r.code),
7518            "every row in the span is flagged code"
7519        );
7520    }
7521
7522    #[test]
7523    fn an_empty_last_line_in_a_code_block_is_a_row_of_its_own() {
7524        // `trim_end_matches('\n')` cut the block's terminator *and* the newline
7525        // that spells a trailing empty line, so the row the Return had just made
7526        // never appeared and the caret on it fell through to the block below.
7527        // Every empty line is a row, wherever in the block it falls.
7528        let src = "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n";
7529        let m = map(src);
7530        let span = m.code_blocks[0].rows_span.clone();
7531        let rows: Vec<String> = m.rows[span.clone()]
7532            .iter()
7533            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7534            .collect();
7535        assert_eq!(
7536            rows,
7537            vec!["alpha".to_string(), "beta".to_string(), String::new()],
7538            "the empty last line gets a row"
7539        );
7540        assert!(
7541            m.rows[span.clone()].iter().all(|r| r.code),
7542            "the empty row is flagged code like the rest of the block"
7543        );
7544        // And it is the *source's* empty line, not a coarse fallback to the
7545        // block start: the offset the caret resolves to is the one Return made.
7546        let empty = span.end - 1;
7547        assert_eq!(
7548            m.rows[empty].end_src,
7549            src.find("beta\n\n").unwrap() + "beta\n".len(),
7550            "the empty row maps to the line the Return opened"
7551        );
7552
7553        // Nothing is invented where there is no empty line, and a second one is
7554        // a second row.
7555        assert_eq!(
7556            map("```\nalpha\nbeta\n```\n").code_blocks[0]
7557                .rows_span
7558                .len(),
7559            2,
7560            "a block that ends at its last code line keeps two rows"
7561        );
7562        assert_eq!(
7563            map("```\nalpha\n\n\n```\n").code_blocks[0].rows_span.len(),
7564            3,
7565            "two trailing empty lines are two rows"
7566        );
7567    }
7568
7569    #[test]
7570    fn a_directive_container_is_tinted_and_labeled_on_its_first_row() {
7571        // diaryx's `:::vis{.public .family}` visibility block, and any other
7572        // `:::name{.class}` fenced div — core is agnostic of `name`.
7573        let src = ":::vis{.public .family}\nhello\n\nworld\n:::\nafter\n";
7574        let m = map_directives(src);
7575
7576        let content_rows: Vec<usize> = (0..m.rows.len()).filter(|&i| m.rows[i].directive).collect();
7577        assert!(!content_rows.is_empty(), "some row is flagged directive");
7578
7579        let after_rows: Vec<usize> = (0..m.rows.len())
7580            .filter(|&i| !content_rows.contains(&i) && !m.rows[i].glyphs.is_empty())
7581            .collect();
7582        assert!(
7583            after_rows.iter().all(|&i| !m.rows[i].directive),
7584            "content outside the fence isn't tinted"
7585        );
7586
7587        let labels: Vec<&str> = content_rows
7588            .iter()
7589            .filter_map(|&i| m.rows[i].directive_label.as_deref())
7590            .collect();
7591        assert_eq!(
7592            labels,
7593            vec!["public family"],
7594            "only the first row carries the label"
7595        );
7596
7597        assert_eq!(
7598            rendered(&m)
7599                .lines()
7600                .filter(|l| !l.is_empty())
7601                .collect::<Vec<_>>(),
7602            vec!["hello", "world", "after"],
7603            "fence markers don't leak into the rendered text"
7604        );
7605    }
7606
7607    #[test]
7608    fn a_bare_word_directive_is_labeled_same_as_dot_classes() {
7609        // diaryx_core::visibility's own `:::vis{public family}` — no leading
7610        // dots — is what apps/web's directive serializer and the native
7611        // publish-time filter both actually write today, distinct from twig's
7612        // `.class` convention. Both must label the same way so every existing
7613        // diaryx `:::vis{...}` block reads, not just newly dot-authored ones.
7614        let src = ":::vis{public family}\nhello\n:::\n";
7615        let m = map_directives(src);
7616        let label = m.rows.iter().find_map(|r| r.directive_label.clone());
7617        assert_eq!(label.as_deref(), Some("public family"));
7618    }
7619
7620    #[test]
7621    fn a_text_directive_keeps_its_paragraph_visible() {
7622        // Regression: an inline `:name[label]{…}` used to make its paragraph
7623        // fail the "all children inline" test, so the whole line was walked as
7624        // a container of blocks and rendered as empty rows with NO caret stops —
7625        // the text vanished from the editor and the caret couldn't enter it.
7626        // diaryx's inline `:vis[…]` is exactly this shape.
7627        let src = "Text with :abbr[HTML]{title=\"HyperText\"} inline.\n";
7628        let m = map_directives(src);
7629        assert_eq!(rendered(&m).trim_end(), "Text with HTML inline.");
7630        // Every character of the line is a caret home, markup excluded — the
7631        // label reads as ordinary text, the way a link's does.
7632        let stops: usize = m
7633            .rows
7634            .iter()
7635            .map(|r| r.glyphs.iter().filter(|g| g.stop).count())
7636            .sum();
7637        assert_eq!(stops, "Text with HTML inline.".chars().count());
7638        // It is inline, so it is not the container form's tinted panel.
7639        assert!(m.rows.iter().all(|r| !r.directive));
7640    }
7641
7642    #[test]
7643    fn a_text_directives_label_maps_to_its_true_source_bytes() {
7644        // Regression (needs twig-doc >= 2.5.0): twig parses a `[label]` as a
7645        // detached slice, and until it rebased the enclosing scan's segments
7646        // onto it every node inside the label reported a span of `(0,0)`. Read
7647        // by anything that trusts a span that means "byte 0", so the label's
7648        // glyphs mapped to the START OF THE DOCUMENT — a click on the label put
7649        // the caret at the top of the file, its stops collided with the real
7650        // first line's, and an edit there landed on the wrong bytes entirely.
7651        //
7652        // The sibling test `a_text_directive_keeps_its_paragraph_visible` only
7653        // counts stops, which is exactly why this went unnoticed: the right
7654        // NUMBER of stops at completely wrong offsets.
7655        let src = "x :abbr[HTML]{title=\"y\"} z\n";
7656        let m = map_directives(src);
7657        let stops: Vec<(char, usize)> = m
7658            .rows
7659            .iter()
7660            .flat_map(|r| &r.glyphs)
7661            .filter(|g| g.stop)
7662            .map(|g| (g.ch, g.src))
7663            .collect();
7664        // `HTML` sits at 8..12. The name, brackets and `{…}` are hidden markup
7665        // the caret steps over, so the line's stops run 0, 1, 8..12, then 24.
7666        assert_eq!(
7667            stops,
7668            [
7669                ('x', 0),
7670                (' ', 1),
7671                ('H', 8),
7672                ('T', 9),
7673                ('M', 10),
7674                ('L', 11),
7675                (' ', 24),
7676                ('z', 25)
7677            ]
7678        );
7679    }
7680
7681    #[test]
7682    fn every_glyph_in_a_directive_label_points_at_its_source_byte() {
7683        // The `every_glyph_points_at_its_source_byte` invariant, extended over
7684        // directive labels now that their offsets are real. Nested markup is
7685        // included: its delimiters are hidden, so the visible glyphs must skip
7686        // them and still name their own bytes.
7687        let src = "x :abbr[a *b* c] y and :vis[family only] z\n";
7688        let m = map_directives(src);
7689        for g in m.rows.iter().flat_map(|r| &r.glyphs).filter(|g| g.stop) {
7690            let at = src[g.src..].chars().next();
7691            assert_eq!(
7692                at,
7693                Some(g.ch),
7694                "glyph {:?} claims byte {}, which is {at:?}",
7695                g.ch,
7696                g.src
7697            );
7698        }
7699        assert_eq!(rendered(&m).trim_end(), "x a b c y and family only z");
7700    }
7701
7702    #[test]
7703    fn a_directive_labels_nested_emphasis_keeps_both_its_style_and_its_offsets() {
7704        let src = "x :abbr[a *b* c] y\n";
7705        let m = map_directives(src);
7706        let b = m
7707            .rows
7708            .iter()
7709            .flat_map(|r| &r.glyphs)
7710            .find(|g| g.ch == 'b')
7711            .expect("the emphasised char");
7712        assert!(b.style.italic, "the label's *b* lost its emphasis");
7713        assert_eq!(b.src, 11, "the label's *b* lost its source byte");
7714    }
7715
7716    #[test]
7717    fn a_bare_colon_word_renders_as_the_prose_it_almost_always_is() {
7718        // Regression: twig matches a colon followed by any letter-led word, so
7719        // ordinary prose is full of "text directives" nobody meant to write.
7720        // With no `[label]` there are no children, and the arm recursed into
7721        // them — rendering *nothing*. The word vanished from the document with
7722        // no caret stop left behind, so it could not even be deleted.
7723        for src in ["a :word b\n", "note :see below\n", ":smile: hi\n"] {
7724            let m = map_directives(src);
7725            assert_eq!(
7726                rendered(&m).trim_end(),
7727                src.trim_end(),
7728                "prose was eaten: {src:?}"
7729            );
7730        }
7731    }
7732
7733    #[test]
7734    fn a_bare_colon_word_keeps_every_byte_a_caret_stop() {
7735        let src = "a :word b\n";
7736        let m = map_directives(src);
7737        // Nothing here is markup, so nothing is hidden: each byte maps to
7738        // itself and can be stood on, which is what makes the colon deletable.
7739        let stops: Vec<(char, usize)> = m
7740            .rows
7741            .iter()
7742            .flat_map(|r| &r.glyphs)
7743            .filter(|g| g.stop)
7744            .map(|g| (g.ch, g.src))
7745            .collect();
7746        assert_eq!(
7747            stops,
7748            "a :word b"
7749                .chars()
7750                .enumerate()
7751                .map(|(i, c)| (c, i))
7752                .collect::<Vec<_>>()
7753        );
7754    }
7755
7756    #[test]
7757    fn an_attribute_bearing_text_directive_draws_a_chip() {
7758        // `{…}` is deliberate in a way a bare colon is not — diaryx writes
7759        // `:vis{.family}` inline — so this one reads as an embed, on the same
7760        // `⧉ label` recipe the leaf form's placeholder row uses.
7761        // Both attribute conventions label it: twig's dot-prefixed classes and
7762        // the bare pandoc-style words diaryx also writes.
7763        for src in ["a :vis{.family} b\n", "a :vis{family} b\n"] {
7764            let m = map_directives(src);
7765            assert_eq!(rendered(&m).trim_end(), "a ⧉ vis family b", "{src:?}");
7766        }
7767        // A `key=value` attr is configuration, not a name, so it adds nothing.
7768        let m = map_directives("a :foo{title=\"x\"} b\n");
7769        assert_eq!(rendered(&m).trim_end(), "a ⧉ foo b");
7770    }
7771
7772    #[test]
7773    fn a_directive_chip_is_one_atomic_caret_stop_at_its_own_offset() {
7774        let src = "a :vis{.family} b\n";
7775        let m = map_directives(src);
7776        let stops: Vec<usize> = m
7777            .rows
7778            .iter()
7779            .flat_map(|r| &r.glyphs)
7780            .filter(|g| g.stop)
7781            .map(|g| g.src)
7782            .collect();
7783        // The chip contributes exactly one stop, at the directive's start (2),
7784        // so the caret steps over it whole instead of walking hidden markup a
7785        // byte at a time. `{.family}`'s bytes (3..15) are never stood on.
7786        assert_eq!(stops, [0, 1, 2, 15, 16]);
7787    }
7788
7789    #[test]
7790    fn a_paragraph_holding_only_a_chip_is_still_navigable() {
7791        // With no stop of its own the row would be unreachable — the caret
7792        // could never be put on the line to edit or delete the directive.
7793        let m = map_directives(":vis{.family}\n");
7794        assert!(
7795            m.row_is_navigable(0),
7796            "a chip-only paragraph has no caret home"
7797        );
7798        assert_eq!(
7799            m.offset_of_pos(0, 0),
7800            0,
7801            "its caret home isn't the directive's start"
7802        );
7803    }
7804
7805    #[test]
7806    fn a_ratio_or_a_clock_time_is_never_a_directive() {
7807        // twig requires a letter after the colon, so these stay prose — the
7808        // verbatim arm must not be reached for them at all.
7809        let src = "ratio 3:4 and 10:30\n";
7810        assert_eq!(
7811            rendered(&map_directives(src)).trim_end(),
7812            "ratio 3:4 and 10:30"
7813        );
7814    }
7815
7816    #[test]
7817    fn a_leaf_directive_is_a_placeholder_row_with_its_attrs_published() {
7818        // `::name{…}` is a standalone block with no body — an embed, a table of
7819        // contents. It used to emit no rows at all: invisible, no caret home,
7820        // vertical motion crossing a void. Now it draws the image recipe's
7821        // placeholder and publishes what the host app needs to paint the real
7822        // thing.
7823        let src = "before\n\n::embed{src=\"demo.html\" height=\"400\"}\n\nafter\n";
7824        let m = map_directives(src);
7825
7826        let row = m
7827            .rows
7828            .iter()
7829            .position(|r| r.leaf_directive.is_some())
7830            .expect("a placeholder row");
7831        assert_eq!(
7832            m.rows[row].glyphs.iter().map(|g| g.ch).collect::<String>(),
7833            "⧉ embed"
7834        );
7835        assert!(
7836            m.rows[row].glyphs.iter().any(|g| g.stop),
7837            "the caret can land on it"
7838        );
7839        assert!(
7840            m.rows[row].directive,
7841            "a frontend frames it like the container form"
7842        );
7843
7844        assert_eq!(m.directives.len(), 1);
7845        let info = &m.directives[0];
7846        assert_eq!(info.name, "embed");
7847        assert_eq!(info.rows_span, row..row + 1);
7848        assert_eq!(info.attr("src"), Some("demo.html"));
7849        assert_eq!(info.attr("height"), Some("400"));
7850        assert_eq!(info.attr("nope"), None);
7851        // The prose around it is untouched.
7852        assert!(rendered(&m).contains("before") && rendered(&m).contains("after"));
7853    }
7854
7855    #[test]
7856    fn a_leaf_directive_shows_its_label_and_honours_its_prefix() {
7857        // A `[label]` names the placeholder (the way an image's alt does), and a
7858        // quoted directive keeps the quote's gutter — it is a block like any
7859        // other, not a special case that escapes its container.
7860        let m = map_directives("::embed[Audience demo]{src=\"demo.html\"}\n");
7861        assert_eq!(rendered(&m).trim_end(), "⧉ Audience demo");
7862        assert_eq!(m.directives[0].label, "Audience demo");
7863
7864        let quoted = map_directives("> ::embed{src=\"x.html\"}\n");
7865        assert_eq!(rendered(&quoted).trim_end(), "│ ⧉ embed");
7866        assert_eq!(quoted.directives[0].name, "embed");
7867    }
7868
7869    #[test]
7870    fn a_container_directive_is_still_a_panel_not_a_placeholder() {
7871        // The three forms must not bleed into each other: only the leaf form is
7872        // a placeholder, and only the container form tints the blocks it wraps.
7873        let m = map_directives(":::note{.warning}\nBody\n:::\n");
7874        assert!(
7875            m.directives.is_empty(),
7876            "a container publishes no placeholder"
7877        );
7878        assert!(m.rows.iter().all(|r| r.leaf_directive.is_none()));
7879        assert_eq!(rendered(&m).trim_end(), "Body");
7880        assert!(
7881            m.rows
7882                .iter()
7883                .any(|r| r.directive && r.directive_label.as_deref() == Some("warning"))
7884        );
7885    }
7886
7887    /// A production-path build with both extensions on — the only way to put a
7888    /// promoted HTML element and a directive in one document, which is what the
7889    /// `container` kind made necessary to tell apart. Returns the whole `Doc`
7890    /// because [`VisualMap`] is not `Clone`; read `doc.vmap`.
7891    fn doc_built(src: &str) -> crate::Doc {
7892        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
7893        doc.build_visual(80);
7894        doc
7895    }
7896
7897    /// Every `container` node in `src`, parsed the way production does (both
7898    /// extensions on), paired with what [`container_is_directive`] makes of it.
7899    fn containers(src: &str) -> Vec<(String, bool, Option<DirectiveForm>)> {
7900        let mut ed = Editor::new_ext(
7901            src.as_bytes(),
7902            Format::Markdown,
7903            twig::MarkdownExtensions {
7904                directives: true,
7905                html_elements: true,
7906                ..Default::default()
7907            },
7908        )
7909        .unwrap();
7910        ed.nodes()
7911            .unwrap()
7912            .iter()
7913            .filter(|n| n.kind == Kind::Container)
7914            .map(|n| {
7915                (
7916                    n.name.clone().unwrap_or_default(),
7917                    container_is_directive(n),
7918                    n.directive_form,
7919                )
7920            })
7921            .collect()
7922    }
7923
7924    #[test]
7925    fn a_directive_and_an_html_element_are_told_apart_by_spelling_not_by_form() {
7926        // twig 2.8 folded `div`/`span`/`directive`/`element` into one `container`
7927        // kind. `directive_form` reads as though it separates them and does not:
7928        // a block-level `<div>` reports `Some(DirectiveForm::Container)` exactly
7929        // as a `:::note` does. Trusting it would draw directive chrome — a tinted
7930        // panel, a `.class` audience label — on every pasted Slack/Docs div.
7931        for (src, name, want) in [
7932            (":::note{.a}\nbody\n:::\n", "note", true),
7933            ("::embed{src=x}\n", "embed", true),
7934            ("a :vis[hi]{.b} b\n", "vis", true),
7935            ("<div class=\"x\">\nhi\n</div>\n", "div", false),
7936            ("<video src=\"v.mp4\" controls></video>\n", "video", false),
7937            ("<audio src=\"a.mp3\" controls></audio>\n", "audio", false),
7938            ("<figure>\n\nhi\n\n</figure>\n", "figure", false),
7939            // The `:` in an attribute must not read as a directive opener: the
7940            // `<` of the tag comes first, and first one wins.
7941            (
7942                "<video src=\"http://x.test/v.mp4\" controls></video>\n",
7943                "video",
7944                false,
7945            ),
7946            (
7947                "<source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\n",
7948                "source",
7949                false,
7950            ),
7951        ] {
7952            let found = containers(src);
7953            let hit = found.iter().find(|(n, ..)| n == name);
7954            let Some((_, is_directive, form)) = hit else {
7955                panic!("no `{name}` container in {src:?} — found {found:?}");
7956            };
7957            assert_eq!(*is_directive, want, "{name} in {src:?} (form was {form:?})");
7958        }
7959
7960        // And the reason this can't just read the field: for the one collision
7961        // that matters, the field says the same thing for both.
7962        let div = containers("<div class=\"x\">\nhi\n</div>\n");
7963        let note = containers(":::note{.a}\nbody\n:::\n");
7964        assert_eq!(
7965            div[0].2, note[0].2,
7966            "if these ever differ, `directive_form` became usable and this rule can go"
7967        );
7968    }
7969
7970    #[test]
7971    fn a_directive_nested_in_a_quote_or_list_is_still_a_directive() {
7972        // A container's span opens with its *block prefix*, not its own markup —
7973        // `> ::embed{…}` starts at the `>`. Reading only the first byte to tell a
7974        // directive from an element (both `container` since 2.8) therefore misses
7975        // every nested one, and the placeholder silently renders as nothing.
7976        for (src, ctx) in [
7977            ("> ::embed{src=\"x\"}\n", "quoted"),
7978            ("- ::embed{src=\"x\"}\n", "listed"),
7979            (">> ::embed{src=\"x\"}\n", "twice quoted"),
7980        ] {
7981            let m = map_directives(src);
7982            assert_eq!(m.directives.len(), 1, "{ctx} directive was lost");
7983            assert_eq!(m.directives[0].name, "embed", "{ctx}");
7984        }
7985    }
7986
7987    #[test]
7988    fn a_video_is_still_media_and_not_a_directive() {
7989        // The other side of the same coin: `<video>` is a `container` too, and
7990        // must reach `block_media` rather than the directive arms.
7991        let doc = doc_built("<video src=\"clip.mp4\" controls></video>\n");
7992        assert_eq!(doc.vmap.media.len(), 1, "the video is block media");
7993        assert!(
7994            doc.vmap.rows.iter().all(|r| !r.directive),
7995            "the video drew directive chrome"
7996        );
7997    }
7998
7999    #[test]
8000    fn a_directive_needs_the_extension_flag() {
8001        // `map` (twig's default extensions) leaves `directives` off — the fence
8002        // renders as literal paragraph text, same as any other unrecognized
8003        // punctuation, never corrupting or panicking.
8004        let src = ":::vis{.public}\nhello\n:::\n";
8005        let m = map(src);
8006        assert!(m.rows.iter().all(|r| !r.directive));
8007        assert!(rendered(&m).contains(":::vis{.public}"));
8008    }
8009
8010    #[test]
8011    fn a_footnote_reference_keeps_its_paragraph_visible() {
8012        // Regression: `footnote_reference` was in neither `is_inline_kind` nor
8013        // the inline walker, so a paragraph carrying one failed the "all children
8014        // inline" test, was walked as a container of blocks, and rendered as
8015        // empty rows with no caret stop anywhere — the whole line vanished.
8016        let src = "A claim[^1] and more.\n";
8017        let m = map(src);
8018        assert_eq!(rendered(&m).trim_end(), "A claim[1] and more.");
8019        // The `^` is spelling, not text: hidden the way a link's `](dest)` is.
8020        assert!(!rendered(&m).contains('^'));
8021    }
8022
8023    #[test]
8024    fn a_footnote_reference_is_raised_and_the_prose_around_it_is_not() {
8025        // What makes `[1]` read as a reference rather than as bracketed text.
8026        // The brackets ride with the label: the chip is one raised mark.
8027        let m = map("A claim[^1] and more.\n");
8028        assert_eq!(baselines_of(&m, '1'), vec![Baseline::Super]);
8029        assert_eq!(baselines_of(&m, '['), vec![Baseline::Super]);
8030        assert_eq!(baselines_of(&m, ']'), vec![Baseline::Super]);
8031        assert_eq!(baselines_of(&m, 'A'), vec![Baseline::Normal]);
8032    }
8033
8034    #[test]
8035    fn a_footnote_reference_keeps_the_link_role_it_had() {
8036        // The raised baseline is added to the role, not swapped for it: every
8037        // frontend already paints `Role::Link`, and a reference is one.
8038        let m = map("A claim[^1].\n");
8039        let label = m
8040            .rows
8041            .iter()
8042            .flat_map(|r| &r.glyphs)
8043            .find(|g| g.ch == '1')
8044            .unwrap();
8045        assert_eq!(label.style.role, Role::Link);
8046        assert_eq!(label.style.baseline, Baseline::Super);
8047    }
8048
8049    /// The [`Role`] of the first glyph spelling `ch` — how a test reads one
8050    /// run's styling off a map without caring which row it landed on.
8051    fn role_of(m: &VisualMap, ch: char) -> Role {
8052        m.rows
8053            .iter()
8054            .flat_map(|r| r.glyphs.iter())
8055            .find(|g| g.ch == ch)
8056            .unwrap_or_else(|| panic!("no glyph spelling {ch:?}"))
8057            .style
8058            .role
8059    }
8060
8061    #[test]
8062    fn a_markdown_highlight_is_a_mark_and_a_coloured_one_names_its_colour() {
8063        // twig 3.3's `highlight`/`highlight_colors`, which `parse_extensions`
8064        // turns on for every leaf document: `==text==` is a `mark` in Markdown
8065        // and not the literal `==` it used to be, and `==🔴 text==` is one
8066        // carrying a colour.
8067        //
8068        // `doc_built` rather than `map`, deliberately — the extensions are
8069        // leaf's choice, not twig's default, so a test that parsed bare
8070        // Markdown here would be testing a document leaf never builds.
8071        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
8072        assert_eq!(role_of(&doc.vmap, 'y'), Role::Mark(None));
8073        assert_eq!(
8074            role_of(&doc.vmap, 'r'),
8075            Role::Mark(Some(MarkColor::Red)),
8076            "the `data-color` twig stripped the emoji into"
8077        );
8078        assert_eq!(role_of(&doc.vmap, 'P'), Role::Body);
8079    }
8080
8081    #[test]
8082    fn the_emoji_that_named_a_highlight_is_markup_and_never_drawn() {
8083        // The colour is *spelling*: twig strips the emoji out of the mark's
8084        // content, so the reader sees the words and the wash, never the circle.
8085        // Drawing it would put a character in the rendered text that the author
8086        // wrote as syntax — the same mistake as drawing an emphasis's `*`.
8087        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
8088        let drawn: String = doc.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
8089        assert_eq!(drawn, "Plain yes and red ok");
8090    }
8091
8092    #[test]
8093    fn a_superscript_and_a_subscript_sit_off_the_baseline() {
8094        // Regression: both rendered flat, so the toolbar's superscript button
8095        // produced markup that looked exactly like the text around it.
8096        let m = map_djot("H~2~O and x^2^\n");
8097        assert_eq!(baselines_of(&m, '2'), vec![Baseline::Sub, Baseline::Super]);
8098        assert_eq!(baselines_of(&m, 'H'), vec![Baseline::Normal]);
8099        assert_eq!(baselines_of(&m, 'O'), vec![Baseline::Normal]);
8100    }
8101
8102    #[test]
8103    fn a_raised_glyph_keeps_the_style_it_was_raised_out_of() {
8104        // Why this is a `Baseline` and not a `Role`: raising a glyph says where
8105        // it sits, and must not cost it what it already was.
8106        let m = map_djot("# Heading x^2^\n");
8107        let two = m
8108            .rows
8109            .iter()
8110            .flat_map(|r| &r.glyphs)
8111            .find(|g| g.ch == '2')
8112            .unwrap();
8113        assert_eq!(two.style.baseline, Baseline::Super);
8114        assert_eq!(two.style.role, Role::Heading(1), "still heading text");
8115    }
8116
8117    #[test]
8118    fn a_footnote_references_brackets_are_decoration_and_only_its_label_is_a_stop() {
8119        let src = "see[^note] here\n";
8120        let m = map(src);
8121        // `[^note]` spans 3..10, its label `note` 5..9. The caret walks the
8122        // label; the brackets are drawn but never stood on, as a table's are,
8123        // and the `[^`/`]` bytes are stepped over like any hidden delimiter.
8124        let stops: Vec<usize> = m
8125            .rows
8126            .iter()
8127            .flat_map(|r| &r.glyphs)
8128            .filter(|g| g.stop)
8129            .map(|g| g.src)
8130            .collect();
8131        for off in 5..9 {
8132            assert!(
8133                stops.contains(&off),
8134                "label byte {off} isn't a caret stop: {stops:?}"
8135            );
8136        }
8137        for off in [3usize, 4, 9] {
8138            assert!(
8139                !stops.contains(&off),
8140                "delimiter byte {off} is a caret stop: {stops:?}"
8141            );
8142        }
8143    }
8144
8145    #[test]
8146    fn a_task_item_draws_its_box_where_the_bullet_would_be() {
8147        // Regression: the `[ ] ` is markup twig consumes — the item's paragraph
8148        // content starts past it — so a task item used to render as `• todo`,
8149        // identical to a plain bullet and with no way to see it was ticked.
8150        let m = map("- [ ] todo\n- [x] done\n- plain\n");
8151        assert_eq!(rendered(&m), "☐ todo\n☑ done\n• plain");
8152
8153        // The tick rides the item's first row, for a GUI that paints its own box.
8154        let ticks: Vec<Option<bool>> = m.rows.iter().map(|r| r.task).collect();
8155        assert_eq!(ticks, [Some(false), Some(true), None]);
8156    }
8157
8158    #[test]
8159    fn a_task_items_box_survives_a_wrap_and_marks_only_the_first_row() {
8160        let m = map_at(
8161            "- [x] a much longer task that has to wrap somewhere\n",
8162            Some(20),
8163        );
8164        assert!(m.rows.len() > 1, "the item should wrap: {:?}", rendered(&m));
8165        assert_eq!(m.rows[0].task, Some(true));
8166        assert!(
8167            m.rows[1..].iter().all(|r| r.task.is_none()),
8168            "only the first row"
8169        );
8170        // The continuation lines hang under the box, not under column zero.
8171        assert!(
8172            rendered(&m)
8173                .lines()
8174                .nth(1)
8175                .is_some_and(|l| l.starts_with("  "))
8176        );
8177    }
8178
8179    #[test]
8180    fn a_bracket_in_an_items_prose_is_not_a_checkbox() {
8181        // `task_checked` finds the box past the list marker; a plain item whose
8182        // text merely contains a bracket has none, and must keep its bullet.
8183        let m = map("- see [1] below\n");
8184        assert_eq!(rendered(&m), "• see [1] below");
8185        assert_eq!(m.rows[0].task, None);
8186    }
8187
8188    #[test]
8189    fn a_footnote_definition_renders_where_it_was_written() {
8190        // Regression: twig parses `[^1]: …` as a root *beside* `doc` — not a
8191        // child of it — so the walk from `doc` never reached one and every byte
8192        // of the note's body rendered as nothing at all.
8193        let src = "A claim[^1].\n\n[^1]: The note body.\n\nAfter.\n";
8194        let m = map(src);
8195        let text = rendered(&m);
8196        assert!(
8197            text.contains("The note body."),
8198            "the note body is invisible: {text:?}"
8199        );
8200        // In source order — between the paragraph that cites it and the one
8201        // after — not hoisted to the end, and marked to match its reference.
8202        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
8203        assert_eq!(lines, ["A claim[1].", "[1] The note body.", "After."]);
8204    }
8205
8206    #[test]
8207    fn a_footnote_definitions_body_maps_to_its_own_source_bytes() {
8208        let src = "x[^a].\n\n[^a]: body\n";
8209        let m = map(src);
8210        // `body` sits at 14..18. Its glyphs must map there — a marker that ate
8211        // the offsets would put the caret in the wrong place on every click.
8212        let body: Vec<(char, usize)> = m
8213            .rows
8214            .iter()
8215            .flat_map(|r| &r.glyphs)
8216            .filter(|g| g.stop && g.src >= 14)
8217            .map(|g| (g.ch, g.src))
8218            .collect();
8219        assert_eq!(body, [('b', 14), ('o', 15), ('d', 16), ('y', 17)]);
8220    }
8221
8222    #[test]
8223    fn an_empty_footnote_definition_still_shows_its_marker() {
8224        // The instant `[^1]: ` has been typed and nothing after it. `blocks`
8225        // renders no child, so without the explicit marker row the definition
8226        // wouldn't appear at all until something was typed into it.
8227        let src = "x[^1]\n\n[^1]:\n";
8228        let m = map(src);
8229        assert!(
8230            rendered(&m).contains("[1] "),
8231            "no marker row: {:?}",
8232            rendered(&m)
8233        );
8234    }
8235
8236    #[test]
8237    fn a_footnote_definition_wearing_a_long_label_indents_its_wrapped_body() {
8238        let src = "x[^src]\n\n[^src]: one two three four five six seven\n";
8239        let m = map_at(src, Some(24));
8240        let text = rendered(&m);
8241        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
8242        // Continuation lines hang under the marker, as a list item's do — the
8243        // indent is the marker's own width, not a fixed one.
8244        assert_eq!(lines[1].trim_end(), "[src] one two three four");
8245        assert!(
8246            lines[2].starts_with("      "),
8247            "body doesn't hang: {:?}",
8248            lines[2]
8249        );
8250        assert_eq!(lines[2].trim(), "five six seven");
8251    }
8252
8253    #[test]
8254    fn a_code_block_leaves_exactly_one_blank_row_below_it() {
8255        // The closing fence line used to be miscounted as a blank separator,
8256        // opening a phantom second gap under the block. One block boundary is
8257        // one blank row, code block or not.
8258        let src = "para\n\n```\ncode\n```\n\nafter\n";
8259        let m = map(src);
8260        let code_end = m.code_blocks[0].rows_span.end;
8261        let after = m
8262            .rows
8263            .iter()
8264            .position(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "after")
8265            .unwrap();
8266        assert_eq!(
8267            after - code_end,
8268            1,
8269            "exactly one row between code and 'after'"
8270        );
8271    }
8272
8273    #[test]
8274    fn a_fenced_block_publishes_its_language_on_its_code_block() {
8275        // The info string becomes the block's label; a bare fence and an indented
8276        // block carry none.
8277        assert_eq!(
8278            map("```rust\nlet x = 1;\n```\n").code_blocks[0]
8279                .lang
8280                .as_deref(),
8281            Some("rust")
8282        );
8283        assert_eq!(map("```\nplain\n```\n").code_blocks[0].lang, None);
8284        assert_eq!(map("    indented\n").code_blocks[0].lang, None);
8285    }
8286
8287    fn lang_of(src: &str) -> Option<String> {
8288        map(src).code_blocks[0].lang.clone()
8289    }
8290
8291    #[test]
8292    fn a_fence_in_a_quote_has_its_language() {
8293        // The block's span starts at the line, `> ` and all; the fence is past
8294        // the quote marker, and so is its info string.
8295        let src = "> ```rust\n> let x = 1;\n> ```\n";
8296        assert_eq!(lang_of(src).as_deref(), Some("rust"));
8297        let info = code_info_span(src, 0).unwrap();
8298        assert_eq!(&src[info], "rust", "the info string's exact bytes");
8299        assert_eq!(
8300            lang_of("> > ~~~ py\n> > x\n> > ~~~\n").as_deref(),
8301            Some("py")
8302        );
8303    }
8304
8305    #[test]
8306    fn a_fence_in_a_list_item_has_its_language() {
8307        // On the item's own line, past its marker…
8308        assert_eq!(
8309            lang_of("- ```rust\n  let x = 1;\n  ```\n").as_deref(),
8310            Some("rust")
8311        );
8312        assert_eq!(
8313            lang_of("10. ```rust\n    let x = 1;\n    ```\n").as_deref(),
8314            Some("rust")
8315        );
8316        // …and on a line of its own inside the item, where the indent is the
8317        // item's content column and not the fence's.
8318        assert_eq!(
8319            lang_of("10. a\n\n    ```rust\n    let x = 1;\n    ```\n").as_deref(),
8320            Some("rust")
8321        );
8322        assert_eq!(
8323            lang_of("- a\n  - b\n\n    ```rust\n    x\n    ```\n").as_deref(),
8324            Some("rust")
8325        );
8326        // In a list in a quote.
8327        assert_eq!(
8328            lang_of("> - a\n>\n>   ```rust\n>   x\n>   ```\n").as_deref(),
8329            Some("rust")
8330        );
8331    }
8332
8333    #[test]
8334    fn an_indented_block_in_a_list_item_still_has_no_language() {
8335        // Four spaces past the item's content column is an indented code
8336        // block, whatever its text looks like — the allowance is measured from
8337        // the item, not dropped.
8338        let src = "- a\n\n      ```rust\n";
8339        assert_eq!(map(src).code_blocks.len(), 1);
8340        assert_eq!(lang_of(src), None);
8341        assert_eq!(lang_of("- a\n\n      indented\n"), None);
8342    }
8343
8344    /// The token every glyph spelling `ch` carries, in row order — how a test
8345    /// reads a block's highlighting off the map.
8346    fn tokens_of(m: &VisualMap, ch: char) -> Vec<Option<Token>> {
8347        m.rows
8348            .iter()
8349            .flat_map(|r| r.glyphs.iter())
8350            .filter(|g| g.ch == ch)
8351            .map(|g| g.style.token)
8352            .collect()
8353    }
8354
8355    #[cfg(feature = "syntax")]
8356    #[test]
8357    fn a_fenced_block_in_a_known_language_carries_tokens() {
8358        // `let` is a keyword, the string literal a string, and the plain
8359        // identifier `x` nothing at all — it draws in the code colour. Every
8360        // glyph is still `Role::Code`: a token is beside the role, not instead.
8361        let m = map("```rust\nlet x = \"s\";\n```\n");
8362        assert_eq!(tokens_of(&m, 'l'), vec![Some(Token::Keyword)]);
8363        assert_eq!(tokens_of(&m, 'x'), vec![None]);
8364        assert_eq!(tokens_of(&m, '"'), vec![Some(Token::String); 2]);
8365        assert!(
8366            m.rows
8367                .iter()
8368                .filter(|r| r.code)
8369                .flat_map(|r| r.glyphs.iter())
8370                .all(|g| g.style.role == Role::Code),
8371            "a token replaced the code role"
8372        );
8373    }
8374
8375    #[cfg(feature = "syntax")]
8376    #[test]
8377    fn a_token_changes_nothing_about_where_a_glyph_is() {
8378        // The same block with and without a language it can be highlighted in
8379        // lays out identically: same rows, same offsets, same stops. Only the
8380        // token differs, so the caret walks a highlighted block as it walked an
8381        // unhighlighted one.
8382        let hl = map("```rust\nlet x = 1; // c\nfn f() {}\n```\n");
8383        let plain = map("```text\nlet x = 1; // c\nfn f() {}\n```\n");
8384        assert_eq!(hl.rows.len(), plain.rows.len());
8385        for (a, b) in hl.rows.iter().zip(&plain.rows) {
8386            assert_eq!(a.end_src, b.end_src);
8387            assert_eq!(a.glyphs.len(), b.glyphs.len());
8388            for (ga, gb) in a.glyphs.iter().zip(&b.glyphs) {
8389                assert_eq!((ga.ch, ga.src, ga.stop), (gb.ch, gb.src, gb.stop));
8390                assert_eq!(ga.style.token(None), gb.style);
8391            }
8392        }
8393        assert!(tokens_of(&hl, 'l').iter().any(Option::is_some));
8394        assert!(tokens_of(&plain, 'l').iter().all(Option::is_none));
8395    }
8396
8397    #[test]
8398    fn a_block_with_no_language_to_highlight_in_carries_no_tokens() {
8399        // A bare fence, an indented block, a fence in a language no grammar
8400        // covers, and inline code all draw as plain code — and so does a
8401        // `rust` fence when the `syntax` feature is off.
8402        for src in [
8403            "```\nlet x = 1;\n```\n",
8404            "    let x = 1;\n",
8405            "```no-such-language\nlet x = 1;\n```\n",
8406            "a `let x` b\n",
8407        ] {
8408            assert!(
8409                tokens_of(&map(src), 'l').iter().all(Option::is_none),
8410                "{src:?} was highlighted"
8411            );
8412        }
8413        #[cfg(not(feature = "syntax"))]
8414        assert!(
8415            tokens_of(&map("```rust\nlet x = 1;\n```\n"), 'l')
8416                .iter()
8417                .all(Option::is_none)
8418        );
8419    }
8420
8421    #[test]
8422    fn inline_code_is_not_a_code_block() {
8423        // A `code` span inside prose is styled by role, not boxed: it's part of a
8424        // normal paragraph row, so it names no `code_blocks` entry.
8425        let m = map("a `snippet` b\n");
8426        assert!(m.code_blocks.is_empty(), "inline code wrongly boxed");
8427        assert!(
8428            m.rows.iter().all(|r| !r.code),
8429            "inline code flagged a code row"
8430        );
8431    }
8432
8433    #[test]
8434    fn caret_steps_over_hidden_delimiters() {
8435        // "a **bold** c": bytes 8,9 are the closing ** — no glyph. Moving right
8436        // from 'd' (src 7) lands on the space before 'c' (src 10), not inside **.
8437        let m = map("a **bold** c\n");
8438        let (r, c) = m.pos_of_offset(7);
8439        assert_eq!(m.offset_of_pos(r, c + 1), 10);
8440    }
8441
8442    // ── the structural view of a table ───────────────────────────────────────
8443
8444    #[test]
8445    fn a_table_is_published_structurally_beside_its_picture() {
8446        let m = map(TABLE);
8447        let t = &m.tables[0];
8448        let cell = |r: usize, c: usize| -> String {
8449            t.grid[r].cells[c].glyphs.iter().map(|g| g.ch).collect()
8450        };
8451        assert_eq!(t.grid.len(), 3, "head + two body rows");
8452        assert_eq!(
8453            (cell(0, 0), cell(0, 1), cell(1, 0), cell(2, 1)),
8454            ("Name".into(), "Qty".into(), "Pear".into(), "12".into())
8455        );
8456        assert_eq!(
8457            t.grid.iter().map(|r| r.head).collect::<Vec<_>>(),
8458            [true, false, false]
8459        );
8460        // The alignment the delimiter row spelled, carried per cell — the only
8461        // place it survives, since the parser consumes that row.
8462        assert!(matches!(t.grid[1].cells[0].align, Alignment::Left));
8463        assert!(matches!(t.grid[1].cells[1].align, Alignment::Right));
8464    }
8465
8466    #[test]
8467    fn a_block_media_is_published_structurally_beside_its_placeholder() {
8468        let m = map("intro\n\n![a cat](img/cat.png)\n\nend\n");
8469        assert_eq!(m.media.len(), 1, "one block image");
8470        let img = &m.media[0];
8471        assert_eq!(img.destination, "img/cat.png");
8472        assert_eq!(img.alt, "a cat");
8473        // The placeholder row named by `rows_span` carries the label a plain
8474        // surface paints and a capable frontend replaces.
8475        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
8476        assert_eq!(
8477            img.rows_span.end - img.rows_span.start,
8478            1,
8479            "one placeholder row"
8480        );
8481        assert_eq!(row_text(img.rows_span.start), "🖼 a cat");
8482        // The row carries the mark `media_spans` derives the side-table from.
8483        assert!(m.rows[img.rows_span.start].media.is_some());
8484    }
8485
8486    #[test]
8487    fn an_image_without_alt_labels_itself_with_its_filename() {
8488        let m = map("![](photos/beach.jpg)\n");
8489        let row = &m.rows[m.media[0].rows_span.start];
8490        assert_eq!(
8491            row.glyphs.iter().map(|g| g.ch).collect::<String>(),
8492            "🖼 beach.jpg"
8493        );
8494        assert_eq!(m.media[0].alt, "");
8495    }
8496
8497    #[test]
8498    fn an_empty_cells_home_is_read_from_either_shape_of_span() {
8499        // A whole-row span: the cell's pipes are the `col`-th and next.
8500        let row = "|  |  |";
8501        assert_eq!(empty_cell_offset(row, 10, 0), 12);
8502        assert_eq!(empty_cell_offset(row, 10, 1), 15);
8503        // A cell's own span, opening pipe to closing pipe exclusive: the same
8504        // homes, each read from its own span.
8505        assert_eq!(empty_cell_offset("|  ", 10, 0), 12);
8506        assert_eq!(empty_cell_offset("|  ", 13, 1), 15);
8507        // Nothing to stand in: just inside the pipe, never past the span.
8508        assert_eq!(empty_cell_offset("|", 10, 0), 11);
8509        assert_eq!(empty_cell_offset("", 10, 1), 10);
8510    }
8511
8512    #[test]
8513    fn a_hidden_marks_content_end_is_a_caret_home_but_not_a_glyph_stop() {
8514        // `a **bold** b`: the `d` is at 7, the content ends at 8, the closing
8515        // `**` draws nothing, and the space after it is at 10. Two homes at one
8516        // spot on screen: 8 (inside the bold) and 10 (past it).
8517        let m = map("a **bold** b\n");
8518        assert!(
8519            !m.stops.contains(&8),
8520            "8 has no glyph, so it is no glyph stop"
8521        );
8522        assert_eq!(m.mark_ends, vec![8]);
8523        assert!(m.is_stop(8), "but the caret may rest there");
8524        assert_eq!(m.snap_to_stop(8), 8, "and is left there when placed there");
8525        // Left/Right take both homes; the character-pairing walk takes one.
8526        assert_eq!(m.caret_stop_after(7), Some(8));
8527        assert_eq!(m.caret_stop_after(8), Some(10));
8528        assert_eq!(m.caret_stop_before(10), Some(8));
8529        assert_eq!(m.caret_stop_before(8), Some(7));
8530        assert_eq!(m.stop_after(7), Some(10));
8531        assert_eq!(m.stop_before(10), Some(7));
8532        // Drawn where the next glyph is: after the `d`, not on it.
8533        assert_eq!(m.pos_of_offset(8), m.pos_of_offset(10));
8534    }
8535
8536    #[test]
8537    fn every_hidden_inline_mark_gives_its_content_end_a_home() {
8538        // One end per mark, whatever it is spelled with; nested marks closing
8539        // together share the outer's end and the inner's alike.
8540        assert_eq!(
8541            map("*em* `code` [link](u) ~~del~~\n").mark_ends,
8542            vec![3, 10, 17, 27]
8543        );
8544        assert_eq!(map("***both***\n").mark_ends, vec![7]);
8545        // A mark that closes at its row's end coincides with the row's own end
8546        // stop — one offset, in both tables.
8547        let m = map("**bold**\n");
8548        assert_eq!(m.mark_ends, vec![6]);
8549        assert!(m.stops.contains(&6));
8550        // Revealed, the delimiter is glyphs of its own and the end is an
8551        // ordinary glyph stop: nothing to add.
8552        let mut ed = Editor::new_str("a **bold** b\n", Format::Markdown).unwrap();
8553        let src = "a **bold** b\n";
8554        let revealed = build(
8555            &ed.nodes().unwrap(),
8556            src,
8557            Some(80),
8558            false,
8559            &Surface::default(),
8560            Some(Reveal::full(0..src.len())),
8561        );
8562        assert!(revealed.mark_ends.is_empty());
8563        assert!(revealed.stops.contains(&8));
8564    }
8565
8566    #[test]
8567    fn a_marks_content_end_is_a_home_inside_a_table_cell() {
8568        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
8569        let m = map(src);
8570        let end = src.find("bold").unwrap() + 4; // 32, before the closing `**`
8571        assert_eq!(m.mark_ends, vec![end]);
8572        assert_eq!(m.snap_to_stop(end), end);
8573        // Drawn after the `d`, in this cell — where the cell's own end stop is.
8574        assert_eq!(m.pos_of_offset(end), m.pos_of_offset(end + 2));
8575    }
8576
8577    #[test]
8578    fn a_block_media_gives_the_caret_a_home_before_and_after_it() {
8579        // `![x](y)` on its own line: the caret can rest in front of the image
8580        // (its start) and just past it (the row end), and nowhere inside the
8581        // markup — the same coarse mapping a thematic break uses.
8582        let src = "![x](y.png)\n";
8583        let m = map(src);
8584        let img = &m.rows[m.media[0].rows_span.start];
8585        let start = 0; // the image opens the document
8586        let end = "![x](y.png)".len();
8587        // Every placeholder glyph maps to the image start and is a stop there.
8588        assert!(img.glyphs.iter().all(|g| g.src == start && g.stop));
8589        assert_eq!(img.end_src, end, "the row ends past the image");
8590        assert_eq!(m.stops.first(), Some(&start));
8591        assert!(m.stops.contains(&end), "a stop sits after the image");
8592        // Nothing inside the markup is a stop.
8593        assert!(!m.stops.iter().any(|&s| s > start && s < end));
8594    }
8595
8596    #[test]
8597    fn an_inline_image_amid_text_is_not_a_block_media() {
8598        // An image sharing its line with prose isn't block-level: it stays in the
8599        // inline path (rendered as its alt text), and publishes no MediaInfo.
8600        let m = map("see ![a cat](cat.png) here\n");
8601        assert!(m.media.is_empty(), "not a block image");
8602        assert!(
8603            rendered(&m).contains("a cat"),
8604            "alt text still renders inline"
8605        );
8606    }
8607
8608    /// The block images `Doc` publishes for `src`, driven through the real
8609    /// production build (`build_visual` → `build_cached`) with `html_elements`
8610    /// on — the path a `<picture>` actually travels. Not the raw `build` the
8611    /// other tests use: the editor's flat whole-arena snapshot tangles the links
8612    /// of inline-promoted HTML (phantom roots, dangling `parent`s), which only
8613    /// the per-block subtree walk `build_cached` does untangles.
8614    fn doc_media(src: &str) -> Vec<MediaInfo> {
8615        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
8616        doc.build_visual(80);
8617        doc.vmap.media.clone()
8618    }
8619
8620    #[test]
8621    fn a_video_block_is_media_with_its_src_poster_and_kind() {
8622        // The load-bearing assumption of video support: twig has no `video` node
8623        // kind, so `html_elements` promotion must land a `<video>` as a generic
8624        // `element` whose tag name and attributes survive onto `FlatNode` — the
8625        // same treatment `<picture>` gets. If that ever stops holding, this is
8626        // the test that says so.
8627        let m = doc_media("<video src=\"clip.mp4\" poster=\"still.png\" controls>\n</video>\n");
8628        assert_eq!(m.len(), 1, "the video is one block media");
8629        assert_eq!(m[0].kind, MediaKind::Video);
8630        assert_eq!(m[0].destination, "clip.mp4");
8631        assert_eq!(m[0].poster, "still.png");
8632    }
8633
8634    #[test]
8635    fn a_single_line_video_is_a_block_too() {
8636        // The spelling everyone actually writes. It used to parse as a paragraph
8637        // of raw inline HTML — CommonMark opens a block on a complete tag only
8638        // when the line ends there, and its fixed tag list predates `<video>` —
8639        // so the tags never reached core as an element at all. twig 2.5.1 widened
8640        // that list under `html_elements`; this is the test that would catch the
8641        // pin sliding back.
8642        let m = doc_media("<video src=\"clip.mp4\" controls></video>\n");
8643        assert_eq!(m.len(), 1, "single-line <video> is a block");
8644        assert_eq!(m[0].kind, MediaKind::Video);
8645        assert_eq!(m[0].destination, "clip.mp4");
8646    }
8647
8648    #[test]
8649    fn a_single_line_picture_is_a_block_with_its_alternatives() {
8650        // `<picture>` had the identical gap and it went unnoticed because the
8651        // conventional spelling breaks the lines. Same twig fix covers it.
8652        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\
8653                   <img src=\"l.svg\" alt=\"banner\"></picture>\n";
8654        let m = doc_media(src);
8655        assert_eq!(m.len(), 1);
8656        assert_eq!(m[0].kind, MediaKind::Image);
8657        assert_eq!(m[0].destination, "l.svg");
8658        assert_eq!(m[0].resolve(ColorScheme::Dark), "d.svg");
8659    }
8660
8661    #[test]
8662    fn an_audio_block_is_media_with_no_poster() {
8663        let m = doc_media("<audio src=\"take.mp3\" controls>\n</audio>\n");
8664        assert_eq!(m.len(), 1);
8665        assert_eq!(m[0].kind, MediaKind::Audio);
8666        assert_eq!(m[0].destination, "take.mp3");
8667        assert!(m[0].poster.is_empty(), "audio has no poster frame");
8668    }
8669
8670    #[test]
8671    fn a_videos_source_children_are_its_candidates_typed_by_mime() {
8672        // A `<video>` with no `src` of its own — the common shape, since it's how
8673        // you offer more than one codec. The candidates come from `<source src>`
8674        // (not `srcset`, which is `<picture>`'s spelling) and carry their MIME.
8675        let src = "<video controls>\n\
8676                   <source src=\"a.webm\" type=\"video/webm\">\n\
8677                   <source src=\"a.mp4\" type=\"video/mp4\">\n\
8678                   fallback\n\
8679                   </video>\n";
8680        let m = doc_media(src);
8681        assert_eq!(m.len(), 1);
8682        assert!(
8683            m[0].destination.is_empty(),
8684            "no src attribute on the element"
8685        );
8686        assert_eq!(m[0].sources.len(), 2);
8687        assert_eq!(m[0].sources[0].srcset, "a.webm");
8688        assert_eq!(m[0].sources[0].mime, "video/webm");
8689        assert_eq!(m[0].sources[1].srcset, "a.mp4");
8690        // With an empty destination, `resolve` falls through to the first
8691        // candidate rather than handing the frontend nothing to load.
8692        assert_eq!(m[0].resolve(ColorScheme::Light), "a.webm");
8693    }
8694
8695    #[test]
8696    fn a_video_placeholder_row_carries_its_own_sigil_and_mark() {
8697        // The placeholder contract images already hold, now for a video: the row
8698        // renders as a labelled stand-in a plain surface can paint as-is, and
8699        // carries the mark a capable frontend replaces it from.
8700        let src = "<video src=\"clip.mp4\" controls>\n</video>\n";
8701        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
8702        doc.build_visual(80);
8703        let row = &doc.vmap.rows[doc.vmap.media[0].rows_span.start];
8704        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
8705        assert!(
8706            text.starts_with('🎬'),
8707            "video sigil, not the image one: {text:?}"
8708        );
8709        assert!(row.media.is_some(), "the mark rides the placeholder row");
8710    }
8711
8712    #[test]
8713    fn a_picture_block_carries_its_source_alternatives() {
8714        // A `<picture>` with a dark-mode `<source>`: one block image, whose
8715        // fallback destination is the `<img>` and whose `sources` carry the
8716        // `<source>`'s media + srcset for a theme-aware frontend to pick.
8717        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"banner\"></picture>\n";
8718        let images = doc_media(src);
8719        assert_eq!(images.len(), 1, "the picture is one block image");
8720        let img = &images[0];
8721        assert_eq!(img.destination, "light.svg", "fallback is the <img>");
8722        assert_eq!(img.alt, "banner");
8723        assert_eq!(
8724            img.sources,
8725            vec![MediaSource {
8726                media: "(prefers-color-scheme: dark)".into(),
8727                srcset: "dark.svg".into(),
8728                mime: String::new(),
8729            }],
8730        );
8731    }
8732
8733    #[test]
8734    fn a_picture_inside_a_heading_is_still_a_block_media_with_sources() {
8735        // fig.md's shape: the banner is an `<h1>` wrapping the `<picture>`.
8736        let src = "<h1><picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\"><img src=\"l.svg\" alt=\"fig\"></picture></h1>\n";
8737        let images = doc_media(src);
8738        assert_eq!(images.len(), 1, "heading-wrapped picture is a block image");
8739        assert_eq!(images[0].destination, "l.svg");
8740        assert_eq!(images[0].sources.len(), 1);
8741        assert_eq!(images[0].sources[0].srcset, "d.svg");
8742    }
8743
8744    #[test]
8745    fn a_plain_image_has_no_media_sources() {
8746        // A bare Markdown image carries an empty `sources` — nothing to pick from.
8747        let images = doc_media("![alt](p.png)\n");
8748        assert_eq!(images.len(), 1);
8749        assert!(
8750            images[0].sources.is_empty(),
8751            "no <picture>, no alternatives"
8752        );
8753    }
8754
8755    #[test]
8756    fn resolve_picks_the_source_matching_the_scheme() {
8757        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"b\"></picture>\n";
8758        let images = doc_media(src);
8759        let img = &images[0];
8760        // Dark theme takes the dark source; light falls through to the <img>.
8761        assert_eq!(img.resolve(ColorScheme::Dark), "dark.svg");
8762        assert_eq!(img.resolve(ColorScheme::Light), "light.svg");
8763    }
8764
8765    #[test]
8766    fn resolve_falls_back_for_a_plain_image_and_unknown_media() {
8767        // A plain image ignores the scheme.
8768        let plain = doc_media("![a](p.png)\n");
8769        assert_eq!(plain[0].resolve(ColorScheme::Dark), "p.png");
8770
8771        // A <source> with an unrecognized media query is skipped; a light source
8772        // is taken under a light theme.
8773        let m = doc_media(
8774            "<picture><source media=\"print\" srcset=\"p.svg\"><source media=\"(prefers-color-scheme: light)\" srcset=\"l.svg\"><img src=\"f.svg\" alt=\"x\"></picture>\n",
8775        );
8776        assert_eq!(m[0].resolve(ColorScheme::Light), "l.svg");
8777        assert_eq!(
8778            m[0].resolve(ColorScheme::Dark),
8779            "f.svg",
8780            "no dark source → <img>"
8781        );
8782    }
8783
8784    #[test]
8785    fn resolve_reads_the_first_srcset_url_ignoring_descriptors() {
8786        // A comma/descriptor srcset resolves to its first URL.
8787        assert_eq!(first_srcset_url("a.png 1x, b.png 2x"), Some("a.png"));
8788        assert_eq!(first_srcset_url("  solo.svg  "), Some("solo.svg"));
8789        assert_eq!(first_srcset_url(""), None);
8790        // An empty (unconditional) media always matches.
8791        assert!(media_matches("", ColorScheme::Light));
8792        assert!(media_matches(
8793            "(prefers-color-scheme:dark)",
8794            ColorScheme::Dark
8795        ));
8796        assert!(!media_matches(
8797            "(prefers-color-scheme: dark)",
8798            ColorScheme::Light
8799        ));
8800    }
8801
8802    #[test]
8803    fn a_block_media_carries_its_list_prefix() {
8804        // An image that is a list item's body opens past the bullet, like every
8805        // other block does.
8806        let m = map("- ![alt](p.png)\n");
8807        let row = &m.rows[m.media[0].rows_span.start];
8808        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
8809        assert!(
8810            text.starts_with("• "),
8811            "the list marker prefixes the image row: {text:?}"
8812        );
8813        assert!(text.contains("🖼 alt"));
8814    }
8815
8816    #[test]
8817    fn the_structural_table_spans_exactly_its_drawn_rows() {
8818        // A frontend drawing its own grid skips `rows_span` and renders from
8819        // `grid`. If the span were short the leftover border rows would be
8820        // painted as text under the real table; if long it would eat a
8821        // neighbouring paragraph. Both are silent, so pin it to the picture.
8822        let m = map(&format!("before\n\n{TABLE}\nafter\n"));
8823        let t = &m.tables[0];
8824        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
8825        assert!(
8826            row_text(t.rows_span.start).starts_with('┌'),
8827            "opens on the top border"
8828        );
8829        assert!(
8830            row_text(t.rows_span.end - 1).starts_with('└'),
8831            "closes on the bottom border"
8832        );
8833        assert!(
8834            !row_text(t.rows_span.start - 1).contains('┌'),
8835            "the row before the span is not the table's"
8836        );
8837        assert_eq!(
8838            row_text(t.rows_span.end),
8839            "",
8840            "the span ends before the gap row"
8841        );
8842    }
8843
8844    #[test]
8845    fn a_nested_tables_structure_carries_the_block_prefix() {
8846        // The picture puts the quote's gutter on every row of the grid. A
8847        // frontend drawing its own table has to draw that too and start past it,
8848        // so the prefix has to travel with the structure — without it a quoted
8849        // table renders flush at the margin and leaves the quote it's in.
8850        let m = map("> | a | b |\n> |---|---|\n> | c | d |\n");
8851        let t = &m.tables[0];
8852        let prefix: String = t.prefix.iter().map(|g| g.ch).collect();
8853        assert_eq!(prefix, "│ ", "the quote's gutter should ride the structure");
8854        // And it matches what the picture actually drew.
8855        let drawn: String = m.rows[t.rows_span.start]
8856            .glyphs
8857            .iter()
8858            .map(|g| g.ch)
8859            .collect();
8860        assert!(
8861            drawn.starts_with(&prefix),
8862            "picture and structure disagree: {drawn:?}"
8863        );
8864    }
8865
8866    #[test]
8867    fn a_top_level_table_carries_no_prefix() {
8868        assert!(map(TABLE).tables[0].prefix.is_empty());
8869    }
8870
8871    #[test]
8872    fn structural_cells_are_unwrapped_even_when_the_picture_wraps_them() {
8873        // The picture wraps a cell to its column; a frontend laying the grid out
8874        // in pixels needs the text as the document spells it, before that
8875        // decision. Narrow enough that the drawn cell must break.
8876        let src = "| Name |\n|------|\n| alpha beta gamma |\n";
8877        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8878        let m = build_t(&ed.nodes().unwrap(), src, Some(12));
8879        let drawn = rendered(&m);
8880        let cell: String = m.tables[0].grid[1].cells[0]
8881            .glyphs
8882            .iter()
8883            .map(|g| g.ch)
8884            .collect();
8885        assert_eq!(
8886            cell, "alpha beta gamma",
8887            "structure must not carry the wrap"
8888        );
8889        assert!(
8890            drawn.lines().count() > 5,
8891            "the picture should have wrapped, else this proves nothing:\n{drawn}"
8892        );
8893    }
8894
8895    // ── display columns ──────────────────────────────────────────────────────
8896
8897    #[test]
8898    fn a_table_column_is_as_wide_as_its_cells_are_drawn() {
8899        // A column sized by counting characters is drawn narrower than the text
8900        // it has to hold — `你好` is two characters in four cells — and the cell
8901        // spills over the border it is supposed to sit inside, taking the whole
8902        // grid out of square with it. Squareness is the property: every row of a
8903        // grid is drawn to the same column, whatever its cells are spelled with.
8904        for src in [
8905            "| A | B |\n|---|---|\n| 你好 | y |\n",
8906            "| A | B |\n|---|---|\n| a👨‍👩‍👧b | y |\n",
8907            "| A | 漢字 |\n|---|---|\n| x | y |\n",
8908        ] {
8909            let m = map(src);
8910            let widths: Vec<usize> = m.rows.iter().map(|r| r.width()).collect();
8911            assert!(
8912                widths.windows(2).all(|w| w[0] == w[1]),
8913                "ragged grid {widths:?} for {src:?}:\n{}",
8914                rendered(&m)
8915            );
8916        }
8917    }
8918
8919    #[test]
8920    fn a_cell_wrapped_narrow_never_breaks_inside_a_character() {
8921        // A column too narrow for its cell hard-breaks the text, and every line
8922        // of it is given an end stop just past its last glyph. Broken into runs
8923        // of four glyphs, the first line of this cell ends between `👨‍👩` and the
8924        // joiner holding `👧` on — so its end stop lands inside a character,
8925        // where a click or Down can reach it and the next Backspace takes the
8926        // cluster apart from the middle.
8927        let src = "| A |\n|---|\n| 👨‍👩‍👧👨‍👩‍👧 |\n";
8928        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8929        let m = build_t(&ed.nodes().unwrap(), src, Some(8));
8930        let boundaries: Vec<usize> = src
8931            .grapheme_indices(true)
8932            .map(|(i, _)| i)
8933            .chain(std::iter::once(src.len()))
8934            .collect();
8935        for off in (0..=src.len()).filter(|&o| m.is_stop(o)) {
8936            assert!(
8937                boundaries.contains(&off),
8938                "stop at {off} is inside a character:\n{}",
8939                rendered(&m)
8940            );
8941        }
8942    }
8943
8944    #[test]
8945    fn a_wrapped_cell_keeps_every_line_inside_its_column() {
8946        // The width is a promise in a table, where a glyph past the column lands
8947        // on the border or in the next cell — and it is a promise about cells,
8948        // which is not what a count of glyphs measures.
8949        let src = "| A |\n|---|\n| 你好世界漢字 |\n";
8950        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8951        let m = build_t(&ed.nodes().unwrap(), src, Some(14));
8952        for r in &m.rows {
8953            assert_eq!(r.width(), 14, "{:?} is not drawn to the grid", rendered(&m));
8954        }
8955    }
8956
8957    #[test]
8958    fn a_hard_break_falls_between_clusters_and_measures_in_cells() {
8959        let glyphs = |s: &str| {
8960            let mut out = Vec::new();
8961            push_text(&mut out, s, 0, Style::default());
8962            out
8963        };
8964        let piece = |p: &[Glyph]| p.iter().map(|g| g.ch).collect::<String>();
8965
8966        // Six cells of CJK broken at four: two characters, then one — never
8967        // between the two cells of `好`.
8968        let w = glyphs("你好世");
8969        let pieces: Vec<String> = hard_break(&w, 4).iter().map(|p| piece(p)).collect();
8970        assert_eq!(pieces, ["你好", "世"]);
8971
8972        // A character wider than the column has nowhere legal to break, so it
8973        // keeps its cells rather than being cut in half.
8974        let w = glyphs("你好");
8975        let pieces: Vec<String> = hard_break(&w, 1).iter().map(|p| piece(p)).collect();
8976        assert_eq!(pieces, ["你", "好"]);
8977
8978        // An empty word yields no pieces at all — a double space stays a space.
8979        assert!(hard_break(&[], 4).is_empty());
8980    }
8981
8982    #[test]
8983    fn an_empty_list_item_still_gets_a_bulleted_row_with_a_caret_home() {
8984        // Pressing Enter at the end of a list item opens a new, empty item —
8985        // a childless `list_item`. Without a row of its own the new bullet
8986        // wouldn't appear until something was typed into it (the caret would be
8987        // stranded on an offset no row draws). It now renders as one prefixed
8988        // row whose end is a caret stop, so the bullet shows and the caret lands
8989        // just past the marker.
8990        let m = map("- item\n- \n");
8991        assert_eq!(m.num_rows(), 2, "the empty second item needs its own row");
8992        assert_eq!(
8993            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8994            "• ",
8995            "the empty item draws just its bullet",
8996        );
8997        // Its end is the caret home (past the `- ` marker), and it's a real stop.
8998        assert!(
8999            m.is_stop(m.rows[1].end_src),
9000            "the empty item's caret home is not a stop"
9001        );
9002        assert_eq!(
9003            m.pos_of_offset(m.rows[1].end_src),
9004            (1, 2),
9005            "caret sits after '• '"
9006        );
9007    }
9008
9009    #[test]
9010    fn a_notes_row_range_stops_at_the_note_even_when_it_ends_in_a_link() {
9011        // The peek bug: a note whose body ends in a link has its last byte
9012        // inside the hidden destination, so mapping `end - 1` through
9013        // `pos_of_offset` snapped *forward* — past its own row, past the drawn
9014        // gap, and onto the next note's row. The popover then drew both notes.
9015        let src = "A[^1] B[^2].\n\n[^1]: bare text\n\n[^2]: [title](https://example.com/x)\n\n[^3]: last\n";
9016        let m = map(src);
9017        let body = src.find("[title]").unwrap();
9018        let end = src.find("\n\n[^3]").unwrap();
9019
9020        let (first, last) = m.row_range_for(body..end);
9021        assert_eq!(
9022            first, last,
9023            "a one-block note is one row, not a span onto the next"
9024        );
9025
9026        // The old arithmetic, kept here as the thing that must stay wrong: it
9027        // is what this method exists instead of.
9028        assert_ne!(
9029            m.pos_of_offset(end - 1).0,
9030            last,
9031            "the forward snap still leaves the note's row — that is the whole point",
9032        );
9033
9034        // A note ending in *visible* text was never broken, and still isn't:
9035        // both readings agree there, which is why the original test missed it.
9036        let plain = src.find("bare text").unwrap();
9037        let plain_end = src.find("\n\n[^2]").unwrap();
9038        let (pf, pl) = m.row_range_for(plain..plain_end);
9039        assert_eq!(pf, pl);
9040        assert_eq!(m.pos_of_offset(plain_end - 1).0, pl);
9041    }
9042
9043    #[test]
9044    fn a_row_range_covers_every_row_of_a_block_that_spans_several() {
9045        // The range is a span, not a point: a quote of two paragraphs covers its
9046        // gap row and both of its text rows, so a peek draws the whole thing.
9047        let src = "> one\n>\n> two\n\nafter\n";
9048        let m = map(src);
9049        let (first, last) = m.row_range_for(0..src.find("\n\nafter").unwrap());
9050        assert_eq!((first, last), (0, 2));
9051
9052        // And a range with no visible byte at all still covers the row it opened
9053        // on, rather than collapsing to nothing.
9054        let (f, l) = m.row_range_for(0..1);
9055        assert_eq!((f, l), (0, 0));
9056    }
9057
9058    #[test]
9059    fn an_empty_block_quote_still_gets_a_gutter_row_with_a_caret_home() {
9060        // The peer of the empty list item, and the case that made an empty line
9061        // in a quote draw as plain body text: a childless `block_quote` — a bare
9062        // `> `, which is what the toolbar's Quote button leaves on a blank line —
9063        // has no inner block to carry the gutter, so the whole quote used to
9064        // render as *nothing*. It didn't merely lose its bar; the row went away
9065        // and the caret had no home on it.
9066        let m = map("a\n\n> \n\nb\n");
9067        assert_eq!(
9068            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
9069            "│ ",
9070            "the empty quote draws just its gutter",
9071        );
9072        assert!(
9073            m.rows[2]
9074                .glyphs
9075                .iter()
9076                .all(|g| g.style.role == Role::QuoteGutter)
9077        );
9078        assert!(
9079            !m.rows[2].decoration,
9080            "it is a line text can go on, not a drawn gap"
9081        );
9082        assert!(
9083            m.is_stop(m.rows[2].end_src),
9084            "the empty quote's caret home is not a stop"
9085        );
9086        assert_eq!(
9087            m.pos_of_offset(m.rows[2].end_src),
9088            (2, 2),
9089            "caret sits after '│ '"
9090        );
9091
9092        // And a document that is *only* an empty quote still renders a row — it
9093        // used to render none at all, leaving the caret nowhere to stand.
9094        let m = map("> \n");
9095        assert_eq!(m.num_rows(), 1);
9096        assert_eq!(
9097            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
9098            "│ "
9099        );
9100    }
9101
9102    #[test]
9103    fn a_quotes_own_trailing_marker_lines_stay_inside_the_quote() {
9104        // Enter at the end of `> a` writes `> a\n>\n> \n`. Those last two lines
9105        // hold no block — a quote's `content_span` stops at its last child — so
9106        // the children walk never reaches them, and they used to fall through to
9107        // the document-level trailing pass, which knows no prefix: the gutter
9108        // stopped and the writer's new line drew as plain prose. Fixable only
9109        // since twig 3.2.0, where the quote's *span* covers its own marker lines
9110        // (`0..3` before, `0..8` now) and there is finally a node saying they
9111        // are the quote's.
9112        let m = map("> a\n>\n> \n");
9113        assert_eq!(m.num_rows(), 3, "one row per line the quote spells");
9114        for (i, row) in m.rows.iter().enumerate() {
9115            let text = row.glyphs.iter().map(|g| g.ch).collect::<String>();
9116            assert!(text.starts_with("│ "), "row {i} lost the gutter: {text:?}");
9117            assert!(
9118                !row.decoration,
9119                "row {i} is a line to type on, not a drawn gap"
9120            );
9121            assert!(m.is_stop(row.end_src), "row {i} has no caret home");
9122        }
9123        assert_eq!(
9124            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
9125            "│ a"
9126        );
9127        // Distinct offsets, so ↑/↓ between them moves the caret rather than
9128        // landing twice on the same byte.
9129        assert!(m.rows[0].end_src < m.rows[1].end_src);
9130        assert!(m.rows[1].end_src < m.rows[2].end_src);
9131
9132        // A blank line *after* the quote is not the quote's: it is spelled with
9133        // no marker, so it stays an ordinary boundary and the gutter ends.
9134        let m = map("> a\n\nb\n");
9135        assert_eq!(m.num_rows(), 3);
9136        assert_eq!(
9137            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
9138            "b"
9139        );
9140        assert!(
9141            !m.rows[1]
9142                .glyphs
9143                .iter()
9144                .any(|g| g.style.role == Role::QuoteGutter)
9145        );
9146
9147        // Nesting is the case this could get wrong, and the depth has to come
9148        // from which quote's span the line falls in rather than from the row
9149        // above it. A trailing `>` under `> > a` matches only the OUTER quote,
9150        // so it wears one gutter; spell it `> >` and it wears two.
9151        let m = map("> > a\n>\n");
9152        assert_eq!(
9153            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
9154            "│ │ a"
9155        );
9156        assert_eq!(
9157            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
9158            "│ "
9159        );
9160        let m = map("> > a\n> >\n");
9161        assert_eq!(
9162            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
9163            "│ │ "
9164        );
9165
9166        // And a marker line BETWEEN two quoted paragraphs is untouched: that is
9167        // the boundary `emit_separators_before` spells, and it stays a drawn gap
9168        // rather than becoming a line to type on.
9169        let m = map("> a\n>\n> b\n");
9170        assert_eq!(m.num_rows(), 3);
9171        assert!(
9172            m.rows[1].decoration,
9173            "the gap between two quoted blocks is still a gap"
9174        );
9175    }
9176
9177    #[test]
9178    fn an_empty_ordered_item_gets_its_number_and_a_caret_home() {
9179        let m = map("1. item\n2. \n");
9180        assert_eq!(m.num_rows(), 2);
9181        assert_eq!(
9182            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
9183            "2. "
9184        );
9185        assert!(m.is_stop(m.rows[1].end_src));
9186        assert_eq!(
9187            m.pos_of_offset(m.rows[1].end_src),
9188            (1, 3),
9189            "caret sits after '2. '"
9190        );
9191    }
9192
9193    #[test]
9194    fn an_empty_headings_caret_home_is_past_its_hidden_marker() {
9195        // The toolbar's H1 on a blank line writes `# ` and nothing else. The row
9196        // it renders is empty (the marker is hidden), so its end *is* its only
9197        // caret stop — and it has to be the offset past the `# `, where typing
9198        // continues the heading. Anchored at the block's start instead, the caret
9199        // drew in front of the hashes and the first character typed there landed
9200        // before them (`x# `), which isn't a heading at all.
9201        let m = map("# \n");
9202        assert_eq!(m.num_rows(), 1);
9203        assert!(m.rows[0].glyphs.is_empty(), "the `# ` marker is hidden");
9204        assert_eq!(m.rows[0].end_src, 2, "the caret home is past the marker");
9205        assert!(m.is_stop(2), "the empty heading's caret home is not a stop");
9206    }
9207
9208    #[test]
9209    fn a_headings_rows_carry_its_level_even_with_nothing_typed_in_it() {
9210        // The row-level fact a proportional frontend sizes a whole line by. An
9211        // empty heading has no glyph to read a `Role::Heading` off, so a renderer
9212        // scanning glyphs drew `# ` (and its caret) at body height until the
9213        // first character landed.
9214        let m = map("# \n");
9215        assert_eq!(
9216            m.rows[0].heading,
9217            Some(1),
9218            "the empty heading knows its level"
9219        );
9220
9221        // Every row of one that wraps, not just the first — and nothing else.
9222        let m = map_at(
9223            "## a heading long enough to wrap over two rows\n\nbody\n",
9224            Some(20),
9225        );
9226        let heads: Vec<Option<u8>> = m.rows.iter().map(|r| r.heading).collect();
9227        assert!(
9228            heads.iter().filter(|h| **h == Some(2)).count() >= 2,
9229            "got {heads:?}"
9230        );
9231        assert_eq!(
9232            m.rows.last().and_then(|r| r.heading),
9233            None,
9234            "the paragraph under it is not a heading",
9235        );
9236    }
9237
9238    #[test]
9239    fn an_empty_heading_leaves_the_rows_under_it_at_their_own_offsets() {
9240        // The row's end is also what the *next* row's separator is measured from,
9241        // so an empty heading that under-reported it shifted every offset below —
9242        // and the blank line under the heading then claimed the same offset as the
9243        // heading's own end. `pos_of_offset` resolves such a tie downstream (a
9244        // soft wrap belongs to the row below), so the caret at the end of the
9245        // heading was drawn two rows lower, on the blank line.
9246        // `text\n\n# \n\n`: the heading's content opens at 8, and the two rows
9247        // under it end at 9 and 10 — the blank line and the document's end.
9248        let m = map("text\n\n# \n\n");
9249        let end = m.rows.last().expect("a trailing blank row").end_src;
9250        assert_eq!(end, 10, "the trailing rows must end at their real offsets");
9251        // The heading's caret home is its own row's, not one shared with a row
9252        // below — the tie that drew the caret two rows down.
9253        assert_eq!(m.pos_of_offset(8), (2, 0), "the empty heading's own row");
9254        assert!(
9255            m.rows[3..].iter().all(|r| r.end_src > 8),
9256            "rows below own later offsets"
9257        );
9258    }
9259
9260    // ── block boundaries ─────────────────────────────────────────────────────
9261
9262    /// Every drawn boundary in `src`, in order, as `(above, below)`.
9263    fn boundaries(m: &VisualMap) -> Vec<(BlockClass, BlockClass)> {
9264        m.rows
9265            .iter()
9266            .filter_map(|r| r.boundary)
9267            .map(|b| (b.above, b.below))
9268            .collect()
9269    }
9270
9271    #[test]
9272    fn a_boundary_says_which_blocks_it_divides() {
9273        use BlockClass::*;
9274        let m = map("one\n\ntwo\n\n# Head\n\ntail\n\n> quoted\n\n```\ncode\n```\n\n");
9275        assert_eq!(
9276            boundaries(&m),
9277            vec![
9278                (Paragraph, Paragraph),
9279                (Paragraph, Heading),
9280                (Heading, Paragraph),
9281                (Paragraph, Quote),
9282                (Quote, Code),
9283                // The blank line the document trails off with is a boundary too
9284                // — it closes the last block above the empty paragraph the caret
9285                // rests on. See `emit_trailing_blank_lines`.
9286                (Code, Paragraph),
9287            ],
9288            "each gap names the pair it falls between, in document order"
9289        );
9290    }
9291
9292    #[test]
9293    fn a_closing_fence_at_the_end_of_the_document_opens_no_phantom_row() {
9294        // The code block's last row ends at its last line of code; the closing
9295        // fence under it has no row. Counted from the row, the fence's line read
9296        // as a trailing blank line and opened an empty paragraph whose offset
9297        // was inside the fence — typing on it wrote into the backticks.
9298        let m = map("para\n\n```\ncode\n```\n");
9299        let texts: Vec<String> = m
9300            .rows
9301            .iter()
9302            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9303            .collect();
9304        assert_eq!(texts, vec!["para", "", "code"], "a row under the fence");
9305        assert!(
9306            m.rows.last().is_some_and(|r| r.code),
9307            "the last row is the code"
9308        );
9309        // One more newline is the real empty paragraph, past the fence.
9310        let m = map("para\n\n```\ncode\n```\n\n");
9311        let last = m.rows.last().expect("a trailing row");
9312        assert_eq!(last.end_src, 20, "the trailing row stands past the fence");
9313        assert!(!last.decoration, "the trailing row is somewhere to type");
9314        // A setext underline is the same shape: markup under the last row.
9315        let m = map("Head\n====\n");
9316        assert_eq!(
9317            m.rows.len(),
9318            1,
9319            "a row under the underline: {:?}",
9320            m.rows.len()
9321        );
9322    }
9323
9324    // ── hidden blocks ────────────────────────────────────────────────────────
9325
9326    /// The row texts of `m`, one string per row.
9327    fn row_texts(m: &VisualMap) -> Vec<String> {
9328        m.rows
9329            .iter()
9330            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9331            .collect()
9332    }
9333
9334    #[test]
9335    fn a_div_s_closing_tag_is_not_a_blank_row() {
9336        // The `</div>` sits on a line of its own under the div's last child and
9337        // draws nothing. Counting the separator from the child's end read that
9338        // line as a blank line between the div and the block below — a
9339        // navigable empty row the author never opened — and at the end of the
9340        // file, as an empty trailing paragraph.
9341        let m = map("above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n");
9342        assert_eq!(row_texts(&m), ["above", "", "hello", "", "below"]);
9343        assert!(!m.is_stop(36), "the `</div>` line is not a caret home");
9344        assert_eq!(
9345            m.stop_after(34),
9346            Some(44),
9347            "from `hello` the next stop is `below`"
9348        );
9349
9350        let m = map("above\n\n<div class=\"center\">\n\nhello\n\n</div>\n");
9351        assert_eq!(row_texts(&m), ["above", "", "hello"], "no trailing rows");
9352    }
9353
9354    #[test]
9355    fn a_comment_between_two_blocks_is_stepped_over_not_drawn_as_a_gap() {
9356        // `<!-- exec -->` is a top-level block that draws no rows. The blocks
9357        // either side of it meet across the one boundary a paragraph and a code
9358        // block always meet across — not that boundary *plus* one blank row per
9359        // line of the comment, which is what counting the separator from the
9360        // paragraph's end used to spell.
9361        let m = map("para one\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n");
9362        assert_eq!(row_texts(&m), ["para one", "", "code", "", "after"]);
9363        assert_eq!(
9364            boundaries(&m),
9365            vec![
9366                (BlockClass::Paragraph, BlockClass::Code),
9367                (BlockClass::Code, BlockClass::Paragraph),
9368            ],
9369            "the boundary names the drawn blocks either side, not the comment"
9370        );
9371        // The gap stands past the comment, so the caret's row lookup never
9372        // resolves inside it.
9373        assert_eq!(
9374            m.rows[1].end_src, 23,
9375            "the gap row ends at the comment's end"
9376        );
9377    }
9378
9379    #[test]
9380    fn a_comment_opening_the_document_draws_no_leading_gap() {
9381        let m = map("<!-- lead -->\n\npara\n");
9382        assert_eq!(row_texts(&m), ["para"]);
9383        assert_eq!(m.content_start, 0, "the comment is still the first block");
9384    }
9385
9386    #[test]
9387    fn a_comment_closing_the_document_is_not_trailing_blank_lines() {
9388        // Its lines are not blank lines the author opened with Enter, so no
9389        // gap-plus-empty-paragraph is fabricated under the last drawn block.
9390        let m = map("para\n\n<!-- trail -->\n");
9391        assert_eq!(row_texts(&m), ["para"]);
9392        // Enter at the end of the document still opens the empty paragraph the
9393        // caret rests on: the newlines *after* the comment count as they would
9394        // after any block.
9395        let m = map("para\n\n<!-- trail -->\n\n");
9396        assert_eq!(row_texts(&m), ["para", "", ""]);
9397    }
9398
9399    #[test]
9400    fn a_comment_in_a_list_item_leaves_the_bullet_to_what_follows_it() {
9401        // The first *drawn* child wears the item's marker; a hidden first child
9402        // would otherwise take it and leave the text without one.
9403        let m = map("- <!-- note -->\n\n  text\n- two\n");
9404        let texts = row_texts(&m);
9405        assert!(
9406            texts.iter().any(|t| t == "• text"),
9407            "the text wears the bullet: {texts:?}"
9408        );
9409        assert!(
9410            !texts.iter().any(|t| t == "• "),
9411            "no empty bullet row for the comment: {texts:?}"
9412        );
9413    }
9414
9415    #[test]
9416    fn the_cached_build_does_not_spell_the_document_out_as_blank_rows_after_a_comment() {
9417        // The bug as seen: a 200-line document with one comment in it rendered
9418        // ~200 blank rows after the comment, one per source line, because the
9419        // comment's per-block builder handed back a `last_off` of 0. Parity with
9420        // `build` alone would not catch a *shared* wrong answer, so the count is
9421        // pinned outright.
9422        let body = (0..200)
9423            .map(|i| format!("line {i}"))
9424            .collect::<Vec<_>>()
9425            .join("\n\n");
9426        let src = format!("intro\n\n<!-- exec -->\n{body}\n");
9427        let mut ed = Editor::new_str(&src, Format::Markdown).unwrap();
9428        let mut cache = BlockCache::default();
9429        let (plain, cached) = render_both(&mut ed, &src, Some(80), &mut cache);
9430        assert_maps_eq(&plain, &cached, "comment then 200 paragraphs");
9431        // intro, then 200 × (gap, paragraph): 401 rows and not a row more.
9432        assert_eq!(cached.rows.len(), 401);
9433    }
9434
9435    #[test]
9436    fn a_link_reference_definition_is_stepped_over_like_a_comment() {
9437        // `[a]: /a` is a root beside `doc` with no rows of its own. Merged into
9438        // the walk it is a hidden block: the blocks either side meet across one
9439        // boundary, and its line is not a blank row.
9440        let m = map("see [a]\n\n[a]: /a\n\nafter\n");
9441        assert_eq!(row_texts(&m), ["see a", "", "after"]);
9442        assert_eq!(
9443            boundaries(&m),
9444            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
9445        );
9446    }
9447
9448    #[test]
9449    fn link_reference_definitions_closing_the_document_are_not_trailing_blank_lines() {
9450        // The README shape: prose, then a `[links]` block nobody reads. Its
9451        // lines used to be counted as blank ones, an empty paragraph per
9452        // definition under the last real block.
9453        let m = map("see [a] and [b]\n\n<!-- links -->\n[a]: /a\n[b]: /b \"bee\"\n");
9454        assert_eq!(row_texts(&m), ["see a and b"]);
9455    }
9456
9457    #[test]
9458    fn a_definition_glued_under_a_paragraph_stays_inside_it() {
9459        // `[a]: /a` at the front of a paragraph's lines is stripped from the
9460        // paragraph's text, but the paragraph's span still starts on its line.
9461        // Both blocks start at the same offset; the definition, sorted first,
9462        // is stepped over, and the paragraph draws as it always did — one gap
9463        // above it, none inside.
9464        let m = map("intro\n\n[a]: /a\ntext [a]\n");
9465        assert_eq!(row_texts(&m), ["intro", "", "text a"]);
9466    }
9467
9468    #[test]
9469    fn a_definition_with_no_span_is_left_out_of_the_walk() {
9470        // twig before 3.3.3 reported `0..0` for every link reference
9471        // definition. One of those has nowhere to be merged: sorted first by
9472        // its zero start it would open the document with a phantom block, and
9473        // the walk would step back to offset 0. It is simply not a block. A
9474        // footnote definition is always placed; it has a body to draw.
9475        assert!(!is_placed_definition(&Kind::Reference, &(0..0)));
9476        assert!(is_placed_definition(&Kind::Reference, &(7..14)));
9477        assert!(is_placed_definition(&Kind::Footnote, &(0..0)));
9478        assert!(!is_placed_definition(&Kind::Str, &(7..14)));
9479    }
9480
9481    #[test]
9482    fn the_trailing_gap_closes_the_last_block() {
9483        // Two Enters at the end of a document: a drawn gap, then the navigable
9484        // empty paragraph. Only the gap is labelled, so a frontend that shrinks
9485        // boundaries shrinks the spacer and leaves the row being typed on alone.
9486        let m = map("# Head\n\n\n");
9487        assert_eq!(
9488            boundaries(&m),
9489            vec![(BlockClass::Heading, BlockClass::Paragraph)]
9490        );
9491    }
9492
9493    #[test]
9494    fn only_the_drawn_gap_rows_carry_a_boundary() {
9495        let m = map("one\n\ntwo\n");
9496        for row in &m.rows {
9497            assert_eq!(
9498                row.boundary.is_some(),
9499                row.decoration,
9500                "a boundary is exactly a drawn gap row: {:?}",
9501                row.glyphs.iter().map(|g| g.ch).collect::<String>()
9502            );
9503        }
9504    }
9505
9506    #[test]
9507    fn preserve_flow_labels_no_boundary() {
9508        // Every blank line is a caret home there — somewhere text can go, not a
9509        // gap between blocks — so nothing is drawn-only and nothing is labelled.
9510        // A frontend keying its spacing off `boundary` can't shrink a row the
9511        // author is about to type on.
9512        let m = map_preserve("one\n\ntwo\n\n# Head\n", Some(80));
9513        assert!(boundaries(&m).is_empty());
9514    }
9515
9516    #[test]
9517    fn a_list_draws_no_boundary_between_its_items() {
9518        // Tight or loose, core puts no gap row between two items of one list —
9519        // so an item↔item boundary is a shape no frontend will ever be handed,
9520        // and spacing one is spacing something that isn't there.
9521        for src in ["- one\n- two\n", "- one\n\n- two\n"] {
9522            let m = map(src);
9523            assert!(
9524                boundaries(&m).is_empty(),
9525                "no gap row inside the list of {src:?}"
9526            );
9527        }
9528        // Leaving the list is an ordinary boundary, and the list is named as
9529        // what sits above it.
9530        let m = map("- one\n- two\n\npara\n");
9531        assert_eq!(
9532            boundaries(&m),
9533            vec![(BlockClass::List, BlockClass::Paragraph)]
9534        );
9535    }
9536
9537    #[test]
9538    fn a_nested_boundary_names_the_blocks_inside_the_container() {
9539        // Two paragraphs inside a blockquote are divided by a Paragraph↔Paragraph
9540        // boundary — the quote is the container they're both in, not what the gap
9541        // separates.
9542        let m = map("> one\n>\n> two\n");
9543        assert_eq!(
9544            boundaries(&m),
9545            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
9546        );
9547    }
9548
9549    #[test]
9550    fn a_directive_container_draws_one_boundary_like_every_other_block() {
9551        // A container's rows stop at its last *child*, so without anchoring
9552        // `last_off` past the closing `:::` the separator logic counted the fence
9553        // line as a blank row of its own and drew the gap twice — one authored
9554        // blank line, two boundaries, and a frontend spacing each of them put
9555        // double margin under every fenced div. The code-block arm anchors past
9556        // its ``` for exactly this reason; compare the two here.
9557        let fenced = map_directives(":::note\nin\n:::\n\ntwo\n");
9558        assert_eq!(
9559            boundaries(&fenced),
9560            vec![(BlockClass::Directive, BlockClass::Paragraph)],
9561            "one authored gap, one boundary row"
9562        );
9563        let code = map("```\nc\n```\n\ntwo\n");
9564        assert_eq!(
9565            boundaries(&code).len(),
9566            boundaries(&fenced).len(),
9567            "a fenced div spaces like a fenced code block"
9568        );
9569        // Nesting closes several fences at once; still one gap.
9570        let nested = map_directives(":::a\n:::b\nin\n:::\n:::\n\ntwo\n");
9571        assert_eq!(
9572            boundaries(&nested),
9573            vec![(BlockClass::Directive, BlockClass::Paragraph)]
9574        );
9575    }
9576
9577    #[test]
9578    fn a_block_media_names_itself_in_the_boundaries_either_side() {
9579        use BlockClass::*;
9580        // A block image is never a node of its own — `media_only` promotes the
9581        // *paragraph* wrapping it — so classifying the node the walk stands on
9582        // called the picture `Paragraph` and left `BlockClass::Media` unreachable:
9583        // a frontend could not give a photo more air than a line of prose.
9584        // `label_media_boundaries` reads it back off the finished rows instead.
9585        let m = map("one\n\n![alt](p.png)\n\ntwo\n");
9586        assert_eq!(boundaries(&m), vec![(Paragraph, Media), (Media, Paragraph)]);
9587        // At the edges of the document too: the leading gap has no boundary of
9588        // its own, and the trailing one is `emit_trailing_blank_lines`'.
9589        let edges = map("![a](p.png)\n\nmid\n\n![b](q.png)\n");
9590        assert_eq!(
9591            boundaries(&edges),
9592            vec![(Media, Paragraph), (Paragraph, Media)]
9593        );
9594        // One gap spelled with several rows — the row closing the block above and
9595        // the row opening the one below, with the author's spare blank line
9596        // navigable between them — carries the same pair on every drawn row.
9597        let roomy = map("one\n\n\n\n![alt](p.png)\n");
9598        assert_eq!(
9599            boundaries(&roomy),
9600            vec![(Paragraph, Media), (Paragraph, Media)]
9601        );
9602    }
9603
9604    #[test]
9605    fn a_block_video_is_media_at_its_boundaries_not_a_directive_panel() {
9606        // Worse than the image case before `label_media_boundaries`: a `<video>`
9607        // arrives as twig's generic `container`, which classifies `Directive` —
9608        // the one class a frontend reads as "draw a tinted panel here". A movie
9609        // got the chrome of a fenced div.
9610        let mut doc = crate::Doc::from_source(
9611            "one\n\n<video src=\"v.mp4\"></video>\n\ntwo\n".to_string(),
9612            Format::Markdown,
9613        )
9614        .unwrap();
9615        doc.build_visual(80);
9616        assert_eq!(
9617            boundaries(&doc.vmap),
9618            vec![
9619                (BlockClass::Paragraph, BlockClass::Media),
9620                (BlockClass::Media, BlockClass::Paragraph),
9621            ]
9622        );
9623    }
9624
9625    #[test]
9626    fn the_incremental_walk_labels_boundaries_like_the_full_one() {
9627        // `assert_maps_eq` compares boundaries too, so this pins the two doors
9628        // into `BlockClass::from_node_kind` — a `FlatNode`'s kind on the full
9629        // build, a query match's on the cached one — against a document with one
9630        // of every boundary in it.
9631        let src = "one\n\n# Head\n\ntwo\n\n- a\n- b\n\n> q\n\n```\nc\n```\n\npara\n";
9632        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
9633        let mut cache = BlockCache::default();
9634        let (full, cached) = render_both(&mut ed, src, Some(80), &mut cache);
9635        assert_maps_eq(&full, &cached, "boundary labelling");
9636        assert!(
9637            !boundaries(&full).is_empty(),
9638            "the fixture has boundaries to compare"
9639        );
9640    }
9641
9642    #[test]
9643    fn every_caret_stop_opens_a_cluster_of_its_row() {
9644        // The two ways of finding a cluster have to agree. `push_text` marks the
9645        // stops by segmenting one run of text; the column mapping segments the
9646        // whole row, decoration and all. A stop that came out as the *middle* of
9647        // some row-level cluster would be a caret with no column of its own —
9648        // drawn at the column of whatever swallowed it.
9649        let src = "# 標題\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` 你好\n\n\
9650                   - 項目 one\n- e\u{0301}dge\n\n> 引用 text\n\n\
9651                   | A | 值 |\n|---|---|\n| 你好 | 👩‍🚀 |\n";
9652        let m = map(src);
9653        for (r, row) in m.rows.iter().enumerate() {
9654            let openers: Vec<usize> = clusters(&row.glyphs).iter().map(|c| c.glyph).collect();
9655            for (i, g) in row.glyphs.iter().enumerate() {
9656                assert!(
9657                    !g.stop || openers.contains(&i),
9658                    "row {r}: the stop at glyph {i} ({:?}) is inside a cluster, \
9659                     so it is drawn at another glyph's column",
9660                    g.ch
9661                );
9662            }
9663        }
9664    }
9665
9666    // ── the presentation vocabulary ─────────────────────────────────────────
9667
9668    /// A block's own attributes, in the three formats that spell one on the
9669    /// block itself: HTML's tag, djot's `{…}` line, and — the odd one — a
9670    /// Markdown `<div>` around it, which is where twig has to put a Markdown
9671    /// block's attributes because the format has nowhere else.
9672    #[test]
9673    fn a_block_carries_its_alignment_on_every_row_it_draws() {
9674        // HTML, on the paragraph. `lead` is somebody else's class and is
9675        // neither read nor in the way.
9676        let html = map_leaf("<p class=\"lead center\">hi</p>\n", Format::Html);
9677        assert_eq!(line_facts(&html), vec![(Some(Align::Center), None)]);
9678
9679        // djot's attribute line, on the block.
9680        let dj = map_leaf("{.right}\nhi\n", Format::Djot);
9681        assert_eq!(line_facts(&dj), vec![(Some(Align::Right), None)]);
9682
9683        // A heading carries it too, and on every row a wrapped one draws.
9684        let h = map_leaf("{.center}\n# a heading\n", Format::Djot);
9685        assert_eq!(line_facts(&h), vec![(Some(Align::Center), None)]);
9686        assert_eq!(h.rows[0].heading, Some(1));
9687
9688        // Both keys at once, and the line spacing is read the same way.
9689        let both = map_leaf("{.justify data-line-height=\"1.5\"}\nhi\n", Format::Djot);
9690        assert_eq!(
9691            line_facts(&both),
9692            vec![(
9693                Some(Align::Justify),
9694                Some(LineHeight::Step(LineSpacing::OneHalf))
9695            )]
9696        );
9697
9698        // An unknown token is somebody else's and the block draws at the
9699        // theme's alignment; a ratio outside the menu's three is the author's
9700        // own and draws at exactly what they wrote.
9701        let other = map_leaf("{.lead data-line-height=\"1.3\"}\nhi\n", Format::Djot);
9702        assert_eq!(line_facts(&other), vec![(None, LineHeight::ratio(1.3))]);
9703
9704        // A value the grammar does not cover is neither: carried by the
9705        // document, drawn at the theme's spacing, and read as nothing at all.
9706        let em = map_leaf("{data-line-height=\"1.3em\"}\nhi\n", Format::Djot);
9707        assert_eq!(line_facts(&em), vec![(None, None)]);
9708    }
9709
9710    /// `<div class="center">` around three paragraphs centres all three, which
9711    /// is what the author of that HTML meant — and around one is the sole-child
9712    /// shape twig's `set_block_attrs` writes in Markdown.
9713    #[test]
9714    fn a_div_lends_its_alignment_to_every_block_inside_it() {
9715        let m = map_leaf(
9716            "<div class=\"center\" data-line-height=\"2\">\n\none\n\ntwo\n\n</div>\n",
9717            Format::Markdown,
9718        );
9719        assert_eq!(
9720            line_facts(&m),
9721            vec![
9722                (
9723                    Some(Align::Center),
9724                    Some(LineHeight::Step(LineSpacing::Double))
9725                ),
9726                (
9727                    Some(Align::Center),
9728                    Some(LineHeight::Step(LineSpacing::Double))
9729                ),
9730            ]
9731        );
9732
9733        // The nearer node wins, and the block after the div is untouched — the
9734        // context is restored, not left running.
9735        let nested = map_leaf(
9736            "<div class=\"center\">\n\n<div class=\"right\">\n\ninner\n\n</div>\n\nouter\n\n</div>\n\nafter\n",
9737            Format::Markdown,
9738        );
9739        assert_eq!(
9740            line_facts(&nested),
9741            vec![
9742                (Some(Align::Right), None),
9743                (Some(Align::Center), None),
9744                (None, None),
9745            ]
9746        );
9747    }
9748
9749    /// Size, face and colour are the run's, and the block's when the whole
9750    /// block is meant — read at both levels with the nearer winning.
9751    #[test]
9752    fn a_span_s_size_beats_its_block_s_and_its_face_falls_through() {
9753        // `<div data-font>` over `<p data-size>` over `<span data-size>`: the
9754        // span wins on size, the block is still what says the face.
9755        // The span is not first on its line: a `<span …>` opening one is an
9756        // HTML *block* to CommonMark, which is a fact about Markdown and not
9757        // about this.
9758        let m = map_leaf(
9759            "<div data-font=\"serif\">\n\nc <span data-size=\"small\">a</span> b\n\n</div>\n",
9760            Format::Markdown,
9761        );
9762        let a = style_of(&m, 'a');
9763        assert_eq!(a.size, Some(FontSize::Step(SizeStep::Small)));
9764        assert_eq!(a.font, Some(FaceRef::Generic(FontFamily::Serif)));
9765        // The text outside the span keeps the div's face and no size at all.
9766        let b = style_of(&m, 'b');
9767        assert_eq!(b.size, None);
9768        assert_eq!(b.font, Some(FaceRef::Generic(FontFamily::Serif)));
9769
9770        // djot spells the same span anonymously and it reads identically.
9771        let dj = map_leaf(
9772            "{data-size=\"large\"}\nx [y]{data-size=\"xx-large\" data-color=\"blue\"} z\n",
9773            Format::Djot,
9774        );
9775        assert_eq!(
9776            style_of(&dj, 'x').size,
9777            Some(FontSize::Step(SizeStep::Large))
9778        );
9779        assert_eq!(
9780            style_of(&dj, 'y').size,
9781            Some(FontSize::Step(SizeStep::XxLarge))
9782        );
9783        assert_eq!(
9784            style_of(&dj, 'y').color,
9785            Some(TextColor::Named(MarkColor::Blue))
9786        );
9787        // The block's size is still the block's outside the span.
9788        assert_eq!(
9789            style_of(&dj, 'z').size,
9790            Some(FontSize::Step(SizeStep::Large))
9791        );
9792        assert_eq!(style_of(&dj, 'z').color, None);
9793    }
9794
9795    /// The exact half of the vocabulary reaches a glyph and a row by the same
9796    /// doors the names do — the fold has one rule, not one per form. A named
9797    /// family is the one that cannot ride the glyph as itself: the walker
9798    /// interns it and the glyph carries the id.
9799    #[test]
9800    fn an_exact_size_face_and_colour_reach_the_glyph_and_the_row() {
9801        let m = map_leaf(
9802            "<div data-line-height=\"1.3\">\n\nc <span data-size=\"14pt\" \
9803             data-color=\"#c03030\" data-font=\"Garamond\">a</span> b\n\n</div>\n",
9804            Format::Markdown,
9805        );
9806        let a = style_of(&m, 'a');
9807        assert_eq!(a.size, FontSize::points(14.0));
9808        assert_eq!(
9809            a.color,
9810            Some(TextColor::Rgb {
9811                r: 0xc0,
9812                g: 0x30,
9813                b: 0x30
9814            })
9815        );
9816        assert_eq!(a.font, Some(FaceRef::Named(FaceId::of("Garamond"))));
9817        assert_eq!(m.face_name(FaceId::of("Garamond")), Some("Garamond"));
9818        // The div's ratio is the row's, on every row the block draws.
9819        assert_eq!(line_facts(&m), vec![(None, LineHeight::ratio(1.3))]);
9820        // And the text outside the span has none of the span's three.
9821        let b = style_of(&m, 'b');
9822        assert_eq!((b.size, b.font, b.color), (None, None, None));
9823
9824        // One name, one entry, however many spans wear it — the table is what
9825        // keeps a `Style` `Copy` and it should not grow per run.
9826        let twice = map_leaf(
9827            "x <span data-font=\"Garamond\">a</span> y <span data-font=\"Garamond\">b</span>\n",
9828            Format::Markdown,
9829        );
9830        assert_eq!(twice.faces().len(), 1);
9831        assert_eq!(
9832            style_of(&twice, 'a').font,
9833            style_of(&twice, 'b').font,
9834            "one family, one id"
9835        );
9836
9837        // A generic needs no entry at all: it names itself.
9838        let generic = map_leaf(
9839            "<div data-font=\"serif\">\n\nhi\n\n</div>\n",
9840            Format::Markdown,
9841        );
9842        assert_eq!(
9843            style_of(&generic, 'h').font,
9844            Some(FaceRef::Generic(FontFamily::Serif))
9845        );
9846        assert!(generic.faces().is_empty());
9847    }
9848
9849    /// The one key two nodes share. `data-color` on a `mark` is the highlight's
9850    /// *background* and reaches a glyph through [`Role::Mark`]; the same key on
9851    /// an attributed span is the text's foreground. Same vocabulary, same enum,
9852    /// no collision — and a mark inside a coloured span wears both.
9853    #[test]
9854    fn a_mark_keeps_its_highlight_colour_and_a_span_colours_the_text() {
9855        let m = map_leaf("a ==\u{1f534} red== b\n", Format::Markdown);
9856        let r = style_of(&m, 'r');
9857        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)));
9858        assert_eq!(r.color, None, "a highlight is not a text colour");
9859
9860        let both = map_leaf(
9861            "<span data-color=\"blue\">a ==\u{1f534} red== b</span>\n",
9862            Format::Markdown,
9863        );
9864        let r = style_of(&both, 'r');
9865        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)), "the highlight");
9866        assert_eq!(
9867            r.color,
9868            Some(TextColor::Named(MarkColor::Blue)),
9869            "the letters"
9870        );
9871    }
9872
9873    /// A page break is the `::page-break` leaf directive, and djot spells the
9874    /// same document as an empty `::: page-break` fence whose name comes back
9875    /// as a class, HTML as a `<page-break>` element and AsciiDoc as `<<<`. All
9876    /// four draw the placeholder row every leaf directive gets and carry the
9877    /// same [`DirectiveMark`], because a frontend that opens a page at one
9878    /// must not be able to tell which format the file is in.
9879    #[test]
9880    fn a_page_break_reads_the_same_in_every_format() {
9881        for (fmt, src) in [
9882            (Format::Markdown, "a\n\n::page-break\n\nb\n"),
9883            (Format::Djot, "a\n\n::: page-break\n:::\n\nb\n"),
9884            (
9885                Format::Html,
9886                "<p>a</p>\n\n<page-break></page-break>\n\n<p>b</p>\n",
9887            ),
9888            (Format::Asciidoc, "a\n\n<<<\n\nb\n"),
9889        ] {
9890            let m = map_leaf(src, fmt);
9891            let marks: Vec<&DirectiveMark> = m
9892                .rows
9893                .iter()
9894                .filter_map(|r| r.leaf_directive.as_ref())
9895                .collect();
9896            assert_eq!(marks.len(), 1, "{fmt:?} draws one placeholder");
9897            assert_eq!(marks[0].name, "page-break", "{fmt:?}");
9898            assert!(marks[0].attrs.is_empty(), "{fmt:?}: {:?}", marks[0].attrs);
9899            assert!(
9900                m.rows
9901                    .iter()
9902                    .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>()
9903                        == "\u{29c9} page-break"),
9904                "{fmt:?} draws the label, got {:?}",
9905                m.rows
9906                    .iter()
9907                    .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
9908                    .collect::<Vec<_>>()
9909            );
9910        }
9911
9912        // A Markdown `:::note` with nothing in it is *not* this: its name is
9913        // its own, and nothing about it says "a block with no body" the way
9914        // djot's spelling of a leaf directive does.
9915        let empty_fence = map_leaf("::: note\n:::\n", Format::Markdown);
9916        assert!(
9917            empty_fence.rows.iter().all(|r| r.leaf_directive.is_none()),
9918            "a named empty fence keeps the reading it has"
9919        );
9920    }
9921
9922    /// A djot fence carrying more than its name keeps the rest as an attribute
9923    /// rather than folding it into the name: the *first* class token is the
9924    /// name, because that is where `insert_directive` puts it.
9925    #[test]
9926    fn a_djot_fence_s_first_class_is_the_directive_s_name_and_the_rest_is_attributes() {
9927        let m = map_leaf("{.page-break .wide}\n:::\n:::\n", Format::Djot);
9928        let mark = m
9929            .rows
9930            .iter()
9931            .find_map(|r| r.leaf_directive.as_ref())
9932            .expect("a placeholder");
9933        assert_eq!(mark.name, "page-break");
9934        assert_eq!(
9935            mark.attrs,
9936            vec![("class".to_string(), Some("wide".to_string()))]
9937        );
9938    }
9939
9940    // ── math ─────────────────────────────────────────────────────────────────
9941
9942    /// [`map_leaf`] on a chosen surface and reveal — the whole of what a math
9943    /// rendering turns on.
9944    fn map_math(src: &str, format: Format, surface: &Surface, reveal: Option<Reveal>) -> VisualMap {
9945        let mut ed =
9946            Editor::new_ext(src.as_bytes(), format, crate::doc::parse_extensions()).unwrap();
9947        build(&ed.nodes().unwrap(), src, Some(80), false, surface, reveal)
9948    }
9949
9950    fn pictures() -> Surface {
9951        Surface {
9952            inline_pictures: true,
9953            ..Default::default()
9954        }
9955    }
9956
9957    #[test]
9958    fn markdown_reads_math_and_a_dollar_before_whitespace_stays_prose() {
9959        // The `math` extension is on for every leaf document; twig's own rule
9960        // keeps a price out of it.
9961        let m = map_leaf("Say $E = mc^2$ for $5 and $6.\n", Format::Markdown);
9962        assert_eq!(row_texts(&m), vec!["Say E = mc^2 for $5 and $6."]);
9963        let e = m.rows[0].glyphs.iter().find(|g| g.ch == 'E').unwrap();
9964        assert_eq!(
9965            e.style.role,
9966            Role::Code,
9967            "the formula's TeX, in the code style"
9968        );
9969        assert_eq!(e.src, 5, "at its own byte, past the `$`");
9970        let five = m.rows[0].glyphs.iter().find(|g| g.ch == '5').unwrap();
9971        assert_eq!(five.style.role, Role::Body);
9972        assert!(m.math.is_empty(), "no picture stands in on a plain surface");
9973    }
9974
9975    #[test]
9976    fn a_plain_surface_draws_inline_math_as_code_with_the_delimiters_hidden() {
9977        // The verbatim treatment, in both languages — what `inline_math` always
9978        // rendered as — with the caret's home at the content's end.
9979        for (src, fmt) in [
9980            ("a $x+y$ b\n", Format::Markdown),
9981            ("a $`x+y` b\n", Format::Djot),
9982        ] {
9983            let m = map_leaf(src, fmt);
9984            assert_eq!(row_texts(&m), vec!["a x+y b"], "{src:?}");
9985            let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
9986            assert_eq!(x.style.role, Role::Code);
9987            assert!(!m.mark_ends.is_empty(), "the content end is a caret home");
9988        }
9989    }
9990
9991    #[test]
9992    fn display_math_in_a_line_of_prose_puts_its_text_at_the_text_s_own_offset() {
9993        // `display_math` had no arm and fell to the default one, which pushed
9994        // the text at the *node's* start: three bytes short in djot, past `$$`
9995        // and the backtick.
9996        let m = map_leaf("Before $$`x`$$ after\n", Format::Djot);
9997        let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
9998        assert_eq!(x.src, "Before $$`".len());
9999        assert_eq!(x.style.role, Role::Code);
10000        let m = map_leaf("Before $$x$$ after\n", Format::Markdown);
10001        let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
10002        assert_eq!(x.src, "Before $$".len());
10003    }
10004
10005    #[test]
10006    fn a_surface_that_paints_in_a_line_gets_one_atom_per_inline_formula() {
10007        let src = "Say $E = mc^2$ and $a$.\n";
10008        let m = map_math(src, Format::Markdown, &pictures(), None);
10009        assert_eq!(row_texts(&m), vec!["Say ∑ and ∑."]);
10010        assert_eq!(m.math.len(), 2);
10011        let first = &m.math[0];
10012        assert_eq!(first.tex, "E = mc^2");
10013        assert!(!first.display);
10014        assert_eq!(first.row, 0);
10015        assert_eq!(first.rows_span, 0..1);
10016        assert_eq!(first.glyph, Some(4));
10017        assert_eq!(first.src, 4, "the formula's start, where a click lands");
10018        let atom = &m.rows[0].glyphs[4];
10019        assert_eq!(atom.ch, MATH_ATOM);
10020        assert_eq!(atom.style.role, Role::Math);
10021        assert!(atom.stop);
10022        assert_eq!(atom.src, 4);
10023        // The caret has a stop on the atom and the next glyph's past it, and
10024        // nothing inside the markup.
10025        assert_eq!(m.stop_after(4), Some("Say $E = mc^2$".len()));
10026        assert!(m.mark_ends.is_empty(), "no home inside the hidden markup");
10027        // The row carries the marks the side-table is derived from.
10028        assert_eq!(m.rows[0].math.len(), 2);
10029        assert_eq!(m.rows[0].math[1].glyph, Some(m.math[1].glyph.unwrap()));
10030        assert_eq!(m.math[1].tex, "a");
10031    }
10032
10033    #[test]
10034    fn a_display_formula_written_inline_is_an_atom_in_display_style() {
10035        let m = map_math("Before $$x$$ after\n", Format::Markdown, &pictures(), None);
10036        assert_eq!(row_texts(&m), vec!["Before ∑ after"]);
10037        assert_eq!(m.math.len(), 1);
10038        assert!(m.math[0].display);
10039        assert_eq!(m.math[0].tex, "x");
10040    }
10041
10042    #[test]
10043    fn an_atom_follows_its_glyph_across_a_wrap() {
10044        // Fifteen words, then a formula that wraps onto the second row: the
10045        // mark is drained onto the row the glyph landed on, at its index there.
10046        let src = format!("{}$x$ end\n", "word ".repeat(15));
10047        let mut ed = Editor::new_ext(
10048            src.as_bytes(),
10049            Format::Markdown,
10050            crate::doc::parse_extensions(),
10051        )
10052        .unwrap();
10053        let m = build(
10054            &ed.nodes().unwrap(),
10055            &src,
10056            Some(40),
10057            false,
10058            &pictures(),
10059            None,
10060        );
10061        assert!(m.rows.len() >= 2);
10062        assert_eq!(m.math.len(), 1);
10063        let info = &m.math[0];
10064        let g = &m.rows[info.row].glyphs[info.glyph.unwrap()];
10065        assert_eq!(g.ch, MATH_ATOM);
10066        assert_eq!(g.src, src.find("$x$").unwrap());
10067        assert!(m.rows[..info.row].iter().all(|r| r.math.is_empty()));
10068    }
10069
10070    #[test]
10071    fn an_atom_in_a_table_cell_rides_the_cell_s_row() {
10072        let m = map_math(
10073            "| a | b |\n|---|---|\n| $x$ | c |\n",
10074            Format::Markdown,
10075            &pictures(),
10076            None,
10077        );
10078        assert_eq!(m.math.len(), 1);
10079        let info = &m.math[0];
10080        assert_eq!(m.rows[info.row].glyphs[info.glyph.unwrap()].ch, MATH_ATOM);
10081    }
10082
10083    #[test]
10084    fn a_display_formula_on_its_own_lines_is_a_block_placeholder_on_every_surface() {
10085        for (src, fmt) in [
10086            (
10087                "intro\n\n$$\n\\int_0^1 x\\,dx\n$$\n\nend\n",
10088                Format::Markdown,
10089            ),
10090            ("intro\n\n$$`\\int_0^1 x\\,dx`\n\nend\n", Format::Djot),
10091        ] {
10092            for surface in [Surface::default(), pictures()] {
10093                let m = map_math(src, fmt, &surface, None);
10094                assert_eq!(
10095                    row_texts(&m),
10096                    vec!["intro", "", "∑ \\int_0^1 x\\,dx", "", "end"],
10097                    "{src:?}"
10098                );
10099                assert_eq!(m.math.len(), 1);
10100                let info = &m.math[0];
10101                assert!(info.display);
10102                assert_eq!(info.glyph, None, "a block, not an atom");
10103                assert_eq!(info.rows_span, 2..3);
10104                assert_eq!(info.tex.trim(), "\\int_0^1 x\\,dx");
10105                let start = src.find("$$").unwrap();
10106                let end = start + src[start..].find("\n\nend").unwrap();
10107                assert_eq!(info.src, start);
10108                // Every label glyph at the formula's start, a stop there and
10109                // one past the block, nothing inside — a picture's two homes.
10110                let row = &m.rows[2];
10111                assert!(
10112                    row.glyphs
10113                        .iter()
10114                        .all(|g| g.src == start && g.style.role == Role::Math)
10115                );
10116                assert_eq!(row.end_src, end);
10117                assert_eq!(m.stop_after(start), Some(end));
10118                assert_eq!(m.stop_before(end), Some(start));
10119                // The gaps either side are labelled as a formula's.
10120                assert_eq!(m.rows[1].boundary.map(|b| b.below), Some(BlockClass::Math));
10121                assert_eq!(m.rows[3].boundary.map(|b| b.above), Some(BlockClass::Math));
10122            }
10123        }
10124    }
10125
10126    #[test]
10127    fn a_display_block_reserves_the_rows_the_frontend_measured() {
10128        let src = "$$\nx\n$$\n\nend\n";
10129        let surface = Surface {
10130            math_rows: HashMap::from([("\nx\n".to_string(), 4)]),
10131            ..Default::default()
10132        };
10133        let m = map_math(src, Format::Markdown, &surface, None);
10134        assert_eq!(m.math[0].rows_span, 0..4);
10135        assert_eq!(row_texts(&m)[..5], ["∑ x", "", "", "", ""]);
10136        // The fillers are decoration: drawn, no caret, anchored past the block.
10137        for r in &m.rows[1..4] {
10138            assert!(r.decoration);
10139            assert_eq!(r.end_src, 7);
10140        }
10141        assert_eq!(m.stop_after(0), Some(7));
10142        // A height keyed by TeX that does not match reserves nothing.
10143        let surface = Surface {
10144            math_rows: HashMap::from([("x".to_string(), 4)]),
10145            ..Default::default()
10146        };
10147        let m = map_math(src, Format::Markdown, &surface, None);
10148        assert_eq!(m.math[0].rows_span, 0..1);
10149    }
10150
10151    #[test]
10152    fn a_paragraph_with_prose_beside_a_display_formula_is_not_a_block() {
10153        let m = map_math("see\n$$\nx\n$$\n", Format::Markdown, &pictures(), None);
10154        assert!(
10155            m.math.iter().all(|i| i.glyph.is_some()),
10156            "an atom, not a placeholder"
10157        );
10158        let m = map_math(
10159            "$$\nx\n$$\n$$\ny\n$$\n",
10160            Format::Markdown,
10161            &pictures(),
10162            None,
10163        );
10164        assert_eq!(m.math.len(), 2);
10165        assert!(
10166            m.math.iter().all(|i| i.glyph.is_some()),
10167            "two formulas is prose with math in it"
10168        );
10169    }
10170
10171    #[test]
10172    fn a_formula_on_the_reveal_line_is_its_tex_in_every_mode() {
10173        let src = "Say $E = mc^2$ here.\n";
10174        // The hidden modes' reveal: only the formula shows its markup.
10175        let m = map_math(
10176            src,
10177            Format::Markdown,
10178            &pictures(),
10179            Some(Reveal::math(0..src.len() - 1)),
10180        );
10181        assert_eq!(row_texts(&m), vec!["Say $E = mc^2$ here."]);
10182        assert!(
10183            m.math.is_empty(),
10184            "nothing stands in for a revealed formula"
10185        );
10186        let dollar = m.rows[0].glyphs.iter().find(|g| g.ch == '$').unwrap();
10187        assert_eq!(dollar.style.role, Role::Delimiter);
10188        let e = m.rows[0].glyphs.iter().find(|g| g.ch == 'E').unwrap();
10189        assert_eq!(e.style.role, Role::Code);
10190        // Full's reveal draws the same, and an emphasis beside it reveals too
10191        // where the hidden modes' does not.
10192        let src = "*a* $x$\n";
10193        let hidden = map_math(
10194            src,
10195            Format::Markdown,
10196            &pictures(),
10197            Some(Reveal::math(0..src.len() - 1)),
10198        );
10199        assert_eq!(row_texts(&hidden), vec!["a $x$"]);
10200        let full = map_math(
10201            src,
10202            Format::Markdown,
10203            &pictures(),
10204            Some(Reveal::full(0..src.len() - 1)),
10205        );
10206        assert_eq!(row_texts(&full), vec!["*a* $x$"]);
10207        // A reveal line that does not meet the formula leaves the atom.
10208        let other = map_math(
10209            "$x$\n\ntext\n",
10210            Format::Markdown,
10211            &pictures(),
10212            Some(Reveal::math(5..9)),
10213        );
10214        assert_eq!(row_texts(&other)[0], "∑");
10215    }
10216
10217    #[test]
10218    fn a_display_block_on_the_reveal_line_is_its_source_lines_in_the_code_style() {
10219        let src = "intro\n\n$$\n\\int_0^1 x\n$$\n\nend\n";
10220        // Any line of the block reveals the whole of it: here the middle one.
10221        let mid = src.find("\\int").unwrap();
10222        let line = mid..mid + "\\int_0^1 x".len();
10223        let m = map_math(src, Format::Markdown, &pictures(), Some(Reveal::math(line)));
10224        assert_eq!(
10225            row_texts(&m),
10226            vec!["intro", "", "$$", "\\int_0^1 x", "$$", "", "end"]
10227        );
10228        assert!(m.math.is_empty());
10229        let fence = m.rows[2].glyphs.iter().find(|g| g.ch == '$').unwrap();
10230        assert_eq!(fence.style.role, Role::Delimiter);
10231        assert_eq!(fence.src, 7);
10232        let x = m.rows[3].glyphs.iter().find(|g| g.ch == 'x').unwrap();
10233        assert_eq!(x.style.role, Role::Code);
10234        assert_eq!(x.src, src.find("x\n$$").unwrap());
10235        // Every byte of the source is reachable: a stop on each fence and each
10236        // character between.
10237        assert!(m.is_stop(7));
10238        assert!(m.is_stop(mid));
10239        // The closing fence's line too, and the same for djot.
10240        let close = src.rfind("$$").unwrap();
10241        let m = map_math(
10242            src,
10243            Format::Markdown,
10244            &pictures(),
10245            Some(Reveal::math(close..close + 2)),
10246        );
10247        assert_eq!(row_texts(&m)[2], "$$");
10248        let src = "$$`\n\\int\n`\n";
10249        let m = map_math(src, Format::Djot, &pictures(), Some(Reveal::math(4..8)));
10250        assert_eq!(row_texts(&m), vec!["$$`", "\\int", "`"]);
10251    }
10252
10253    #[test]
10254    fn a_block_that_holds_a_formula_says_so_to_the_cache() {
10255        let src = "plain\n\nwith $x$ in it\n\n$$\ny\n$$\n";
10256        let mut ed = Editor::new_ext(
10257            src.as_bytes(),
10258            Format::Markdown,
10259            crate::doc::parse_extensions(),
10260        )
10261        .unwrap();
10262        let mut cache = BlockCache::default();
10263        let top = top_blocks(&mut ed);
10264        let _ = build_cached(
10265            &top,
10266            src,
10267            None,
10268            false,
10269            &pictures(),
10270            None,
10271            &mut cache,
10272            |id| ed.subtree(NodeId(id)).unwrap_or_default(),
10273        );
10274        assert!(!cache.math_meets(&(0..5)), "the plain paragraph");
10275        assert!(cache.math_meets(&(7..21)), "the one with an atom");
10276        assert!(
10277            cache.math_meets(&(26..27)),
10278            "the middle line of the display block"
10279        );
10280        // A hit carries the answer without a walk: build again from the cache.
10281        let _ = build_cached(
10282            &top,
10283            src,
10284            None,
10285            false,
10286            &pictures(),
10287            None,
10288            &mut cache,
10289            |_| Vec::new(),
10290        );
10291        assert!(cache.math_meets(&(7..21)));
10292        assert!(!cache.math_meets(&(0..5)));
10293    }
10294
10295    #[test]
10296    fn incremental_builds_agree_with_the_reference_on_math() {
10297        for src in [
10298            "a $x$ b\n\n$$\ny\n$$\n\nc\n",
10299            "one\n\ntwo $\\frac{a}{b}$ three\n",
10300            "$$\n\\int\n$$\n",
10301        ] {
10302            for surface in [Surface::default(), pictures()] {
10303                let mut ed = Editor::new_ext(
10304                    src.as_bytes(),
10305                    Format::Markdown,
10306                    crate::doc::parse_extensions(),
10307                )
10308                .unwrap();
10309                let all = ed.nodes().unwrap();
10310                let plain = build(&all, src, Some(80), false, &surface, None);
10311                let mut cache = BlockCache::default();
10312                let top = top_blocks(&mut ed);
10313                let cached = build_cached(
10314                    &top,
10315                    src,
10316                    Some(80),
10317                    false,
10318                    &surface,
10319                    None,
10320                    &mut cache,
10321                    |id| ed.subtree(NodeId(id)).unwrap_or_default(),
10322                );
10323                assert_eq!(row_texts(&plain), row_texts(&cached), "{src:?}");
10324                assert_eq!(plain.math, cached.math, "{src:?}");
10325                assert_eq!(plain.stops, cached.stops, "{src:?}");
10326            }
10327        }
10328    }
10329}