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/// Shared by the WYSIWYG builder (to label the box) and [`crate::Doc`] (to edit
1484/// the label through a prompt), so the two agree on where the language lives.
1485pub fn code_info_span(source: &str, block_start: usize) -> Option<Range<usize>> {
1486    let rest = source.get(block_start..)?;
1487    let line_len = rest.find('\n').unwrap_or(rest.len());
1488    let line = &rest[..line_len];
1489    // A fence may be indented up to three spaces; past that it opens with a run
1490    // of the same fence character.
1491    let indent = line.len() - line.trim_start().len();
1492    if indent > 3 {
1493        return None;
1494    }
1495    let fence = line[indent..].chars().next()?;
1496    if fence != '`' && fence != '~' {
1497        return None; // an indented block, not a fenced one
1498    }
1499    let fence_len = line[indent..].chars().take_while(|&c| c == fence).count();
1500    let info_start = block_start + indent + fence_len;
1501    Some(info_start..block_start + line_len)
1502}
1503
1504/// A fenced code block's language for display: its info string, trimmed, or
1505/// `None` when there's no fence or the fence carries no language. The trimmed
1506/// text is what a frontend labels the box with; [`code_info_span`] is what an
1507/// edit replaces.
1508pub fn code_language(source: &str, block_start: usize) -> Option<String> {
1509    let span = code_info_span(source, block_start)?;
1510    let text = source.get(span)?.trim();
1511    (!text.is_empty()).then(|| text.to_string())
1512}
1513
1514/// A horizontal rule's dash count when the map isn't wrapping to a column grid
1515/// (the GUI, which wraps at pixel width): a fixed, sane width the frontend can
1516/// paint or re-wrap, instead of a runaway count from an unbounded wrap width.
1517const UNWRAPPED_RULE_WIDTH: usize = 40;
1518
1519/// The one glyph an inline formula renders to on a surface that paints
1520/// pictures in a line — what a plain surface handed such a map would show.
1521/// One column wide, so a column-wrapped build's arithmetic still holds; the
1522/// frontend that asked for atoms draws the picture as wide as it is.
1523const MATH_ATOM: char = '∑';
1524
1525/// What the surface a map is built for can paint, and how tall its pictures
1526/// came out — the things about a frontend that change the rows core lays
1527/// down, gathered from the frontend by [`crate::Doc`] and threaded into every
1528/// build. The defaults are the plain surface: nothing painted in a line, every
1529/// picture a one-row placeholder, which is what every test that passes
1530/// `Surface::default()` gets and what every build got before there was one.
1531#[derive(Clone, Debug, Default, PartialEq, Eq)]
1532pub struct Surface {
1533    /// How many visual rows each block image reserves, keyed by its
1534    /// destination — the frontend's per-image height, set through
1535    /// [`crate::Doc::set_media_rows`] so [`Builder::block_media`] can size the
1536    /// placeholder without core doing any I/O. A destination absent from the
1537    /// map (or a `0`/`1` entry) reserves the bare one-row placeholder.
1538    pub media_rows: HashMap<String, usize>,
1539    /// The same for each display formula, keyed by its TeX verbatim (the
1540    /// [`MathMark::tex`] a frontend was handed) — set through
1541    /// [`crate::Doc::set_math_rows`] once the frontend has typeset and
1542    /// measured the picture.
1543    pub math_rows: HashMap<String, usize>,
1544    /// Whether the surface can paint a picture *inside* a line of text, so an
1545    /// inline formula may render to one atom glyph it draws over
1546    /// ([`MathInfo`]). A pixel-laid-out frontend says yes; a terminal cannot
1547    /// composite an image over one cell, and leaves this off to keep an inline
1548    /// formula as the code-styled TeX it always showed. Off by default.
1549    pub inline_pictures: bool,
1550}
1551
1552/// The one source line rendering its markup raw — the caret's, when the mode
1553/// or the content asks for it — and how much of the markup that means. See
1554/// [`crate::Doc::reveal_line`], which decides both.
1555///
1556/// Two grades because two things ask. Under
1557/// [`MarkupMode::Full`](crate::MarkupMode::Full) *every* delimiter on the line
1558/// comes back (`markup: true`). In the two hidden modes a formula still
1559/// reveals — its content is its TeX and not its picture, so hiding is not
1560/// enough — and the line is threaded through with `markup: false`: a math node
1561/// meeting it shows its source, and an emphasis meeting it hides its
1562/// asterisks as it always did.
1563#[derive(Clone, Debug, PartialEq, Eq)]
1564pub struct Reveal {
1565    /// The source byte range of the line, newline excluded — empty but present
1566    /// on a blank line.
1567    pub line: Range<usize>,
1568    /// Whether ordinary inline markup reveals on it too, or only math.
1569    pub markup: bool,
1570}
1571
1572impl Reveal {
1573    /// The caret's line under `MarkupMode::Full`: everything on it reveals.
1574    pub fn full(line: Range<usize>) -> Self {
1575        Reveal { line, markup: true }
1576    }
1577
1578    /// The caret's line in a hidden mode, where only a formula reveals.
1579    pub fn math(line: Range<usize>) -> Self {
1580        Reveal {
1581            line,
1582            markup: false,
1583        }
1584    }
1585
1586    /// Whether `span` meets this line — the test every arm that reveals runs.
1587    ///
1588    /// Touching at an endpoint counts: an emphasis ending exactly where the
1589    /// line does is on that line, and a zero-length reveal range (the caret
1590    /// alone on a blank line) still meets a node that starts there. The test
1591    /// is deliberately generous — the failure it avoids is revealing one
1592    /// delimiter of a pair while hiding the other, which looks like corruption
1593    /// rather than like markup.
1594    fn meets(&self, span: &Range<usize>) -> bool {
1595        span.start <= self.line.end && self.line.start <= span.end
1596    }
1597}
1598
1599/// Render the document to a [`VisualMap`]. `wrap` is the column budget for
1600/// word-wrapping (`Some` for the monospace TUI), or `None` to emit one row per
1601/// block — the GUI does its own proportional pixel wrapping over these rows.
1602/// Text and offsets come from the AST (`str` nodes carry the verbatim source
1603/// slice and an exact span), so the original source string isn't needed here.
1604pub fn build(
1605    nodes: &[FlatNode],
1606    source: &str,
1607    wrap: Option<usize>,
1608    preserve_soft: bool,
1609    surface: &Surface,
1610    reveal: Option<Reveal>,
1611) -> VisualMap {
1612    let Some(doc) = nodes.iter().position(|n| n.kind == Kind::Doc) else {
1613        return VisualMap::default();
1614    };
1615    let top = top_level(nodes, doc);
1616    let mut b = Builder {
1617        nodes,
1618        source,
1619        wrap: wrap.map(|w| w.max(8)),
1620        rows: Vec::new(),
1621        tables: Vec::new(),
1622        last_off: 0,
1623        stepped_over: 0,
1624        surface,
1625        break_glyph: Cell::new(' '),
1626        preserve_soft,
1627        reveal: reveal.clone(),
1628        pending_mark_ends: RefCell::new(Vec::new()),
1629        pending_math: RefCell::new(Vec::new()),
1630        saw_math: Cell::new(false),
1631        presentation: Presentation::default(),
1632        faces: RefCell::new(FaceTable::default()),
1633    };
1634    let last_drawn = b.top_blocks(&top);
1635    // The hidden frontmatter's end is the baseline for both the trailing blank
1636    // rows and the caret floor — see [`hidden_prefix_end`]. `top_level` has
1637    // already dropped every `metadata` child, so read it off the arena.
1638    let hidden_end = hidden_prefix_end(source, metadata_end_of(nodes, doc));
1639    b.emit_trailing_blank_lines(last_drawn.unwrap_or(BlockClass::Paragraph), hidden_end);
1640    let content_start = top.first().map_or(hidden_end, |&i| nodes[i].span.start);
1641    let stops = collect_stops(&b.rows);
1642    let mark_ends = collect_mark_ends(&b.rows);
1643    label_media_boundaries(&mut b.rows);
1644    let code_blocks = code_block_spans(&b.rows);
1645    let media = media_spans(&b.rows);
1646    let directives = directive_spans(&b.rows);
1647    let math = math_spans(&b.rows);
1648    VisualMap {
1649        rows: b.rows,
1650        content_start,
1651        stops,
1652        mark_ends,
1653        tables: b.tables,
1654        code_blocks,
1655        media,
1656        directives,
1657        math,
1658        faces: b.faces.into_inner(),
1659        spelling: OnceLock::new(),
1660    }
1661}
1662
1663/// Like [`build`], but reuses a persistent [`BlockCache`] so an edit re-renders
1664/// only the top-level blocks whose source bytes changed *and* marshals only
1665/// those blocks from twig instead of the whole arena.
1666///
1667/// `top` is the document's top-level blocks — twig's `child_spans` of the doc
1668/// root: `(node_id, kind, span)` for each, in order. `fetch_subtree(node_id)`
1669/// marshals one block's subtree (local-indexed, root at 0) and is called *only*
1670/// for a block that missed the cache, i.e. one that actually changed. So a
1671/// keystroke marshals one small subtree, not ~20k nodes. The result is
1672/// byte-for-byte identical to [`build`] on the same document (the
1673/// `build_cached_matches_build` test pins this); [`build`] stays the cache-free,
1674/// whole-arena reference. This is the entry point [`crate::Doc`] uses.
1675// One builder, and every one of these is a distinct input to the same layout
1676// pass — a struct of them would be built at the one call site and unpacked
1677// here, which is the same arguments with an extra name in the way.
1678#[allow(clippy::too_many_arguments)]
1679pub fn build_cached(
1680    top: &[QueryMatch],
1681    source: &str,
1682    wrap: Option<usize>,
1683    preserve_soft: bool,
1684    surface: &Surface,
1685    reveal: Option<Reveal>,
1686    cache: &mut BlockCache,
1687    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
1688) -> VisualMap {
1689    let wrap = wrap.map(|w| w.max(8));
1690
1691    // Wrapping is a function of the width, so a width change makes every cached
1692    // row's wrap wrong: start the cache over.
1693    if cache.wrap != Some(wrap) {
1694        cache.entries.clear();
1695        cache.wrap = Some(wrap);
1696    }
1697    cache.generation = cache.generation.wrapping_add(1);
1698
1699    // Frontmatter (a leading `metadata` block) is document metadata, not prose:
1700    // hidden in the rich view exactly as [`Builder::blocks`] skips it.
1701    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
1702
1703    // The outer builder only accumulates rows/tables and spells block boundaries
1704    // — both a function of the source and `last_off`, never of a node array — so
1705    // it carries an empty `nodes`. Each changed block is rendered by a *fresh*
1706    // builder over that block's subtree.
1707    let mut b = Builder {
1708        nodes: &[],
1709        source,
1710        wrap,
1711        rows: Vec::new(),
1712        tables: Vec::new(),
1713        last_off: 0,
1714        stepped_over: 0,
1715        surface,
1716        break_glyph: Cell::new(' '),
1717        preserve_soft,
1718        reveal: reveal.clone(),
1719        pending_mark_ends: RefCell::new(Vec::new()),
1720        pending_math: RefCell::new(Vec::new()),
1721        saw_math: Cell::new(false),
1722        presentation: Presentation::default(),
1723        faces: RefCell::new(FaceTable::default()),
1724    };
1725
1726    // Record the per-block row decomposition as we go, so a later
1727    // [`build_spliced`] can patch one block without rebuilding the map.
1728    let mut layout_blocks: Vec<BlockLayout> = Vec::with_capacity(blocks.len());
1729    // The document's face table, assembled block by block: from the walk on a
1730    // miss, from what the entry stored on a hit. The outer builder walks no
1731    // attributes of its own (it spells boundaries), so it never adds to it.
1732    let mut faces = FaceTable::default();
1733    let mut all_shift_safe = true;
1734    // The class of the last block that drew anything: what the next separator
1735    // closes, and what the trailing blank lines close at the end. A hidden block
1736    // (a comment) never becomes it — see [`Builder::block_or_hidden`], whose
1737    // step-over this loop repeats for the incremental walk.
1738    let mut above: Option<BlockClass> = None;
1739    for block in &blocks {
1740        let start = block.span.start;
1741        let before_sep = b.rows.len();
1742        if let Some(above) = above {
1743            // This walker has no node arena at all (see the `nodes: &[]` above),
1744            // but a top-level query match carries its kind — the same string
1745            // `BlockClass::from_node_kind` classifies for the whole-arena walk, so
1746            // the incremental and full builds label a boundary identically.
1747            b.emit_separators_before(
1748                start,
1749                &[],
1750                true,
1751                Boundary {
1752                    above,
1753                    below: BlockClass::from_node_kind(&block.kind),
1754                },
1755            );
1756        }
1757        let after_sep = b.rows.len();
1758        let bytes = block_bytes(source, &block.span);
1759        let hash = block_hash(bytes);
1760        // How this block meets the reveal line, if at all — part of its cache
1761        // key, since the same bytes render differently on the caret's line.
1762        let rkey = reveal_key(&reveal, &block.span);
1763
1764        // Hit: clone the block's rows shifted to its current offset and restore
1765        // the (shifted) `last_off` so the next separator lands right — no marshal.
1766        // Only shift-safe blocks are ever cached, so a hit is safe by construction.
1767        let mut has_math = false;
1768        if let Some(hit) = cache.reuse(hash, bytes, &rkey) {
1769            faces.merge(&hit.faces);
1770            has_math = hit.has_math;
1771            let delta = start as isize - hit.built_start as isize;
1772            for row in &hit.rows {
1773                b.rows.push(shift_row(row, delta));
1774            }
1775            b.last_off = (hit.last_off as isize + delta) as usize;
1776            // `0` is a block that stepped over nothing, and no answer to shift.
1777            if hit.stepped_over > 0 {
1778                let stepped = (hit.stepped_over as isize + delta) as usize;
1779                b.stepped_over = b.stepped_over.max(stepped);
1780            }
1781        } else {
1782            // Miss: marshal just this block's subtree and render it. A subtree is
1783            // self-contained with local ids (root at 0) and absolute spans, so a
1784            // fresh builder over it produces the same rows the whole-arena path
1785            // would. An empty subtree (twig couldn't hand it back) renders nothing.
1786            let subtree = fetch_subtree(block.node_id);
1787            if !subtree.is_empty() {
1788                let mut sub = Builder {
1789                    nodes: &subtree,
1790                    source,
1791                    wrap,
1792                    rows: Vec::new(),
1793                    tables: Vec::new(),
1794                    last_off: 0,
1795                    stepped_over: 0,
1796                    surface,
1797                    break_glyph: Cell::new(' '),
1798                    preserve_soft,
1799                    reveal: reveal.clone(),
1800                    pending_mark_ends: RefCell::new(Vec::new()),
1801                    pending_math: RefCell::new(Vec::new()),
1802                    saw_math: Cell::new(false),
1803                    presentation: Presentation::default(),
1804                    faces: RefCell::new(FaceTable::default()),
1805                };
1806                sub.block(0, &[], &[]);
1807                // A block that drew nothing is stepped over, not stood on: its
1808                // `last_off` is its own end, so the separator after it counts
1809                // from there. The sub-builder started at 0 and never moved, and
1810                // 0 is where the next separator would otherwise count from —
1811                // every line of the document, as a blank row each.
1812                let last_off = if sub.rows.is_empty() {
1813                    block.span.end
1814                } else {
1815                    sub.last_off
1816                };
1817                let stepped_over = sub.stepped_over;
1818                b.stepped_over = b.stepped_over.max(stepped_over);
1819                // The names this block's glyph ids stand for. They go into the
1820                // document's table *and* into the cache entry, because a hit
1821                // re-emits these rows without walking an attribute again.
1822                let block_faces = sub.faces.into_inner();
1823                faces.merge(&block_faces);
1824                has_math = sub.saw_math.get();
1825                // Cache only a block that is table-free AND renders inside its own
1826                // span: those two are the conditions for reuse-by-shift to be
1827                // correct. A block failing either is re-rendered every build (a
1828                // fresh render always matches a fresh whole-document build).
1829                if sub.tables.is_empty() {
1830                    if rows_within(&sub.rows, &block.span) {
1831                        cache.store(
1832                            hash,
1833                            bytes,
1834                            start,
1835                            sub.rows.clone(),
1836                            last_off,
1837                            stepped_over,
1838                            rkey,
1839                            has_math,
1840                            block_faces,
1841                        );
1842                    }
1843                    b.rows.extend(sub.rows);
1844                } else {
1845                    // A table block is never cached; rebase its row-index
1846                    // bookkeeping onto the combined row vector and append.
1847                    let base = b.rows.len();
1848                    for t in &mut sub.tables {
1849                        t.rows_span = (t.rows_span.start + base)..(t.rows_span.end + base);
1850                    }
1851                    b.rows.extend(sub.rows);
1852                    b.tables.extend(sub.tables);
1853                }
1854                b.last_off = last_off;
1855            }
1856        }
1857        let content_rows = b.rows.len() - after_sep;
1858        let sep_rows = if content_rows == 0 {
1859            // Hidden: take back the separator drawn for it, so what stands
1860            // either side meets across one boundary. Its layout entry stays, at
1861            // no rows, so the splice arithmetic still counts one entry per block.
1862            b.rows.truncate(before_sep);
1863            // A cache hit restored the stored `last_off` above; an empty subtree
1864            // (twig couldn't hand it back) restored nothing. Either way the walk
1865            // stands past the block.
1866            b.last_off = b.last_off.max(block.span.end);
1867            b.stepped_over = b.stepped_over.max(block.span.end);
1868            0
1869        } else {
1870            above = Some(BlockClass::from_node_kind(&block.kind));
1871            all_shift_safe &= rows_within(&b.rows[after_sep..], &block.span);
1872            after_sep - before_sep
1873        };
1874        layout_blocks.push(BlockLayout {
1875            span: block.span.clone(),
1876            kind: block.kind.clone(),
1877            sep_rows,
1878            content_rows,
1879            has_math,
1880        });
1881    }
1882
1883    let before_trailing = b.rows.len();
1884    let hidden_end = hidden_prefix_end(
1885        source,
1886        top.iter()
1887            .filter(|m| m.kind == Kind::Metadata)
1888            .map(|m| m.span.end)
1889            .next_back(),
1890    );
1891    b.emit_trailing_blank_lines(above.unwrap_or(BlockClass::Paragraph), hidden_end);
1892    let trailing_rows = b.rows.len() - before_trailing;
1893
1894    // Evict every entry no block reused this build, so the cache tracks the
1895    // current document instead of growing without bound over a session.
1896    let g = cache.generation;
1897    cache.entries.retain(|_, bucket| {
1898        bucket.retain(|e| e.generation == g);
1899        !bucket.is_empty()
1900    });
1901
1902    cache.layout = Layout {
1903        blocks: layout_blocks,
1904        trailing_rows,
1905        built_len: source.len(),
1906        has_tables: !b.tables.is_empty(),
1907        all_shift_safe,
1908        reveal: reveal.clone(),
1909    };
1910
1911    // The first rendered offset is the first non-metadata block's start — the
1912    // analogue of [`first_content_offset`] for the top-level list. With nothing
1913    // but frontmatter it's the end of that frontmatter, and 0 for an empty
1914    // document ([`hidden_prefix_end`]).
1915    let content_start = blocks.first().map_or(hidden_end, |m| m.span.start);
1916    let stops = collect_stops(&b.rows);
1917    let mark_ends = collect_mark_ends(&b.rows);
1918    label_media_boundaries(&mut b.rows);
1919    let code_blocks = code_block_spans(&b.rows);
1920    let media = media_spans(&b.rows);
1921    let directives = directive_spans(&b.rows);
1922    let math = math_spans(&b.rows);
1923    VisualMap {
1924        rows: b.rows,
1925        content_start,
1926        stops,
1927        mark_ends,
1928        tables: b.tables,
1929        code_blocks,
1930        media,
1931        directives,
1932        math,
1933        faces,
1934        spelling: OnceLock::new(),
1935    }
1936}
1937
1938/// The fast path for a single-block edit: patch the previous [`VisualMap`] in
1939/// place rather than reassembling it. Returns `Some(new_map)` when it applies,
1940/// or `None` to tell the caller to fall back to [`build_cached`] (always
1941/// correct). Consumes `prev` either way — on `None` the caller rebuilds from
1942/// scratch and doesn't need it.
1943///
1944/// It applies only when `dirty` (twig's dirty byte range) falls inside exactly
1945/// one top-level block AND the block structure around it is unchanged — verified
1946/// by matching the new `top` list against the previous [`Layout`] block for
1947/// block: kinds unchanged, spans before the edit identical, spans after it
1948/// shifted by the byte delta, count unchanged. Any deviation — a block split or
1949/// merged, a fence opened to swallow later blocks, a table anywhere, a
1950/// multi-block edit — fails the match and returns `None`. That check is what
1951/// makes the byte-range trustworthy: twig's dirty range is exact about *bytes*
1952/// but silent about *reparse*, and the structural match catches the reparse
1953/// effects it can't see.
1954///
1955/// When it applies, the unchanged prefix rows move verbatim, the suffix rows
1956/// shift by the delta *in place* (integer adds, no glyph copy), and only the one
1957/// dirty block is re-marshalled and re-rendered; stops splice the same way by
1958/// offset. So the cost is O(rows after the edit), and nothing before the edit is
1959/// touched. The hash-keyed entry cache is left alone — a later [`build_cached`]
1960/// will miss on the changed block, re-render it, and evict the stale entry, so
1961/// chained splices neither corrupt nor grow it.
1962// One builder, and every one of these is a distinct input to the same layout
1963// pass — a struct of them would be built at the one call site and unpacked
1964// here, which is the same arguments with an extra name in the way.
1965#[allow(clippy::too_many_arguments)]
1966pub fn build_spliced(
1967    prev: VisualMap,
1968    source: &str,
1969    wrap: Option<usize>,
1970    preserve_soft: bool,
1971    top: &[QueryMatch],
1972    dirty: Range<usize>,
1973    surface: &Surface,
1974    reveal: Option<Reveal>,
1975    cache: &mut BlockCache,
1976    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
1977) -> Option<VisualMap> {
1978    let wrap = wrap.map(|w| w.max(8));
1979    // A width change invalidates every cached row — a full rebuild's job.
1980    if cache.wrap != Some(wrap) {
1981        return None;
1982    }
1983    // So does a moved reveal line, and for the same reason: this path reuses
1984    // every row outside the dirty block, and those rows encode which line was
1985    // showing its raw markup when they were built. Typing almost always moves
1986    // the caret, so under `MarkupMode::Full` this bails to `build_cached` on
1987    // most keystrokes — still block-cached, so only the edited block and the
1988    // revealed one actually re-render.
1989    if cache.layout.reveal != reveal {
1990        return None;
1991    }
1992    // Take the previous layout; on any bail below the caller rebuilds it (and the
1993    // map) via `build_cached`, so leaving it empty is fine. A table or a block
1994    // that renders outside its span (a degenerate inline span) makes shifting
1995    // unsound, so those force the full-rebuild path.
1996    let prev_layout = std::mem::take(&mut cache.layout);
1997    if prev_layout.built_len == 0 || prev_layout.has_tables || !prev_layout.all_shift_safe {
1998        return None;
1999    }
2000    // The layout addresses `prev` by row index, so it is only usable against the
2001    // map it was built from. A frontend is free to hold the map it was handed and
2002    // present it differently — leaf-ratatui splices blank filler rows under an
2003    // oversized heading so the raster has somewhere to stand — and if one of those
2004    // comes back here the row arithmetic below lands on the wrong rows: the
2005    // re-rendered block is laid over a filler and the rows it really occupied
2006    // survive into the suffix, stranding a stale copy of the edited line and
2007    // pushing everything after it one row down, once per keystroke. A row count
2008    // that doesn't match what this layout describes is the tell, and the honest
2009    // answer is the full rebuild.
2010    let described_rows = prev_layout
2011        .blocks
2012        .iter()
2013        .map(|pl| pl.sep_rows + pl.content_rows)
2014        .sum::<usize>()
2015        + prev_layout.trailing_rows;
2016    if described_rows != prev.rows.len() {
2017        return None;
2018    }
2019
2020    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
2021    if blocks.is_empty() || blocks.len() != prev_layout.blocks.len() {
2022        return None;
2023    }
2024    let delta = source.len() as isize - prev_layout.built_len as isize;
2025
2026    // The single block whose NEW span contains the whole dirty range. A dirty
2027    // range straddling a block boundary (or a separator) finds none → bail.
2028    let k = blocks
2029        .iter()
2030        .position(|m| m.span.start <= dirty.start && dirty.end <= m.span.end)?;
2031
2032    // Structural match: every OTHER block is unchanged — same kind throughout,
2033    // span identical before the edit and shifted by `delta` after it. A mismatch
2034    // means the reparse reshaped the block structure, which only a full rebuild
2035    // renders correctly.
2036    for (i, (m, pl)) in blocks.iter().zip(&prev_layout.blocks).enumerate() {
2037        if m.kind != pl.kind {
2038            return None;
2039        }
2040        if i == k {
2041            continue;
2042        }
2043        let want = if i < k {
2044            pl.span.clone()
2045        } else {
2046            (pl.span.start as isize + delta) as usize..(pl.span.end as isize + delta) as usize
2047        };
2048        if m.span != want {
2049            return None;
2050        }
2051    }
2052    // The dirty block itself: start unchanged (the edit is inside it, past its
2053    // start), end moved by exactly the delta.
2054    let pk_start = prev_layout.blocks[k].span.start;
2055    let pk_end = prev_layout.blocks[k].span.end;
2056    let pk_sep = prev_layout.blocks[k].sep_rows;
2057    let pk_content = prev_layout.blocks[k].content_rows;
2058    if blocks[k].span.start != pk_start || blocks[k].span.end != (pk_end as isize + delta) as usize
2059    {
2060        return None;
2061    }
2062
2063    // Re-render the dirty block from its subtree. A table makes the splice
2064    // bookkeeping unsafe, so bail if one appears.
2065    let subtree = fetch_subtree(blocks[k].node_id);
2066    if subtree.is_empty() {
2067        return None;
2068    }
2069    let mut sub = Builder {
2070        nodes: &subtree,
2071        source,
2072        wrap,
2073        rows: Vec::new(),
2074        tables: Vec::new(),
2075        last_off: 0,
2076        stepped_over: 0,
2077        surface,
2078        break_glyph: Cell::new(' '),
2079        preserve_soft,
2080        reveal: reveal.clone(),
2081        pending_mark_ends: RefCell::new(Vec::new()),
2082        pending_math: RefCell::new(Vec::new()),
2083        saw_math: Cell::new(false),
2084        presentation: Presentation::default(),
2085        faces: RefCell::new(FaceTable::default()),
2086    };
2087    sub.block(0, &[], &[]);
2088    // A table, or content that renders outside the block's span (a degenerate
2089    // inline span), makes the shift bookkeeping unsound — fall back.
2090    if !sub.tables.is_empty() || !rows_within(&sub.rows, &blocks[k].span) {
2091        return None;
2092    }
2093    // The face table starts from the previous map's, because every row this
2094    // path keeps was built against it and its glyphs' ids still mean what they
2095    // meant. The re-rendered block adds whatever it met. An id the edit took
2096    // the last glyph of stays in the table, naming nothing — the price of not
2097    // walking the rows this path exists to avoid walking.
2098    let mut faces = prev.faces;
2099    faces.merge(&sub.faces.into_inner());
2100    let sub_saw_math = sub.saw_math.get();
2101    let new_content = sub.rows;
2102    let new_content_len = new_content.len();
2103    let new_stops = collect_stops(&new_content);
2104    let new_mark_ends = collect_mark_ends(&new_content);
2105
2106    // Row span of the dirty block's CONTENT. Its leading separator stays in the
2107    // prefix: the gap before block k is unchanged, since k's start didn't move.
2108    let content_start_row: usize = prev_layout.blocks[..k]
2109        .iter()
2110        .map(|pl| pl.sep_rows + pl.content_rows)
2111        .sum::<usize>()
2112        + pk_sep;
2113    let content_end_row = content_start_row + pk_content;
2114
2115    // Splice rows: [prefix | new content | suffix + delta]. The prefix moves
2116    // untouched; the suffix shifts in place — integer adds, no glyph copy.
2117    let mut rows = prev.rows;
2118    let mut suffix = rows.split_off(content_end_row);
2119    rows.truncate(content_start_row);
2120    for row in &mut suffix {
2121        shift_row_in_place(row, delta);
2122    }
2123    rows.reserve(new_content_len + suffix.len());
2124    rows.extend(new_content);
2125    rows.extend(suffix);
2126
2127    // Splice stops by offset. The old dirty block covered `[pk_start, pk_end]`:
2128    // prefix stops fall below it, suffix stops above it (shift by delta), the new
2129    // content supplies the middle. The three ranges stay disjoint and ascending,
2130    // so the result needs no re-sort.
2131    let p1 = prev.stops.partition_point(|&s| s < pk_start);
2132    let p2 = prev.stops.partition_point(|&s| s <= pk_end);
2133    let mut stops = Vec::with_capacity(p1 + new_stops.len() + (prev.stops.len() - p2));
2134    stops.extend_from_slice(&prev.stops[..p1]);
2135    stops.extend(new_stops);
2136    for &s in &prev.stops[p2..] {
2137        stops.push((s as isize + delta) as usize);
2138    }
2139    // The mark ends splice the same way: they are offsets in the same
2140    // coordinates, cut at the same block.
2141    let m1 = prev.mark_ends.partition_point(|&s| s < pk_start);
2142    let m2 = prev.mark_ends.partition_point(|&s| s <= pk_end);
2143    let mut mark_ends = Vec::with_capacity(m1 + new_mark_ends.len() + (prev.mark_ends.len() - m2));
2144    mark_ends.extend_from_slice(&prev.mark_ends[..m1]);
2145    mark_ends.extend(new_mark_ends);
2146    for &s in &prev.mark_ends[m2..] {
2147        mark_ends.push((s as isize + delta) as usize);
2148    }
2149
2150    // Record the patched layout for the next splice: spans move to the new
2151    // coordinates, and the dirty block takes its new content-row count.
2152    let mut new_blocks = prev_layout.blocks;
2153    for (pl, m) in new_blocks.iter_mut().zip(&blocks) {
2154        pl.span = m.span.clone();
2155    }
2156    new_blocks[k].content_rows = new_content_len;
2157    new_blocks[k].has_math = sub_saw_math;
2158    cache.layout = Layout {
2159        blocks: new_blocks,
2160        trailing_rows: prev_layout.trailing_rows,
2161        built_len: source.len(),
2162        has_tables: false,
2163        // Every prefix/suffix block was shift-safe last build (we bailed
2164        // otherwise) and the re-rendered block was just checked, so the patched
2165        // document is still entirely shift-safe.
2166        all_shift_safe: true,
2167        reveal,
2168    };
2169
2170    label_media_boundaries(&mut rows);
2171    let code_blocks = code_block_spans(&rows);
2172    let media = media_spans(&rows);
2173    let directives = directive_spans(&rows);
2174    let math = math_spans(&rows);
2175    Some(VisualMap {
2176        rows,
2177        content_start: blocks[0].span.start,
2178        stops,
2179        mark_ends,
2180        tables: Vec::new(),
2181        code_blocks,
2182        media,
2183        directives,
2184        math,
2185        faces,
2186        spelling: OnceLock::new(),
2187    })
2188}
2189
2190/// A persistent, content-keyed cache of the rows each top-level block renders
2191/// to — the [`VisualMap`] analogue of the GUI's ShapedLine cache, one level
2192/// down. Held by a [`crate::Doc`] and threaded into [`build_cached`], it is what
2193/// makes a rebuild after a keystroke cost "re-render the edited block + shift
2194/// the rest" instead of re-rendering the whole document.
2195///
2196/// A top-level block's rows are a pure function of its source bytes and the wrap
2197/// width, so an unchanged block's rows are cloned and their source offsets
2198/// shifted by the edit's byte delta rather than rebuilt glyph by glyph. Two
2199/// things make that purity hold: at the top level the render prefix is always
2200/// empty (nesting prefixes — a quote gutter, a list indent — exist only *inside*
2201/// a top-level block, within its cached unit), and a block's output never reads
2202/// the incoming `last_off` (it writes `last_off` from its own content before any
2203/// nested separator reads it). So the only thing that differs between two
2204/// positions of an unchanged block is a uniform offset shift. Keyed by a fast
2205/// hash of the block's bytes with the bytes kept for a verify-on-hit — exactly
2206/// the shape cache's weak-hash-then-compare, so a collision costs a re-render,
2207/// never a wrong row.
2208///
2209/// Tables are never cached (a block that emits any table row is always rebuilt):
2210/// their rows are cross-referenced from the map's `tables` side-table by row
2211/// index, which a blind offset-shift wouldn't fix up, and they are rare enough
2212/// that the simplicity beats the reuse.
2213#[derive(Default)]
2214pub struct BlockCache {
2215    /// The wrap width every entry was built at; a change invalidates all of
2216    /// them. `None` before the first build (distinct from `Some(None)`, the
2217    /// unwrapped GUI width).
2218    wrap: Option<Option<usize>>,
2219    /// Bumped once per [`build_cached`]. An entry reused or inserted this build
2220    /// carries the current value; stale entries are dropped at the end of it.
2221    generation: u64,
2222    /// `hash(bytes)` → the block(s) sharing that hash — a bucket because
2223    /// distinct blocks can collide, while two *identical* blocks share one entry
2224    /// (free dedup).
2225    entries: HashMap<u64, Vec<CachedBlock>>,
2226    /// The row/stop decomposition of the last build, which [`build_spliced`]
2227    /// patches in place for a single-block edit. Kept in step with whatever
2228    /// [`VisualMap`] was last produced; empty before the first build.
2229    layout: Layout,
2230}
2231
2232/// How the last build's [`VisualMap`] decomposes into top-level blocks — the
2233/// bookkeeping [`build_spliced`] needs to splice one block's rows and stops
2234/// without rebuilding the whole map. Every field describes the *previous* build,
2235/// in that build's coordinates.
2236#[derive(Default)]
2237struct Layout {
2238    /// One entry per rendered (metadata-filtered) top-level block, in order.
2239    blocks: Vec<BlockLayout>,
2240    /// Trailing blank rows past the last block (from `emit_trailing_blank_lines`).
2241    trailing_rows: usize,
2242    /// The source length this layout was built at — the reference for the edit's
2243    /// byte delta.
2244    built_len: usize,
2245    /// Whether the last build drew any table. A table's cross-referenced row
2246    /// indices don't survive a blind splice, so their presence makes
2247    /// [`build_spliced`] bail to a full rebuild.
2248    has_tables: bool,
2249    /// Whether every block rendered strictly inside its own span (see
2250    /// [`rows_within`]). A block that doesn't — a malformed Markdown inline node
2251    /// that twig leaves with a degenerate `0..0` span renders at a fixed offset
2252    /// outside its block — can't be shifted correctly, so its presence makes
2253    /// [`build_spliced`] bail to a full rebuild.
2254    all_shift_safe: bool,
2255    /// The reveal line this layout was built under (see [`Builder::reveal`]).
2256    /// A splice reuses every row it isn't re-rendering, so a reveal line that
2257    /// has moved would leave the old line still showing its delimiters and the
2258    /// new one still hiding them — [`build_spliced`] bails when this changes.
2259    reveal: Option<Reveal>,
2260}
2261
2262/// One top-level block's contribution to the last build: its span and kind (for
2263/// the structural match that proves only one block changed) and how many
2264/// separator and content rows it emitted (to locate its slice of the row
2265/// vector).
2266struct BlockLayout {
2267    span: Range<usize>,
2268    kind: Kind,
2269    sep_rows: usize,
2270    content_rows: usize,
2271    /// Whether the block holds a formula — see [`BlockCache::math_meets`].
2272    has_math: bool,
2273}
2274
2275/// One cached block: the rows it rendered to, plus what a reuse at a new
2276/// position needs to shift them. Offsets are stored absolute (as built) and
2277/// shifted by `new_start - built_start` on reuse.
2278struct CachedBlock {
2279    /// The block's exact source bytes, compared on a hash hit so a collision
2280    /// can never hand back another block's rows.
2281    bytes: Box<[u8]>,
2282    /// The offset the rows were built at (the block's `span.start`).
2283    built_start: usize,
2284    /// The block's rows, offsets absolute as built.
2285    rows: Vec<VRow>,
2286    /// `last_off` after this block was emitted, absolute as built — restored
2287    /// (shifted) on reuse so the following separator lands correctly.
2288    last_off: usize,
2289    /// `stepped_over` after this block was emitted, absolute as built — the
2290    /// hidden tail a block ends with (a `</div>`), restored with `last_off`
2291    /// so the trailing blank lines are counted from past it on a hit too.
2292    stepped_over: usize,
2293    /// Where the reveal line fell *within this block* when the rows were built,
2294    /// as a block-relative byte range — see [`reveal_key`]. Compared alongside
2295    /// `bytes` on a hit, because identical source renders to different rows
2296    /// depending on whether the caret's line is inside it: the same `*em*`
2297    /// shows its asterisks on the revealed line and hides them everywhere else.
2298    ///
2299    /// Block-relative rather than absolute so an unaffected block still hits
2300    /// after an edit shifts it, and `None` for the overwhelmingly common
2301    /// no-reveal case — which is why an entry stored under `MarkupMode::None`
2302    /// keeps hitting for every block that isn't the caret's.
2303    reveal: Option<Range<usize>>,
2304    /// Whether the block holds a formula, so a hit can say so to the layout
2305    /// without walking the rows it is re-emitting.
2306    has_math: bool,
2307    /// The named families this block's glyphs are set in — see
2308    /// [`VisualMap::faces`]. Stored with the rows because a hit re-emits them
2309    /// without walking a `data-font` again, and the map still has to be able to
2310    /// say what the id on a reused glyph names. Empty for every block that
2311    /// names no family, which is nearly all of them.
2312    faces: FaceTable,
2313    /// The build that last reused or inserted this entry (see `generation`).
2314    generation: u64,
2315}
2316
2317/// Where `reveal` falls inside a block, in block-relative bytes — the extra key
2318/// a cached block is stored and matched under.
2319///
2320/// `None` when the block doesn't meet the reveal line at all, which is every
2321/// block on every build in the two hidden modes, and all but one of them under
2322/// [`crate::MarkupMode::Full`]. So the cache keeps its hit rate as the caret
2323/// moves: only the line the caret leaves and the line it arrives at re-render.
2324fn reveal_key(reveal: &Option<Reveal>, span: &Range<usize>) -> Option<Range<usize>> {
2325    let r = reveal.as_ref()?;
2326    // The same generous intersection test `Builder::revealed` uses, so a block
2327    // is keyed as revealed exactly when its glyphs will be built that way.
2328    // Whether the line reveals markup or only math is not in the key: that is
2329    // a mode, and a mode change empties the cache.
2330    r.meets(span).then(|| {
2331        let start = r.line.start.max(span.start) - span.start;
2332        let end = r.line.end.min(span.end) - span.start;
2333        start..end
2334    })
2335}
2336
2337impl BlockCache {
2338    /// Whether the caret's `line` meets a top-level block that holds a
2339    /// formula, as of the last build — the question [`crate::Doc::reveal_line`]
2340    /// asks in the hidden markup modes before it threads the line through, so
2341    /// that only a line with something to reveal costs a rebuild.
2342    ///
2343    /// Answered from the layout rather than from twig because the layout is
2344    /// free: every build records per block whether its walk met a formula
2345    /// ([`BlockLayout::has_math`]), and a query against the tree is
2346    /// O(document) on every frame. Coarse on purpose — a block, not a line —
2347    /// since a block with a formula in it is rare, small, and the one thing
2348    /// worth re-rendering as the caret moves through it.
2349    ///
2350    /// Exact between edits, when the spans are the document's. Across an edit
2351    /// the spans are the previous revision's, so the caller checks again once
2352    /// the new layout is in and rebuilds if the answer changed.
2353    pub(crate) fn math_meets(&self, line: &Range<usize>) -> bool {
2354        self.layout
2355            .blocks
2356            .iter()
2357            .any(|b| b.has_math && b.span.start <= line.end && line.start <= b.span.end)
2358    }
2359
2360    /// Look up a block by hash, verify its bytes and reveal key, and on a hit
2361    /// stamp it used this build and hand back a borrow to shift-and-clone from.
2362    /// `None` on a miss (unknown hash, a collision whose bytes differ, or the
2363    /// same bytes built under a different reveal).
2364    fn reuse(
2365        &mut self,
2366        hash: u64,
2367        bytes: &[u8],
2368        reveal: &Option<Range<usize>>,
2369    ) -> Option<&CachedBlock> {
2370        let g = self.generation;
2371        let bucket = self.entries.get_mut(&hash)?;
2372        let e = bucket
2373            .iter_mut()
2374            .find(|e| &*e.bytes == bytes && &e.reveal == reveal)?;
2375        e.generation = g;
2376        Some(&*e)
2377    }
2378
2379    /// Cache the rows a freshly-rendered block produced (or refresh an existing
2380    /// entry for the same bytes and reveal — an identical block elsewhere, or a
2381    /// re-render).
2382    #[allow(clippy::too_many_arguments)]
2383    fn store(
2384        &mut self,
2385        hash: u64,
2386        bytes: &[u8],
2387        built_start: usize,
2388        rows: Vec<VRow>,
2389        last_off: usize,
2390        stepped_over: usize,
2391        reveal: Option<Range<usize>>,
2392        has_math: bool,
2393        faces: FaceTable,
2394    ) {
2395        let g = self.generation;
2396        let bucket = self.entries.entry(hash).or_default();
2397        if let Some(e) = bucket
2398            .iter_mut()
2399            .find(|e| &*e.bytes == bytes && e.reveal == reveal)
2400        {
2401            e.built_start = built_start;
2402            e.rows = rows;
2403            e.last_off = last_off;
2404            e.stepped_over = stepped_over;
2405            e.has_math = has_math;
2406            e.faces = faces;
2407            e.generation = g;
2408        } else {
2409            bucket.push(CachedBlock {
2410                bytes: bytes.into(),
2411                built_start,
2412                rows,
2413                last_off,
2414                stepped_over,
2415                reveal,
2416                has_math,
2417                faces,
2418                generation: g,
2419            });
2420        }
2421    }
2422}
2423
2424/// The source bytes a top-level block covers — the block cache's key material.
2425///
2426/// Clamped to the source rather than sliced by the span as twig gives it,
2427/// because that span can end *past* the last byte: the final block of a document
2428/// with no trailing newline is closed on the virtual newline the parser supplies
2429/// at EOF, so its `span.end` is `source.len() + 1`. Slicing by such a range
2430/// yields `None`, and the obvious `unwrap_or(&[])` reads that as *this block has
2431/// no bytes* — the wrong answer twice over.
2432///
2433/// Two blocks whose spans both overrun then key alike, and the second is served
2434/// the first one's rows. That is not hypothetical: a footnote definition is a
2435/// root beside `doc` merged back into the top level by [`top_blocks`], while the
2436/// `section` above it spans the definition's bytes too, so both end at EOF —
2437/// and a document ending in `[^note]: …` renders that definition as a second
2438/// copy of the heading. Even alone, a block that keeps hashing empty as the user
2439/// types in it is served the stale rows built before the edit.
2440///
2441/// Clamping hands back the bytes the block really covers, which tells both cases
2442/// apart, and costs nothing for a span that was in range to begin with.
2443fn block_bytes<'a>(source: &'a str, span: &Range<usize>) -> &'a [u8] {
2444    let bytes = source.as_bytes();
2445    let start = span.start.min(bytes.len());
2446    &bytes[start..span.end.clamp(start, bytes.len())]
2447}
2448
2449/// A fast, allocation-free content hash (FNV-1a) for a block's bytes. Weak by
2450/// design — the bytes are compared on a hit — so its only job is to spread
2451/// blocks across buckets cheaply. SipHash over every block's bytes on every
2452/// keystroke would cost more than it saves, the same lesson the shape cache
2453/// learned when it stopped hashing through the standard hasher.
2454fn block_hash(bytes: &[u8]) -> u64 {
2455    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
2456    for &x in bytes {
2457        h ^= x as u64;
2458        h = h.wrapping_mul(0x0000_0100_0000_01b3);
2459    }
2460    h
2461}
2462
2463/// Clone a cached row with every source offset advanced by `delta` — the whole
2464/// cost of reusing an unchanged block: integer adds where a rebuild would
2465/// re-shape every glyph.
2466fn shift_row(row: &VRow, delta: isize) -> VRow {
2467    let shift = |off: usize| (off as isize + delta) as usize;
2468    VRow {
2469        glyphs: row
2470            .glyphs
2471            .iter()
2472            .map(|g| Glyph {
2473                ch: g.ch,
2474                style: g.style,
2475                src: shift(g.src),
2476                stop: g.stop,
2477            })
2478            .collect(),
2479        end_src: shift(row.end_src),
2480        decoration: row.decoration,
2481        code: row.code,
2482        code_lang: row.code_lang.clone(),
2483        directive: row.directive,
2484        directive_label: row.directive_label.clone(),
2485        media: row.media.clone(),
2486        // A tick, not an offset — reuse carries it as-is, like `code_lang`.
2487        task: row.task,
2488        leaf_directive: row.leaf_directive.clone(),
2489        heading: row.heading,
2490        // Presentation, not offsets: names the author wrote, which a shifted
2491        // block still wears — like `code_lang`.
2492        align: row.align,
2493        line_height: row.line_height,
2494        // Structure, not offsets: a reused block's rows divide the same blocks
2495        // wherever the edit above moved them to.
2496        boundary: row.boundary,
2497        mark_ends: row.mark_ends.iter().map(|&o| shift(o)).collect(),
2498        // Strings and a glyph index: the glyph moved, the index into the row
2499        // did not.
2500        math: row.math.clone(),
2501    }
2502}
2503
2504/// Advance a row's source offsets by `delta` in place — the suffix half of
2505/// [`build_spliced`], where the rows are already owned and only need shifting,
2506/// not copying.
2507fn shift_row_in_place(row: &mut VRow, delta: isize) {
2508    for g in &mut row.glyphs {
2509        g.src = (g.src as isize + delta) as usize;
2510    }
2511    row.end_src = (row.end_src as isize + delta) as usize;
2512    for o in &mut row.mark_ends {
2513        *o = (*o as isize + delta) as usize;
2514    }
2515}
2516
2517/// Whether every source offset a block's rows carry falls inside the block's own
2518/// span — the precondition for reusing the block by a uniform offset shift. It
2519/// holds for well-formed blocks (their glyphs and row ends address bytes within
2520/// the block, synthetic glyphs point at the block start). It fails when a node
2521/// renders *outside* its block, which today means a malformed Markdown inline
2522/// node twig leaves with a degenerate `0..0` span: that content lands at a fixed
2523/// offset that doesn't move with the block. Such a block is re-rendered every
2524/// build instead of shifted, so the incremental map still matches a fresh one —
2525/// see [`build_cached`] and [`build_spliced`].
2526fn rows_within(rows: &[VRow], span: &Range<usize>) -> bool {
2527    rows.iter().all(|r| {
2528        r.end_src >= span.start
2529            && r.end_src <= span.end
2530            && r.glyphs
2531                .iter()
2532                .all(|g| g.src >= span.start && g.src <= span.end)
2533    })
2534}
2535
2536/// Where the rendered document begins when a leading `metadata` block is all
2537/// there is — the end of that hidden frontmatter, past the newline that closes
2538/// its last line so the floor sits at the start of the (empty) body rather than
2539/// on the closing `---`.
2540///
2541/// With a real block after it the frontmatter's end is never needed: the floor
2542/// is that block's start, and the rows begin there. With nothing after it, both
2543/// the caret floor and the trailing-blank-line count would otherwise fall back
2544/// to offset 0 — inside the hidden frontmatter — which put the caret *before*
2545/// the metadata and made typing land ahead of the opening `---`.
2546fn hidden_prefix_end(source: &str, meta_end: Option<usize>) -> usize {
2547    let Some(end) = meta_end else { return 0 };
2548    let end = end.min(source.len());
2549    let rest = &source[end..];
2550    if rest.starts_with("\r\n") {
2551        end + 2
2552    } else if rest.starts_with('\n') {
2553        end + 1
2554    } else {
2555        end
2556    }
2557}
2558
2559/// The end of the document's hidden frontmatter: the last `metadata` child of
2560/// `doc`, which is what [`top_level`] and [`Builder::blocks`] drop. `None` when
2561/// there is none.
2562fn metadata_end_of(nodes: &[FlatNode], doc: usize) -> Option<usize> {
2563    let mut end = None;
2564    let mut child = nodes[doc].first_child;
2565    while let Some(cid) = child {
2566        let n = &nodes[cid.0 as usize];
2567        if n.kind == Kind::Metadata {
2568            end = Some(n.span.end);
2569        }
2570        child = n.next_sibling;
2571    }
2572    end
2573}
2574
2575/// The document's rendered top-level blocks, as node indices in source order.
2576///
2577/// Not simply `doc`'s children, for two reasons. Frontmatter (a leading
2578/// `metadata` block) is document metadata rather than prose and is dropped, the
2579/// way [`Builder::blocks`] drops it. And a **footnote definition** (`[^1]: …`)
2580/// is not a child of `doc` at all: twig parses it as a root of its own, a
2581/// *sibling* of the document node with `parent == None`. A walk that starts at
2582/// `doc` therefore never reaches one, which is why a definition — and every
2583/// byte of its body — used to render as nothing at all. Merging the roots back
2584/// in by `span.start` puts each definition on screen exactly where it was
2585/// written, which is what keeps rows, stops, and offsets monotonic.
2586///
2587/// A **link reference definition** (`[foo]: /url`) is a root of the same kind,
2588/// and is merged for the opposite reason: it draws *nothing*, and the walk has
2589/// to know where it stands to step over it. A definition closing a README —
2590/// the `[links]: …` block under the prose — left no block over its lines, so
2591/// the separator logic read them as blank lines and drew an empty paragraph
2592/// per definition. Merged in, it is a hidden block like a comment, and
2593/// [`Builder::block_or_hidden`] moves the walk past it. One with no span
2594/// (`0..0`, what twig before 3.3.3 reported for every one) has nowhere to be
2595/// merged, and is left out as before.
2596///
2597/// Only those roots are merged. twig also leaves stray orphan `str` nodes
2598/// parented to nothing (the `*` of an emphasis run, for one); those are already
2599/// rendered as part of the subtree that owns their bytes, and re-emitting them
2600/// here would double them.
2601fn top_level(nodes: &[FlatNode], doc: usize) -> Vec<usize> {
2602    let mut out = Vec::new();
2603    let mut child = nodes[doc].first_child;
2604    while let Some(cid) = child {
2605        let n = &nodes[cid.0 as usize];
2606        if n.kind != Kind::Metadata {
2607            out.push(cid.0 as usize);
2608        }
2609        child = n.next_sibling;
2610    }
2611    out.extend(
2612        nodes
2613            .iter()
2614            .enumerate()
2615            .filter(|(_, n)| n.parent.is_none() && is_placed_definition(&n.kind, &n.span))
2616            .map(|(i, _)| i),
2617    );
2618    out.sort_by_key(|&i| nodes[i].span.start);
2619    out
2620}
2621
2622/// Is a parentless node of `kind` at `span` a definition the top-level walk
2623/// merges in — a footnote definition, or a link reference definition that
2624/// knows where it stands? Shared by [`top_level`] and [`top_blocks`] so the
2625/// two walks cannot disagree about what the top-level blocks are.
2626fn is_placed_definition(kind: &Kind, span: &Range<usize>) -> bool {
2627    match *kind {
2628        Kind::Footnote => true,
2629        Kind::Reference => span.end > span.start,
2630        _ => false,
2631    }
2632}
2633
2634/// The top-level blocks to hand [`build_cached`] / [`build_spliced`] — the
2635/// incremental path's twin of [`top_level`], which the two must agree with block
2636/// for block or the render paths diverge.
2637///
2638/// `child_spans(None)` gives `doc`'s children, which is all of them for an
2639/// ordinary document. A **footnote definition** is not one: twig parses `[^1]: …`
2640/// as a root beside `doc` with no parent, and indexes it at no offset either —
2641/// `node_at` inside its bytes answers `doc`, and a `query("footnote")` selector
2642/// finds nothing. Leaf used to discover them by marshalling the whole arena with
2643/// `nodes()` — the very cost the incremental path exists to avoid — behind a
2644/// byte-scan gate that gave documents with no `[^…]:` line a substring search
2645/// instead. twig 3.0's `definitions()` asks the library the question directly,
2646/// so both the marshal and the gate are gone.
2647///
2648/// The link reference definitions `definitions()` also reports are merged on
2649/// the same terms as [`top_level`] merges them — see [`is_placed_definition`].
2650///
2651/// This is the one part of the render that needs an [`Editor`] rather than a
2652/// marshalled node array. The builders themselves stay editor-free; this only
2653/// prepares their input.
2654pub(crate) fn top_blocks(editor: &mut Editor) -> Vec<QueryMatch> {
2655    let mut top = editor.child_spans(None).unwrap_or_default();
2656    let defs: Vec<QueryMatch> = definitions(editor)
2657        .into_iter()
2658        .filter(|m| is_placed_definition(&m.kind, &m.span))
2659        .collect();
2660    if defs.is_empty() {
2661        return top;
2662    }
2663    top.extend(defs);
2664    // Source order — what every offset-keyed thing downstream (rows, stops, the
2665    // splice path's block-for-block match) is built to assume.
2666    top.sort_by_key(|m| m.span.start);
2667    top
2668}
2669
2670/// Every `[^label]: …` definition in the document, in whatever order twig
2671/// reports them.
2672///
2673/// Filtered to [`Kind::Footnote`]: `definitions()` also reports the *link*
2674/// reference definitions (`[foo]: /url`), which are [`top_blocks`]'s business
2675/// and not [`crate::Doc::footnote_at_caret`]'s.
2676///
2677/// Empty when the document can't be walked, which leaves [`top_blocks`] with
2678/// the ordinary top-level children and [`crate::Doc::footnote_at_caret`] with an
2679/// undefined reference — in both cases the same answer as a document that has
2680/// no definitions, which is the right way to degrade.
2681pub(crate) fn footnote_definitions(editor: &mut Editor) -> Vec<QueryMatch> {
2682    definitions(editor)
2683        .into_iter()
2684        .filter(|m| m.kind == Kind::Footnote)
2685        .collect()
2686}
2687
2688/// Every definition twig resolves by label rather than by position — footnote
2689/// and link reference definitions both — or nothing when the document can't be
2690/// walked.
2691fn definitions(editor: &mut Editor) -> Vec<QueryMatch> {
2692    let Ok(mut doc) = editor.document() else {
2693        return Vec::new();
2694    };
2695    doc.definitions().unwrap_or_default()
2696}
2697
2698/// The label of the footnote definition starting at `start` — the `1` in
2699/// `[^1]: …`. twig gives the `footnote` node no label of its own (no `text`, no
2700/// `name`), and the bytes that spell it belong to no child node either — the
2701/// body `para` starts its *content* past them — so the source is the only place
2702/// to read it from. `None` when what's there isn't a definition after all.
2703pub(crate) fn footnote_label(source: &str, start: usize) -> Option<&str> {
2704    let rest = source.get(start..)?.strip_prefix("[^")?;
2705    let end = rest.find("]:")?;
2706    Some(&rest[..end])
2707}
2708
2709/// Where the body of the footnote definition spanning `span` sits in `source` —
2710/// everything past the `[^1]:` marker, which is the part a reader actually wants
2711/// when they follow a reference.
2712///
2713/// Source bytes, verbatim but for the whitespace trimmed off each end: a note
2714/// that says `see *later*` answers with the asterisks in. Rendering that body is
2715/// a frontend's business the same way painting a [`Role`] is, and a caller that
2716/// wants it laid out already has the definition on screen where it was written.
2717///
2718/// The trim is what makes the common case read right — `[^1]: text` has a space
2719/// after the colon that belongs to the marker, not the note, and a definition's
2720/// span runs to the newline ending it.
2721///
2722/// The span is taken at its word, which it has only been safe to do since twig
2723/// 3.1: a djot definition's span used to run *past* its own last line, through
2724/// the blank line separating it from the next block and into that block's first
2725/// byte, so `[^2a]: a note.` came back as `"a note.\n\n["` and the offsets named
2726/// the following note's rows as well as this one's — a reader asking about one
2727/// footnote was shown two. leaf measured the body itself to get around that, and
2728/// paid for it: the scan stopped at the first blank line, so a note with a second
2729/// indented paragraph lost it. Both halves go away with the fix, since a blank
2730/// line *inside* a definition was always interior to the span and still is.
2731///
2732/// A range rather than a slice because "go to note" needs the *position* as much
2733/// as the text, and it needs the position of the body specifically: a
2734/// definition's `[^1]:` marker is decoration the caret can't occupy (the rich
2735/// view draws it as `[1] ` and gives it no stop), so aiming a caret at the
2736/// definition's first byte lands it on the nearest real stop instead — which is
2737/// up in the paragraph *above* the note. The body's first byte is a stop, and is
2738/// where a reader following a reference wants to arrive anyway.
2739pub(crate) fn footnote_body_span(source: &str, span: Range<usize>) -> Option<Range<usize>> {
2740    let rest = source.get(span.clone())?.strip_prefix("[^")?;
2741    let marker = rest.find("]:")?;
2742    // `span.start` + `[^` + the label + `]:`.
2743    let after_marker = span.start + 2 + marker + 2;
2744    let raw = source.get(after_marker..span.end)?;
2745    // Written as a start plus a length so an all-whitespace body lands on an
2746    // empty range at the end rather than an inverted one.
2747    let start = after_marker + (raw.len() - raw.trim_start().len());
2748    Some(start..start + raw.trim().len())
2749}
2750
2751/// The label of the footnote *reference* spanning `span` — the `1` in `[^1]`.
2752///
2753/// The peer of [`footnote_label`] for the other half of the pair, and needed for
2754/// the same reason: a reference whose node carries neither a `content_span` nor
2755/// a `text` still spells its label plainly in the source. `None` when the bytes
2756/// aren't a reference after all.
2757pub(crate) fn footnote_reference_label(source: &str, span: Range<usize>) -> Option<&str> {
2758    let rest = source.get(span)?.strip_prefix("[^")?;
2759    let end = rest.find(']')?;
2760    Some(&rest[..end])
2761}
2762
2763/// Where a heading's *content* starts — past the `#`s and the space the rich
2764/// view hides, for an ATX heading; the block's own start for a setext one (which
2765/// has no leading marker) and for a format that spells headings some other way.
2766///
2767/// Only an empty heading needs asking: with any content at all, the row ends on
2768/// its last glyph. Bounded to the heading's own first line so a marker-less
2769/// heading can't scan into the text under it.
2770fn heading_content_start(source: &str, span: &Range<usize>) -> usize {
2771    let end = span.end.min(source.len());
2772    let Some(line) = source.get(span.start..end) else {
2773        return span.start;
2774    };
2775    let line = line.split('\n').next().unwrap_or("");
2776    let hashes = line.len() - line.trim_start_matches('#').len();
2777    if hashes == 0 {
2778        return span.start;
2779    }
2780    let after = &line[hashes..];
2781    span.start + hashes + (after.len() - after.trim_start_matches([' ', '\t']).len())
2782}
2783
2784struct Builder<'a> {
2785    nodes: &'a [FlatNode],
2786    /// The document source, consulted to place blank-line rows at the source
2787    /// offsets the caret should occupy on them (the AST drops blank lines).
2788    source: &'a str,
2789    /// The word-wrap column budget, or `None` to emit each block as a single
2790    /// unwrapped row (the frontend wraps).
2791    wrap: Option<usize>,
2792    rows: Vec<VRow>,
2793    /// Built alongside `rows`, never instead of them — see [`TableInfo`].
2794    tables: Vec<TableInfo>,
2795    /// The end offset of the last content emitted — the anchor for blank
2796    /// separator rows so the caret never snaps onto one.
2797    last_off: usize,
2798    /// The end of the last block the walk stepped over without drawing — a
2799    /// comment, which the rich view hides. `last_off` moves past it too, for the
2800    /// separators; this is kept apart so the trailing blank lines can be counted
2801    /// from it without also being counted from a code block's closing fence,
2802    /// which `last_off` likewise ends after. `0` until a hidden block is met.
2803    stepped_over: usize,
2804    /// How many rows each block image reserves, keyed by its destination — the
2805    /// frontend's per-image height, threaded in from [`crate::Doc::set_media_rows`]
2806    /// so [`Builder::block_media`] can size the placeholder without core doing any
2807    /// I/O. A destination absent from the map (or a `0`/`1` entry) reserves the
2808    /// bare one-row placeholder, which is the whole-document default and what
2809    /// every existing test — passing an empty map — still gets.
2810    surface: &'a Surface,
2811    /// The glyph a hard break renders as while the current inline run is built:
2812    /// a space in prose (a break folds into the flow the frontend wraps), but a
2813    /// newline (`\n`) inside a table cell, where a row is one source line and the
2814    /// only break it can carry is an explicit one that must show as a line of its
2815    /// own. Set around [`Builder::row_cells`] and otherwise left at `' '`.
2816    break_glyph: Cell<char>,
2817    /// Render a soft break (a bare newline inside a paragraph) as a line break
2818    /// where it was written, rather than folding it into the reflowed paragraph
2819    /// — the `LineFlow::Preserve` behaviour. A soft break emits a `'\n'` glyph
2820    /// (like a hard break in a cell), which [`Builder::emit_wrapped`] turns into
2821    /// a fresh visual row. `false` is the flowing-prose default. Inside a table
2822    /// cell (where `break_glyph` is already `'\n'`) it has no effect: a cell is
2823    /// one line and folds its own soft breaks regardless.
2824    preserve_soft: bool,
2825    /// The source byte range of the one line that should render its markup
2826    /// *raw* — the caret's line under `MarkupMode::Full` (see
2827    /// [`crate::Doc::reveal_line`]). `None` in every other mode and view, which
2828    /// is the delimiters-always-hidden behaviour every build had before the
2829    /// preference existed.
2830    ///
2831    /// Read only by [`Builder::revealed`], which every delimiter-bearing arm of
2832    /// [`Builder::inline`] consults. A range rather than a bare caret offset
2833    /// because the decision is per-*node*, not per-caret: a node is revealed
2834    /// when its span meets this line, so `*em*` shows both its asterisks even
2835    /// with the caret at one end of it.
2836    reveal: Option<Reveal>,
2837    /// The content ends of the hidden marks rendered since the last row was
2838    /// pushed — recorded as the inline walk meets each mark, and drained onto
2839    /// the rows as they are emitted (see [`Builder::take_mark_ends`]). A cell
2840    /// rather than a `&mut`, for the reason `break_glyph` is: the inline walk
2841    /// borrows the builder shared.
2842    pending_mark_ends: RefCell<Vec<usize>>,
2843    /// The inline atoms rendered since the last row was pushed, keyed by the
2844    /// formula's start offset — the offset the atom glyph carries, which is
2845    /// how [`Builder::take_math`] pairs each with its glyph once the wrap has
2846    /// decided which row it landed on. Drained the way `pending_mark_ends` is.
2847    pending_math: RefCell<Vec<(usize, MathMark)>>,
2848    /// Whether this walk met a formula at all, atom, block, or revealed — the
2849    /// fact [`BlockCache`] keeps per block so [`crate::Doc::reveal_line`] can
2850    /// tell whether the caret's line has anything to reveal without walking.
2851    saw_math: Cell<bool>,
2852    /// The presentation vocabulary in force at the block being walked — the
2853    /// keys the `div`s around it carry, folded together with the nearest
2854    /// winning, and [`Presentation::default`] at the top level.
2855    ///
2856    /// Saved and restored around each `div` in [`Builder::block`], so a block
2857    /// reads its own attributes over whatever its containers said and nothing
2858    /// leaks sideways to the block after it. It is per-*build* state rather
2859    /// than a parameter because every one of the dozen call sites of `block`
2860    /// would otherwise thread a value none of them care about.
2861    presentation: Presentation,
2862    /// The named families this walk has met, by the id its glyphs carry — see
2863    /// [`VisualMap::faces`]. A `RefCell` for [`pending_mark_ends`]'s reason:
2864    /// the inline walk borrows the builder shared, and a span's `data-font` is
2865    /// read from inside it.
2866    ///
2867    /// [`pending_mark_ends`]: Builder::pending_mark_ends
2868    faces: RefCell<FaceTable>,
2869}
2870
2871/// The six presentation keys as the walker carries them down a block tree —
2872/// the two that are the block's ([`Align`], [`LineHeight`]) and the three that
2873/// are a run's but may be written on the block ([`FontSize`], [`FaceRef`],
2874/// [`TextColor`]).
2875///
2876/// `Copy` and five `Option`s, because folding is the whole of what it does:
2877/// [`under`](Presentation::under) reads a container's attributes over an
2878/// existing set and a key the container does not name keeps the value it had.
2879/// That is the "nearest wins" rule stated once, rather than at each of the
2880/// three levels a key can be written at. A name and a value fold alike: the
2881/// nearer node wins whichever of the two forms either of them wrote.
2882#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2883struct Presentation {
2884    align: Option<Align>,
2885    line_height: Option<LineHeight>,
2886    size: Option<FontSize>,
2887    font: Option<FaceRef>,
2888    color: Option<TextColor>,
2889}
2890
2891impl Presentation {
2892    /// This set with whatever `attrs` names written over it — the nearer node's
2893    /// answer where it has one, the outer node's where it hasn't.
2894    ///
2895    /// `faces` is the build's intern table, which a named family is recorded in
2896    /// on the way past: the glyph carries the id and the table carries the
2897    /// string. Shared rather than `&mut` because the inline walk this feeds
2898    /// borrows the builder shared, the way `pending_mark_ends` does.
2899    fn under(self, attrs: &[(String, Option<String>)], faces: &RefCell<FaceTable>) -> Self {
2900        Self {
2901            align: Align::from_attrs(attrs).or(self.align),
2902            line_height: LineHeight::from_attrs(attrs).or(self.line_height),
2903            size: FontSize::from_attrs(attrs).or(self.size),
2904            font: faces.borrow_mut().face_from_attrs(attrs).or(self.font),
2905            color: TextColor::from_attrs(attrs).or(self.color),
2906        }
2907    }
2908
2909    /// `base` carrying the three run-level keys — the style a block's glyphs
2910    /// start from, which an attributed span inside it then writes over.
2911    fn over(self, base: Style) -> Style {
2912        base.size(self.size).font(self.font).color(self.color)
2913    }
2914}
2915
2916impl Builder<'_> {
2917    /// Note that the mark `id` closes with a hidden delimiter, so its content
2918    /// end is a caret home — unless the mark is empty, where the end is the
2919    /// start and there is nothing to extend.
2920    fn note_mark_end(&self, id: usize) {
2921        let node = &self.nodes[id];
2922        if let Some(content) = &node.content_span
2923            && content.end < node.span.end
2924            && !content.is_empty()
2925        {
2926            self.pending_mark_ends.borrow_mut().push(content.end);
2927        }
2928    }
2929
2930    /// The pending mark ends at or before `end_src`, for the row ending there
2931    /// — every mark rendered so far that closes on it. A mark's end never
2932    /// exceeds the end of the row its last glyph is on, so the leftovers are
2933    /// those of rows still to come.
2934    fn take_mark_ends(&self, end_src: usize) -> Vec<usize> {
2935        let mut pending = self.pending_mark_ends.borrow_mut();
2936        let (taken, kept): (Vec<usize>, Vec<usize>) =
2937            pending.drain(..).partition(|&o| o <= end_src);
2938        *pending = kept;
2939        taken
2940    }
2941
2942    /// The pending inline atoms whose glyph is on the row `glyphs` is about
2943    /// to become — each paired with the index of the [`Role::Math`] glyph
2944    /// carrying its offset, in glyph order. An atom whose glyph landed on an
2945    /// earlier row was taken then; one on a later row is left for it. The
2946    /// peer of [`take_mark_ends`](Self::take_mark_ends), and why an atom is
2947    /// keyed by offset: the wrap decides the row, and the offset is what the
2948    /// glyph still carries once it has.
2949    fn take_math(&self, glyphs: &[Glyph]) -> Vec<MathMark> {
2950        let mut pending = self.pending_math.borrow_mut();
2951        if pending.is_empty() {
2952            return Vec::new();
2953        }
2954        let mut out = Vec::new();
2955        for (i, g) in glyphs.iter().enumerate() {
2956            if g.style.role != Role::Math || !g.stop {
2957                continue;
2958            }
2959            if let Some(at) = pending.iter().position(|(src, _)| *src == g.src) {
2960                let (_, mut mark) = pending.remove(at);
2961                mark.glyph = Some(i);
2962                out.push(mark);
2963            }
2964        }
2965        out
2966    }
2967    /// Whether `span` belongs to the line that is showing its raw markup. True
2968    /// only when a reveal line is set *for markup* (`MarkupMode::Full`) and the
2969    /// two ranges actually meet — see [`Reveal::meets`] for what meeting is.
2970    fn revealed(&self, span: &Range<usize>) -> bool {
2971        self.reveal
2972            .as_ref()
2973            .is_some_and(|r| r.markup && r.meets(span))
2974    }
2975
2976    /// Whether a formula at `span` shows its TeX rather than its picture: it
2977    /// meets the reveal line, in *any* mode. A formula's content is its source
2978    /// and not its picture, so for it the choice is not between a clean
2979    /// surface and a raw one but between editable and not — which is why this
2980    /// does not read [`Reveal::markup`] the way [`revealed`](Self::revealed)
2981    /// does.
2982    fn math_revealed(&self, span: &Range<usize>) -> bool {
2983        self.reveal.as_ref().is_some_and(|r| r.meets(span))
2984    }
2985
2986    /// The `(opening, closing)` source byte ranges of a node's delimiters — the
2987    /// bytes its `span` holds that its `content_span` doesn't.
2988    ///
2989    /// This is how *every* inline delimiter is recovered, rather than a table of
2990    /// spellings per kind: twig gives `*em*` a span of `13..17` and a content
2991    /// span of `14..16`, so the gaps at each end are the delimiters, whatever
2992    /// they happen to be. That matters because one kind has many spellings —
2993    /// `*em*` and `_em_` are both emphasis, `` `x` `` and ``` ``x`` ``` both
2994    /// verbatim — and re-deriving the text from the source is the only way to
2995    /// show back what the author actually typed. It also gets a link's
2996    /// asymmetric `[` / `](dest)` right for free.
2997    ///
2998    /// `None` when the node has no content span, or when content and span
2999    /// coincide (nothing was elided, so there is nothing to reveal).
3000    fn delims(&self, id: usize) -> Option<(Range<usize>, Range<usize>)> {
3001        let node = &self.nodes[id];
3002        let content = node.content_span.clone()?;
3003        let span = node.span.clone();
3004        // A content span that escapes its own node's span means the two are
3005        // describing different things; reveal nothing rather than slice wildly.
3006        if content.start < span.start || content.end > span.end {
3007            return None;
3008        }
3009        let (open, close) = (span.start..content.start, content.end..span.end);
3010        // A delimiter that spans a newline isn't this line's to reveal — a setext
3011        // heading's `\n=====` underline is the case that arises in practice. It
3012        // would also inject a `'\n'` glyph, which `emit_wrapped` reads as a hard
3013        // row break, so the row would split where the author wrote no break.
3014        let multiline =
3015            |r: &Range<usize>| self.source.get(r.clone()).is_some_and(|s| s.contains('\n'));
3016        if multiline(&open) || multiline(&close) {
3017            return None;
3018        }
3019        (!open.is_empty() || !close.is_empty()).then_some((open, close))
3020    }
3021
3022    /// Emit the source bytes of `range` as revealed markup — real glyphs, each
3023    /// mapped to its own source byte and each a caret stop, so a delimiter shown
3024    /// is a delimiter that can be selected, edited and deleted like any other
3025    /// text. Styled [`Role::Delimiter`] on top of the run's own style, which is
3026    /// how a frontend tells scaffolding from prose and dims it.
3027    ///
3028    /// Deliberately *not* [`push_escaped_text`]: this is raw source, not parsed
3029    /// text, so there is no escape-driven drift between the two to correct.
3030    fn push_delim(&self, out: &mut Vec<Glyph>, range: &Range<usize>, base: Style) {
3031        let Some(text) = self.source.get(range.clone()) else {
3032            return;
3033        };
3034        push_text(out, text, range.start, base.role(Role::Delimiter));
3035    }
3036
3037    /// Render an inline node's children wrapped in its raw delimiters when the
3038    /// node is on the revealed line, and bare (delimiters resolved away) when it
3039    /// isn't — the shared body of every delimiter-bearing arm of
3040    /// [`inline`](Self::inline).
3041    ///
3042    /// `style` is the resolved styling the content still gets in *both* modes:
3043    /// revealing `*em*` shows the asterisks *and* keeps the text italic, the
3044    /// live-preview behaviour. Showing the markup is not the same as turning the
3045    /// rendering off — that is what [`crate::View::Source`] is for.
3046    fn inline_delimited(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
3047        let show = self
3048            .revealed(&self.nodes[id].span)
3049            .then(|| self.delims(id))
3050            .flatten();
3051        if let Some((open, _)) = &show {
3052            self.push_delim(out, open, style);
3053        }
3054        self.recurse(id, style, out);
3055        match &show {
3056            Some((_, close)) => self.push_delim(out, close, style),
3057            // Hidden, so the content's end has no glyph after it: give the
3058            // caret its home there.
3059            None => self.note_mark_end(id),
3060        }
3061    }
3062
3063    /// A verbatim span — or a formula drawn as its TeX — in the code style:
3064    /// its text at its content's offset, bracketed by its raw delimiters when
3065    /// `show` says the line is revealed and by nothing (plus the caret's home
3066    /// at the content's end) when it isn't.
3067    ///
3068    /// Not [`inline_delimited`](Self::inline_delimited): verbatim has no child
3069    /// nodes to recurse into — its content is its own `text` — so the fences
3070    /// bracket a [`push_text`] instead. The fences themselves keep
3071    /// `Role::Code`'s sibling treatment via [`push_delim`]'s role override.
3072    ///
3073    /// [`push_delim`]: Self::push_delim
3074    fn inline_verbatim(&self, id: usize, base: Style, out: &mut Vec<Glyph>, show: bool) {
3075        let node = &self.nodes[id];
3076        // The interior begins at `content_span.start` — past however many
3077        // backticks the fence used, which `span.start + 1` only guessed right
3078        // for a single one. Fall back to that guess if it's absent.
3079        let at = node
3080            .content_span
3081            .as_ref()
3082            .map_or(node.span.start + 1, |c| c.start);
3083        let style = base.role(Role::Code);
3084        let show = show.then(|| self.delims(id)).flatten();
3085        if let Some((open, _)) = &show {
3086            self.push_delim(out, open, style);
3087        }
3088        push_text(out, node.text.as_deref().unwrap_or(""), at, style);
3089        match &show {
3090            Some((_, close)) => self.push_delim(out, close, style),
3091            None => self.note_mark_end(id),
3092        }
3093    }
3094
3095    fn children(&self, id: usize) -> Vec<usize> {
3096        let mut out = Vec::new();
3097        let mut c = self.nodes[id].first_child;
3098        while let Some(cid) = c {
3099            out.push(cid.0 as usize);
3100            c = self.nodes[cid.0 as usize].next_sibling;
3101        }
3102        out
3103    }
3104
3105    /// Render a node's block children, a blank separator between each. `tight`
3106    /// suppresses the *fabricated* separator between adjacent children that share
3107    /// a source line boundary — a tight list item and the sub-list nested in it —
3108    /// while a real blank source line between them still opens a gap.
3109    fn blocks(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph], tight: bool) {
3110        // Frontmatter (a leading `metadata` block) is document metadata, not
3111        // prose: hide it entirely in the rich-text view. Skipping it here means
3112        // no phantom blank rows for its lines and no separator before the first
3113        // real block — the document opens straight into its content.
3114        let kids: Vec<usize> = self
3115            .children(id)
3116            .into_iter()
3117            .filter(|&c| self.nodes[c].kind != Kind::Metadata)
3118            .collect();
3119        let mut above: Option<BlockClass> = None;
3120        for child in kids {
3121            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
3122            let before_sep = self.rows.len();
3123            if let Some(above) = above {
3124                self.emit_separators_before(
3125                    self.nodes[child].span.start,
3126                    pc,
3127                    !tight,
3128                    Boundary { above, below },
3129                );
3130            }
3131            // The first *drawn* child wears the first-row prefix (a bullet, a
3132            // footnote label), not the first child: a comment opening a list
3133            // item draws nothing, and the bullet belongs to what follows it.
3134            let first = if above.is_none() { pf } else { pc };
3135            if self.block_or_hidden(child, before_sep, first, pc) {
3136                above = Some(below);
3137            }
3138        }
3139    }
3140
3141    /// Render `child` after the separator [`Builder::emit_separators_before`]
3142    /// spelled for it from row `before_sep` on, and say whether it drew
3143    /// anything.
3144    ///
3145    /// A block that draws no rows — an HTML comment, which the rich view hides
3146    /// the way it hides frontmatter — is still *there* in the source, and the
3147    /// walk has to step over it: `last_off` moves past it so the next separator
3148    /// counts the blank lines from its end, not from wherever the last drawn
3149    /// block stopped. Left where it was, the separator counted every line of the
3150    /// comment as a blank row; and the cached path, whose per-block builder
3151    /// starts at offset 0, handed back a `last_off` of 0 and counted every line
3152    /// of the *document* — one phantom blank row per source line, once per
3153    /// comment. The separator drawn for it is taken back too, so a hidden block
3154    /// leaves no gap of its own: what stands either side of it meets across one
3155    /// boundary, as if the comment were not there.
3156    fn block_or_hidden(
3157        &mut self,
3158        child: usize,
3159        before_sep: usize,
3160        pf: &[Glyph],
3161        pc: &[Glyph],
3162    ) -> bool {
3163        let after_sep = self.rows.len();
3164        self.block(child, pf, pc);
3165        if self.rows.len() > after_sep {
3166            return true;
3167        }
3168        self.rows.truncate(before_sep);
3169        let end = self.nodes[child].span.end;
3170        self.last_off = self.last_off.max(end);
3171        self.stepped_over = self.stepped_over.max(end);
3172        false
3173    }
3174
3175    /// Render an explicit, ordered list of top-level blocks — [`Builder::blocks`]
3176    /// for a walk that isn't "the children of one node". The document's top level
3177    /// no longer is: a footnote definition is a root beside `doc`, not under it,
3178    /// and [`top_level`] merges it into this list by source position.
3179    ///
3180    /// The separator between blocks is spelled by the same
3181    /// [`Builder::emit_separators_before`] the incremental top-level walk in
3182    /// [`build_cached`] uses, so the two paths can't drift on how a boundary
3183    /// looks.
3184    ///
3185    /// Returns the class of the last block that drew anything — what the
3186    /// trailing blank lines close — or `None` when nothing did.
3187    fn top_blocks(&mut self, ids: &[usize]) -> Option<BlockClass> {
3188        let mut above: Option<BlockClass> = None;
3189        for &child in ids {
3190            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
3191            let before_sep = self.rows.len();
3192            if let Some(above) = above {
3193                self.emit_separators_before(
3194                    self.nodes[child].span.start,
3195                    &[],
3196                    true,
3197                    Boundary { above, below },
3198                );
3199            }
3200            if self.block_or_hidden(child, before_sep, &[], &[]) {
3201                above = Some(below);
3202            }
3203        }
3204        above
3205    }
3206
3207    /// Emit the blank separator row(s) that sit between a block ending at the
3208    /// current `last_off` and the next block starting at `next_start`, wearing
3209    /// the continuation prefix `pc`. Shared by [`Builder::blocks`] and the
3210    /// incremental top-level walk so the two can't drift on how a boundary is
3211    /// spelled.
3212    ///
3213    /// The blank line(s) between two blocks are real caret stops, each needing
3214    /// its *own* source offset — one strictly past the previous block's content,
3215    /// else it collides with that block's last row and `pos_of_offset`
3216    /// (first-match-wins) would resolve the caret onto the wrong row, pinning
3217    /// downward motion there.
3218    ///
3219    /// One row *per* blank source line, not a single collapsed separator: an
3220    /// empty paragraph opened between two blocks (Enter in the gap,
3221    /// `…\n\n\n\n…`) must be a navigable empty row, not vanish — else the caret
3222    /// in it snaps onto the *next* block's start and Enter looks like it did
3223    /// nothing.
3224    fn emit_separators_before(
3225        &mut self,
3226        next_start: usize,
3227        pc: &[Glyph],
3228        synthetic: bool,
3229        boundary: Boundary,
3230    ) {
3231        let mut offs = self.blank_rows_between(self.last_off, next_start);
3232        if offs.is_empty() {
3233            if !synthetic {
3234                // A tight list item's own text sits directly above the sub-list
3235                // nested in it — no fabricated gap. The "breathe" row belongs
3236                // between free-standing blocks, not between an item and its
3237                // child list, which the source writes on the very next line. A
3238                // real blank source line (a loose list) still lands a gap below,
3239                // because `blank_rows_between` found it and we never reach here.
3240                return;
3241            }
3242            // A tight gap with no blank line (e.g. a heading directly above its
3243            // text): keep the one conventional separator row so blocks still
3244            // breathe, as they always have.
3245            offs.push(self.blank_line_offset(self.last_off, next_start));
3246        }
3247        let last = offs.len() - 1;
3248        for (k, end_src) in offs.into_iter().enumerate() {
3249            // Only the drawn-only rows carry the boundary: the navigable blank
3250            // lines between them (and every blank line under preserve-soft flow)
3251            // are somewhere text can go, not a gap between blocks, and a frontend
3252            // that shrank one would be shrinking a line the author is typing on.
3253            let drawn = !self.preserve_soft && (k == 0 || k == last);
3254            // The blank line a boundary is *drawn* with isn't a place text can
3255            // go. The first one closes the block above and the last one opens the
3256            // block below — with a single blank line, the usual case, doing both
3257            // at once. Typing on either just continues the paragraph it abuts,
3258            // since the blank line it would need to be a paragraph of its own is
3259            // the very line being typed on. So they're a gap, like a table's
3260            // border: drawn, clickable, never a caret's home.
3261            //
3262            // The lines *between* them are the real ones. That's what Enter
3263            // opens: it inserts a paragraph break (`\n\n`), which leaves a blank
3264            // line spare on each side and the caret on the navigable line
3265            // between them.
3266            //
3267            // Preserve flow is the exception: there a bare `\n` is a visible line
3268            // break the author edits directly, so a lone blank line *is* a caret
3269            // home — typing on it makes the soft break the mode exists to show,
3270            // and Enter at a line's end lands the caret on exactly this row. So no
3271            // separator is drawn-only; every blank line is navigable.
3272            self.rows.push(VRow {
3273                glyphs: pc.to_vec(),
3274                end_src,
3275                decoration: drawn,
3276                code: false,
3277                code_lang: None,
3278                directive: false,
3279                directive_label: None,
3280                media: None,
3281                task: None,
3282                leaf_directive: None,
3283                heading: None,
3284                align: None,
3285                line_height: None,
3286                boundary: drawn.then_some(boundary),
3287                mark_ends: Vec::new(),
3288                math: Vec::new(),
3289            });
3290        }
3291    }
3292
3293    /// One block, drawn under whatever presentation the containers around it
3294    /// impose.
3295    ///
3296    /// A container named `div` with `Element` origin is transparent already —
3297    /// its children draw as themselves — and it now also *contributes* its
3298    /// vocabulary keys to every block it holds. That is the reading side of
3299    /// twig's own rule for where a Markdown block's attributes live: there is
3300    /// no attribute syntax to put on the paragraph, so `set_block_attrs` writes
3301    /// a `<div …>` around it, and reading one back has to look through the div.
3302    /// `<div class="center">` around three paragraphs centres all three, which
3303    /// is what the author of that HTML meant, and around one is the sole-child
3304    /// shape twig writes.
3305    ///
3306    /// Saved and restored rather than pushed onto a stack, so a nested div
3307    /// reads its own keys over its parent's and the block *after* the div is
3308    /// unaffected.
3309    fn block(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
3310        if element_tag(&self.nodes[id]) == Some("div") {
3311            let saved = self.presentation;
3312            self.presentation = saved.under(&self.nodes[id].attrs, &self.faces);
3313            self.block_kind(id, pf, pc);
3314            self.presentation = saved;
3315            // Step the walk past the closing `</div>`, as the fenced-div arm
3316            // below anchors past its `:::`. The tag sits on a line of its own
3317            // after the last child and the blank line under it, and the rich
3318            // view draws nothing for it — so left where the last child ended,
3319            // the separator logic read the tag's line as a blank line between
3320            // the div and the block below, and drew a navigable empty row there
3321            // that the author never opened and Backspace could not close; and
3322            // at the end of the document the trailing count read it as an empty
3323            // paragraph the author had left. It is hidden markup the walk steps
3324            // over, which is what `stepped_over` records, so both counts start
3325            // past it.
3326            let end = self.nodes[id].span.end;
3327            self.last_off = self.last_off.max(end);
3328            self.stepped_over = self.stepped_over.max(end);
3329            return;
3330        }
3331        self.block_kind(id, pf, pc);
3332    }
3333
3334    fn block_kind(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
3335        let node = &self.nodes[id];
3336        match node.kind.as_str() {
3337            "doc" | "section" => self.blocks(id, pf, pc, false),
3338            "heading" => {
3339                // A heading whose only visible content is a single image — a
3340                // banner set in an `<h1>` (`<h1><picture><img></picture></h1>`),
3341                // or `# ![](banner.png)` — is a block picture, not text. Render
3342                // it as one; anything with real heading text falls through.
3343                if let Some((m, kind)) = self.media_only(id) {
3344                    self.block_media(m, kind, id, pf);
3345                    return;
3346                }
3347                let level = node.level.unwrap_or(1);
3348                // A `data-size` on a heading scales the *heading's* ramp, not
3349                // the body's — the role and the step compose rather than
3350                // compete, which is the same thing a colour does to a link.
3351                let pres = self.presentation.under(&node.attrs, &self.faces);
3352                let style = pres.over(heading_style(level));
3353                let mut glyphs = Vec::new();
3354                // On the revealed line the `# ` comes back as real, editable
3355                // text in front of the heading. Only the opening marker: a
3356                // closing `#`-run (`## title ##`) is covered by the same
3357                // `delims` pair, and a setext underline is excluded there for
3358                // being on another line entirely.
3359                if let Some((open, close)) =
3360                    self.revealed(&node.span).then(|| self.delims(id)).flatten()
3361                {
3362                    self.push_delim(&mut glyphs, &open, style);
3363                    glyphs.extend(self.inline_children_with_trailing(id, style));
3364                    self.push_delim(&mut glyphs, &close, style);
3365                } else {
3366                    glyphs = self.inline_children_with_trailing(id, style);
3367                }
3368                // An *empty* heading — `# ` with nothing typed after it, which is
3369                // what the toolbar's H1 leaves on a blank line — has no glyph for
3370                // its row to end on, so the fallback below is the row's whole
3371                // extent: its only caret stop, and the offset every row after it
3372                // is measured from. The block's start is the wrong answer for
3373                // both, because it sits *in front of* the `# ` the rich view
3374                // hides: the caret drew (and typed) before the hashes, and the
3375                // rows below inherited an offset short by the marker's length,
3376                // which put the caret on one of them the moment the heading grew
3377                // text. Its content's start is where the caret belongs.
3378                let home = heading_content_start(self.source, &node.span);
3379                let first = self.rows.len();
3380                self.emit_wrapped(glyphs, home, pf, pc);
3381                // Stamp the level on every row the heading just emitted — a
3382                // wrapped heading's continuation rows as much as its first, and
3383                // an empty one's single glyphless row, which is the whole point
3384                // (see [`VRow::heading`]).
3385                for row in &mut self.rows[first..] {
3386                    row.heading = Some(level.min(255) as u8);
3387                    row.align = pres.align;
3388                    row.line_height = pres.line_height;
3389                }
3390            }
3391            "block_quote" => {
3392                let (start, end) = (node.span.start, node.span.end);
3393                let gutter = synth("│ ", Role::QuoteGutter, start);
3394                let f = concat(pf, &gutter);
3395                let c = concat(pc, &gutter);
3396                // A childless quote — a bare `> ` on an otherwise blank line,
3397                // which is what the toolbar's Quote button leaves there — has no
3398                // inner block to carry the gutter or a caret home, so `blocks`
3399                // emitted *nothing at all*: the quote didn't merely draw
3400                // unstyled, it disappeared, and a document that was only `> `
3401                // rendered zero rows with the caret nowhere to stand. Emit the
3402                // gutter row itself, ending just past the marker, exactly as an
3403                // empty `list_item` emits its bare bullet.
3404                if self.children(id).is_empty() {
3405                    self.push_row_at(f, end.min(self.source.len()));
3406                } else {
3407                    self.blocks(id, &f, &c, false);
3408                    self.emit_quote_trailing_lines(&c, end);
3409                }
3410            }
3411            // A generic `:::name{.class}` fenced-div container (twig's
3412            // `directive`, container form). Core is agnostic of `name` — it's
3413            // the host app's vocabulary (diaryx's `vis` for audience
3414            // visibility, say) and isn't available here regardless: twig only
3415            // threads an `element`'s tag name through `FlatNode::name`, not a
3416            // directive's own identifier. Every row gets marked `directive` (a
3417            // frontend draws a tinted panel around each maximal run, the
3418            // `code`/`code_block` recipe) and the first row carries a label —
3419            // the way a code fence's language rides only its first row.
3420            //
3421            // The label reads BOTH attribute conventions diaryx content
3422            // actually uses: twig's own dot-prefixed classes (`{.public
3423            // .family}`, one combined `class` attr) and bare pandoc-style
3424            // words with no leading dot (`{public family}` — the syntax
3425            // `diaryx_core::visibility`'s hand-rolled publish-time filter and
3426            // apps/web's directive serializer both write; twig parses each
3427            // bare word as its own attribute with an empty value, per
3428            // `languages/markdown/attributes.zig`). Reading only `.class`
3429            // would leave every *existing* diaryx `:::vis{...}` block
3430            // unlabeled.
3431            // Only the *container* form is the panel below. A `text` directive
3432            // is inline and never reaches the block walker (see `is_inline`); a
3433            // `leaf` one is a standalone block with no body, drawn as a
3434            // placeholder the way an image is.
3435            "container"
3436                if container_is_directive(node)
3437                    && node.directive_form == Some(DirectiveForm::Leaf) =>
3438            {
3439                self.block_directive(id, pf);
3440            }
3441            // djot has no *leaf* directive form. `insert_directive` spells the
3442            // same document as an empty `::: page-break` fence — a container
3443            // with nothing in it — and the name comes back as the fence's one
3444            // class rather than as the node's name, because djot's div is
3445            // anonymous. Draw it as the placeholder Markdown's `::page-break`
3446            // gets, so a frontend that paginates on a `page-break`
3447            // [`DirectiveMark`] cannot tell which format the file is in.
3448            //
3449            // Narrow on purpose: only an *anonymous* empty fence. A Markdown
3450            // `:::note` with nothing in it keeps the reading it has, because
3451            // its name is its own and nothing about it says "a block with no
3452            // body" the way djot's spelling of a leaf directive does.
3453            "container"
3454                if container_is_directive(node)
3455                    && node.directive_form == Some(DirectiveForm::Container)
3456                    && node.name.as_deref().unwrap_or_default().is_empty()
3457                    && self.children(id).is_empty()
3458                    && !leaf_directive_identity(node).0.is_empty() =>
3459            {
3460                self.block_directive(id, pf);
3461            }
3462            "container" if container_is_directive(node) => {
3463                let label = directive_attr_label(&node.attrs);
3464                let start_row = self.rows.len();
3465                self.blocks(id, pf, pc, false);
3466                for (i, row) in self.rows[start_row..].iter_mut().enumerate() {
3467                    row.directive = true;
3468                    if i == 0 {
3469                        row.directive_label = label.clone();
3470                    }
3471                }
3472                // Anchor the block's end past its closing `:::` fence, exactly as
3473                // the code-block arm anchors past its ```` ``` ````. A container's
3474                // last content row ends at its last *child*, before the fence and
3475                // the blank line under it, so the separator logic counted the
3476                // fence line as a blank row of its own and drew a second boundary
3477                // — one gap's worth of margin twice, under every fenced div.
3478                self.last_off = node.span.end;
3479            }
3480            "bullet_list" | "ordered_list" | "task_list" => {
3481                let ordered = node.kind == Kind::OrderedList;
3482                let mut item_no = 0usize;
3483                let kids = self.children(id);
3484                for (i, child) in kids.iter().copied().enumerate() {
3485                    let kind = &self.nodes[child].kind;
3486                    if *kind == Kind::ListItem || *kind == Kind::TaskListItem {
3487                        let start = self.nodes[child].span.start;
3488                        item_no += 1;
3489                        // A task item's box replaces the bullet rather than
3490                        // joining it. The `[ ] ` that spells it is markup twig
3491                        // has already consumed — the item's paragraph *content*
3492                        // starts past it — so without a drawn box a task item
3493                        // was indistinguishable from a plain bullet, ticked or
3494                        // not. `☐`/`☑` is the marker for the same reason `•` is:
3495                        // it stands where the source's own marker stands. Which
3496                        // way it faces is `checked`, straight off the node.
3497                        let checked = self.nodes[child].checked;
3498                        let marker = match (checked, ordered) {
3499                            (Some(true), _) => "☑ ".to_string(),
3500                            (Some(false), _) => "☐ ".to_string(),
3501                            (None, true) => format!("{item_no}. "),
3502                            (None, false) => "• ".to_string(),
3503                        };
3504                        let bullet = synth(&marker, Role::ListMarker, start);
3505                        let indent = synth(&" ".repeat(text_width(&marker)), Role::Body, start);
3506                        let first_row = self.rows.len();
3507                        self.block(child, &concat(pc, &bullet), &concat(pc, &indent));
3508                        // On the item's first row, the way `code_lang` rides the
3509                        // first row of its block.
3510                        if let (Some(c), Some(row)) = (checked, self.rows.get_mut(first_row)) {
3511                            row.task = Some(c);
3512                        }
3513                    } else {
3514                        // twig can nest a *following* top-level block as a direct
3515                        // child of the list rather than a sibling of it — e.g.
3516                        // `- item\n\n> quote` parses the block quote under the
3517                        // `bullet_list`. It isn't a list item, so render it de-nested:
3518                        // no bullet, at the list's own prefix, with the usual block
3519                        // separator — never `• │ quote`.
3520                        if i > 0 {
3521                            self.emit_separators_before(
3522                                self.nodes[child].span.start,
3523                                pc,
3524                                true,
3525                                Boundary {
3526                                    above: BlockClass::from_node_kind(
3527                                        &self.nodes[kids[i - 1]].kind,
3528                                    ),
3529                                    below: BlockClass::from_node_kind(&self.nodes[child].kind),
3530                                },
3531                            );
3532                        }
3533                        self.block(child, pc, pc);
3534                    }
3535                }
3536            }
3537            "list_item" | "task_list_item" => {
3538                // A childless item — the empty bullet you get the instant you
3539                // press Enter to open a new one — has no inner block to carry the
3540                // marker prefix or a caret home, so `blocks` would emit nothing
3541                // and the new bullet simply wouldn't appear until something was
3542                // typed into it. Emit the prefixed row itself, ending at a caret
3543                // stop just past the marker (the item's `span.end`), the way an
3544                // empty paragraph emits its one prefixed row via `emit_wrapped`.
3545                if self.children(id).is_empty() {
3546                    let home = self.nodes[id].span.end.min(self.source.len());
3547                    self.push_row_at(pf.to_vec(), home);
3548                } else {
3549                    // Tight: an item's text and the list nested under it butt
3550                    // together (`• a` / `  • b`), no fabricated blank row between —
3551                    // a loose item's real blank line still parts them.
3552                    self.blocks(id, pf, pc, true);
3553                }
3554            }
3555            // A footnote *definition* (`[^1]: the note`). It reaches this walker
3556            // only because [`top_level`] merges it back in — twig hangs it off no
3557            // parent at all, so a walk from `doc` never sees one and every byte
3558            // of its body used to render as nothing.
3559            //
3560            // Drawn as a hanging-indent item, the way a list item is: the marker
3561            // reads `[1] `, matching the `[1]` its references render as, so the
3562            // two can be paired by eye, and the body wraps under it. The marker
3563            // is synthetic decoration (one shared offset, never a caret stop) —
3564            // the `[^1]: ` that spells it in the source is markup, hidden like a
3565            // heading's `# `.
3566            "footnote" => {
3567                let (start, end) = (node.span.start, node.span.end);
3568                let source = self.source;
3569                let marker = format!("[{}] ", footnote_label(source, start).unwrap_or(""));
3570                let indent = " ".repeat(text_width(&marker));
3571                let f = concat(pf, &synth(&marker, Role::ListMarker, start));
3572                let c = concat(pc, &synth(&indent, Role::Body, start));
3573                if self.children(id).is_empty() {
3574                    // A definition with no body yet — the instant `[^1]: ` has
3575                    // been typed and nothing after it. `blocks` would emit
3576                    // nothing and the definition simply wouldn't appear, so emit
3577                    // the marker row itself with a caret home just past it,
3578                    // exactly as an empty list item does.
3579                    self.push_row_at(f, end.min(source.len()));
3580                } else {
3581                    self.blocks(id, &f, &c, false);
3582                }
3583            }
3584            // A link reference definition (`[foo]: /url`): resolved by label
3585            // into the links that use it, and drawn nowhere — the rich view has
3586            // no more use for its line than for a comment's. It is walked at all
3587            // (see [`top_level`]) so [`Builder::block_or_hidden`] can step the
3588            // walk past its bytes rather than count them as blank lines.
3589            "reference" => {}
3590            "table" => self.table(id, pf, pc),
3591            "code_block" => {
3592                let style = Style::default().role(Role::Code);
3593                let text = node.text.clone().unwrap_or_default();
3594                // Cut the block's *terminator*, not every trailing newline. A
3595                // block whose last line is empty spells that as a second `\n`,
3596                // and `trim_end_matches` ate it along with the terminator: the
3597                // Return that made the line got no row, so the caret placed on
3598                // it fell through to the paragraph below and typing landed
3599                // outside the block. twig's `content_span` is `text` less
3600                // exactly this one newline, so cutting one and no more is also
3601                // what keeps `code_line_offsets` lined up.
3602                let lines: Vec<&str> = text
3603                    .strip_suffix('\n')
3604                    .unwrap_or(text.as_str())
3605                    .split('\n')
3606                    .collect();
3607                // Each line at its own source offset, so the caret can walk the
3608                // code a character at a time like any other text. Where the
3609                // lines can't be lined up with the source there's no honest
3610                // offset to give, so the block maps coarsely to its start (and
3611                // stays a source-view job, as all of it once was).
3612                let offs = node
3613                    .content_span
3614                    .as_ref()
3615                    .and_then(|c| self.code_line_offsets(c, &lines));
3616                // The fence's info string, carried on the block's first row as
3617                // its language label (`None` for an indented block or a bare
3618                // fence). Kept on the row so it rides the block cache.
3619                let lang = code_language(self.source, node.span.start);
3620                // The block's syntax highlighting, a token per byte range of
3621                // each line — `None` unless the fence names a language the
3622                // grammars know (and unless the `syntax` feature is on). Done
3623                // here, once per build of the block, because the rows it
3624                // colours ride the block cache: an edit elsewhere in the
3625                // document reuses them, tokens and all.
3626                let tokens = lang.as_deref().and_then(|l| code_tokens(l, &lines));
3627                for (i, raw) in lines.iter().enumerate() {
3628                    let at = offs.as_ref().map_or(node.span.start, |o| o[i]);
3629                    // No gutter glyph: the block is set apart by the border and
3630                    // tint a frontend draws around the whole run of `code` rows,
3631                    // not by a per-line mark. Just the block prefix (a list
3632                    // indent, a quote gutter) and the code text.
3633                    let mut glyphs: Vec<Glyph> = pf.to_vec();
3634                    match tokens.as_ref().and_then(|t| t.get(i)) {
3635                        Some(spans) => push_code_text(&mut glyphs, raw, at, style, spans),
3636                        None => push_text(&mut glyphs, raw, at, style),
3637                    }
3638                    // Explicitly past the line's *text*: a blank code line has no
3639                    // glyph, and any prefix's offset would put the row's end
3640                    // inside the next line.
3641                    self.push_row_at(glyphs, at + raw.len());
3642                    if let Some(row) = self.rows.last_mut() {
3643                        row.code = true;
3644                        if i == 0 {
3645                            row.code_lang = lang.clone();
3646                        }
3647                    }
3648                }
3649                // Anchor the block's end past its closing fence. Its last content
3650                // row ends at the last code line, before the ``` and the blank
3651                // line under it; without this the separator logic would count the
3652                // closing-fence line as its own blank row and open a phantom
3653                // second gap below the block.
3654                self.last_off = node.span.end;
3655            }
3656            "thematic_break" => {
3657                let full = self.wrap.unwrap_or(UNWRAPPED_RULE_WIDTH);
3658                let w = full.saturating_sub(prefix_width(pf)).max(4);
3659                let mut glyphs = pf.to_vec();
3660                for _ in 0..w {
3661                    glyphs.push(Glyph {
3662                        ch: '─',
3663                        style: Style::default().role(Role::Rule),
3664                        src: node.span.start,
3665                        // A rule is a block the caret can sit on, as it always
3666                        // has; it maps coarsely to the block's start.
3667                        stop: true,
3668                    });
3669                }
3670                // The dashes share one caret home in front of the atomic block,
3671                // while the row's end is the second home just past its source.
3672                // Without that trailing stop a final rule made the document end
3673                // unreachable: Right could not cross it and a click in the
3674                // empty space below it snapped back before the rule.
3675                let after_line = node.span.end
3676                    + self.source[node.span.end..]
3677                        .strip_prefix("\r\n")
3678                        .map_or_else(
3679                            || usize::from(self.source[node.span.end..].starts_with('\n')),
3680                            |_| 2,
3681                        );
3682                self.push_row_at(glyphs, after_line);
3683            }
3684            // A block-level image node with no wrapping paragraph — a promoted
3685            // top-level HTML `<img>` lands as a direct `doc` child like this
3686            // (a Markdown `![](…)` comes wrapped in a `para`, handled below).
3687            "image" => self.block_media(id, MediaKind::Image, id, pf),
3688            // The same case for a promoted top-level `<video>`/`<audio>`, which
3689            // arrives as a generic `container` rather than a node kind of its
3690            // own. It can't be found by the `media_only` scan below the way a
3691            // wrapped one is: that scan looks at a wrapper's *children*, and here
3692            // the media element is itself the block.
3693            "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
3694                let kind = match element_tag(node) {
3695                    Some("audio") => MediaKind::Audio,
3696                    _ => MediaKind::Video,
3697                };
3698                self.block_media(id, kind, id, pf);
3699            }
3700            _ => {
3701                // A container of blocks, or an inline-bearing paragraph.
3702                let kids = self.children(id);
3703                // A block-level image: a paragraph (or other wrapper — a
3704                // `<picture>`, an `<h1>` banner) whose only visible content is a
3705                // single `image` node. Render it as a placeholder row + record an
3706                // [`MediaInfo`] a capable frontend replaces. An image mixed with
3707                // real text or other images on the line isn't block-level and
3708                // falls through to the inline path below, still as its alt text.
3709                if let Some((m, kind)) = self.media_only(id) {
3710                    self.block_media(m, kind, id, pf);
3711                    return;
3712                }
3713                // A display formula on lines of its own — a paragraph whose
3714                // only visible content is one `display_math` — promotes the
3715                // same way, to a placeholder row and a [`MathMark`].
3716                if let Some(m) = self.math_only(id) {
3717                    self.block_math(m, pf, pc);
3718                    return;
3719                }
3720                let inline = !kids.is_empty() && kids.iter().all(|&c| is_inline(&self.nodes[c]));
3721                if inline || kids.is_empty() {
3722                    // The block's own attributes over its containers' — the
3723                    // three run-level keys become the style its glyphs start
3724                    // from, and the two line-level ones ride every row it
3725                    // emits, a wrapped paragraph's continuations included.
3726                    let pres = self.presentation.under(&node.attrs, &self.faces);
3727                    let glyphs =
3728                        self.inline_children_with_trailing(id, pres.over(Style::default()));
3729                    if !glyphs.is_empty() {
3730                        let first = self.rows.len();
3731                        self.emit_wrapped(glyphs, node.span.start, pf, pc);
3732                        for row in &mut self.rows[first..] {
3733                            row.align = pres.align;
3734                            row.line_height = pres.line_height;
3735                        }
3736                    }
3737                } else {
3738                    self.blocks(id, pf, pc, false);
3739                }
3740            }
3741        }
3742    }
3743
3744    /// Render a table as a box-drawn grid: every column as wide as its widest
3745    /// cell, the header bold and ruled off, each cell padded to its column's
3746    /// alignment. This is the *default* monospace rendering (see
3747    /// [`VisualMap::rows`]); the same cells are also published structurally as
3748    /// [`TableInfo`], so a frontend that lays the grid out in its own units draws
3749    /// from there and skips the picture built here.
3750    ///
3751    /// The alignment comes from twig's `cell.alignment` — the delimiter row
3752    /// (`|:--|--:|`) that spells it out is consumed by the parser and leaves no
3753    /// node, so the snapshot is the only source for it.
3754    ///
3755    /// Borders and padding are *decoration*: they carry the source offset of the
3756    /// text they surround, so a click lands in that cell, but they're never
3757    /// caret stops — the caret steps cell-to-cell instead of into the box art.
3758    fn table(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
3759        let node_end = self.nodes[id].span.end;
3760        // twig's shape is `[caption, row, row, …]`: the caption is always
3761        // present (usually empty in Markdown) and is not part of the grid.
3762        let row_ids: Vec<usize> = self
3763            .children(id)
3764            .into_iter()
3765            .filter(|&c| self.nodes[c].kind == Kind::Row)
3766            .collect();
3767        if row_ids.is_empty() {
3768            return;
3769        }
3770        // Lay every cell out first — the column widths depend on all of them.
3771        let grid: Vec<Vec<TableCell>> = row_ids.iter().map(|&r| self.row_cells(r)).collect();
3772        let heads: Vec<bool> = row_ids
3773            .iter()
3774            .map(|&r| self.nodes[r].head.unwrap_or(false))
3775            .collect();
3776        let cols = grid.iter().map(|r| r.len()).max().unwrap_or(0);
3777        if cols == 0 {
3778            return;
3779        }
3780        let mut widths = vec![0usize; cols];
3781        for row in &grid {
3782            for (c, cell) in row.iter().enumerate() {
3783                widths[c] = widths[c].max(cell_width(&cell.glyphs));
3784            }
3785        }
3786        // Every column at its widest cell is only the *wish*; a grid wider than
3787        // the surface has its far side hanging off the edge where no amount of
3788        // caret motion can reach it. Cut it down to what's actually there, and
3789        // let the cells wrap into the space they're given.
3790        if let Some(w) = self.wrap {
3791            fit_widths(&mut widths, w.saturating_sub(prefix_width(pc)));
3792        }
3793
3794        // Where the picture starts, so a frontend drawing its own grid knows
3795        // which rows to skip. Recorded before the first border goes down.
3796        let rows_start = self.rows.len();
3797
3798        let anchor = grid[0].first().map(|c| c.start).unwrap_or(node_end);
3799        self.push_rule(&rule_text(&widths, '┌', '┬', '┐'), anchor, pf);
3800        for (ri, row) in grid.iter().enumerate() {
3801            self.push_table_row(row, &widths, pc);
3802            // The rule under the header: only where the head actually ends.
3803            let ends_head = heads[ri] && heads.get(ri + 1) == Some(&false);
3804            if ends_head {
3805                let next = grid[ri + 1].first().map(|c| c.start).unwrap_or(node_end);
3806                self.push_rule(&rule_text(&widths, '├', '┼', '┤'), next, pc);
3807            }
3808        }
3809        // The bottom border is the one rule the caret can rest on: its end is
3810        // the table's trailing stop, the caret home just past the block — the
3811        // peer of a block picture's second stop, and of a rule's row end. Without
3812        // it a document ending in a table ended *inside* it: nothing after the
3813        // last cell was a stop, so Right could not leave the table, and a click
3814        // in the blank space under it snapped back into the last cell — or, on a
3815        // surface that resolved the click onto the border row, to the table's
3816        // first cell, since a decoration row's only stop is the nearest one.
3817        // Typing at the stop opens a paragraph first, as at a picture's — see
3818        // `Doc::open_paragraph_at_block_edge`. The glyphs stay non-stops at
3819        // `node_end`, so a click anywhere on the border lands past the table.
3820        self.push_rule_with_home(&rule_text(&widths, '└', '┴', '┘'), node_end, pc);
3821
3822        // The same cells the picture above was drawn from, published unwrapped
3823        // and unpadded for a frontend that lays them out in pixels.
3824        self.tables.push(TableInfo {
3825            rows_span: rows_start..self.rows.len(),
3826            end_src: node_end,
3827            // The *continuation* prefix: `pf` opens the block and only its first
3828            // row wears it, but every row of a grid is a continuation of the
3829            // block the table sits in.
3830            prefix: pc.to_vec(),
3831            grid: grid
3832                .into_iter()
3833                .zip(heads)
3834                .map(|(cells, head)| TableRow { head, cells })
3835                .collect(),
3836        });
3837        // The table's own end anchors whatever separator follows it; the border
3838        // rows deliberately don't move `last_off` (they hold no content).
3839        self.last_off = node_end;
3840    }
3841
3842    /// One row of laid-out cells, in column order.
3843    fn row_cells(&self, row: usize) -> Vec<TableCell> {
3844        // A cell is one source line, so a break within it is an explicit line
3845        // break (an inline `<br>`) that must render as a line of its own — not the
3846        // flow-folding space a break is in prose.
3847        self.break_glyph.set('\n');
3848        let cells = self
3849            .children(row)
3850            .into_iter()
3851            .filter(|&c| self.nodes[c].kind == Kind::Cell)
3852            .enumerate()
3853            .map(|(col, c)| {
3854                let n = &self.nodes[c];
3855                let style = if n.head.unwrap_or(false) {
3856                    Style::default().bold()
3857                } else {
3858                    Style::default()
3859                };
3860                // Only `content_span` bounds a cell's text, and an EMPTY cell
3861                // has none at all — twig records no interior for it — so both
3862                // offsets would fall back to the cell's `span.start`: on the
3863                // pipe that opens it, or (under a twig that gave every cell
3864                // the whole row's span) the row's start, where every empty
3865                // cell collapses onto one spot before the first `│` and a
3866                // caret there types *before* the table. Derive the interior
3867                // from the span's own pipes and this cell's column instead,
3868                // so each empty cell has a distinct, editable caret home.
3869                let span = n.content_span.clone().unwrap_or_else(|| {
3870                    let off = empty_cell_offset(
3871                        &self.source[n.span.start.min(self.source.len())
3872                            ..n.span.end.min(self.source.len())],
3873                        n.span.start,
3874                        col,
3875                    );
3876                    off..off
3877                });
3878                TableCell {
3879                    glyphs: self.inline_children(c, style),
3880                    start: span.start,
3881                    end: span.end,
3882                    align: n.alignment.unwrap_or(Alignment::Default),
3883                }
3884            })
3885            .collect();
3886        self.break_glyph.set(' ');
3887        cells
3888    }
3889
3890    /// A horizontal rule between/around rows — entirely decoration.
3891    fn push_rule(&mut self, text: &str, src: usize, prefix: &[Glyph]) {
3892        self.push_rule_row(text, src, prefix, true);
3893    }
3894
3895    /// A table's bottom border: drawn like the other rules, but a row the caret
3896    /// can rest on, its end (`src`) being the table's trailing stop.
3897    fn push_rule_with_home(&mut self, text: &str, src: usize, prefix: &[Glyph]) {
3898        self.push_rule_row(text, src, prefix, false);
3899    }
3900
3901    fn push_rule_row(&mut self, text: &str, src: usize, prefix: &[Glyph], decoration: bool) {
3902        let glyphs = concat(prefix, &synth(text, Role::Rule, src));
3903        self.rows.push(VRow {
3904            glyphs,
3905            end_src: src,
3906            decoration,
3907            code: false,
3908            code_lang: None,
3909            directive: false,
3910            directive_label: None,
3911            media: None,
3912            task: None,
3913            leaf_directive: None,
3914            heading: None,
3915            align: None,
3916            line_height: None,
3917            boundary: None,
3918            mark_ends: Vec::new(),
3919            math: Vec::new(),
3920        });
3921    }
3922
3923    /// One `│ a │ b │` row of the grid: real cell text between decoration.
3924    ///
3925    /// A row of cells is not a row of the screen — a cell wrapped to its column
3926    /// spans several, each one `│`-divided across the full width so the grid
3927    /// stays square. Cells in the same row are laid out independently and run
3928    /// out at their own heights; a column that has run dry pads out as
3929    /// decoration while its neighbours keep going.
3930    fn push_table_row(&mut self, cells: &[TableCell], widths: &[usize], prefix: &[Glyph]) {
3931        let fallback = cells.last().map(|c| c.end).unwrap_or(0);
3932        let laid: Vec<Vec<Vec<Glyph>>> = cells
3933            .iter()
3934            .enumerate()
3935            .map(|(ci, c)| wrap_glyphs(&c.glyphs, widths.get(ci).copied().unwrap_or(0)))
3936            .collect();
3937        let height = laid.iter().map(|l| l.len()).max().unwrap_or(1).max(1);
3938
3939        for j in 0..height {
3940            let mut glyphs = prefix.to_vec();
3941            for (ci, &w) in widths.iter().enumerate() {
3942                let cell = cells.get(ci);
3943                let line = laid.get(ci).and_then(|l| l.get(j));
3944                // The divider before this column belongs to the cell it
3945                // introduces, so clicking it lands in that cell — on this line
3946                // of it, which is what's next to the divider being clicked.
3947                let at = line
3948                    .and_then(|l| l.first().map(|g| g.src))
3949                    .or_else(|| cell.map(|c| c.start))
3950                    .unwrap_or(fallback);
3951                glyphs.extend(synth("│", Role::Rule, at));
3952                match (cell, line) {
3953                    (Some(cell), Some(line)) => {
3954                        let pad = w.saturating_sub(glyphs_width(line));
3955                        let (lead, trail) = match cell.align {
3956                            Alignment::Right => (pad, 0),
3957                            Alignment::Center => (pad / 2, pad - pad / 2),
3958                            Alignment::Left | Alignment::Default => (0, pad),
3959                        };
3960                        // Every line renders at least one space after its text
3961                        // (the gutter before `│`), so there is always somewhere
3962                        // to put the "after the last character" caret a line
3963                        // needs. It's the one padding glyph that is a stop: on
3964                        // the cell's last line that's the cell's end, and on any
3965                        // other it's the space the wrap consumed.
3966                        let last = laid[ci].len() == j + 1;
3967                        let end = match last {
3968                            true => cell.end,
3969                            false => line
3970                                .last()
3971                                .map(|g| g.src + g.ch.len_utf8())
3972                                .unwrap_or(cell.end),
3973                        };
3974                        glyphs.extend(synth(&" ".repeat(lead + 1), Role::Body, at));
3975                        glyphs.extend(line.iter().cloned());
3976                        glyphs.push(Glyph {
3977                            ch: ' ',
3978                            style: Style::default(),
3979                            src: end,
3980                            stop: true,
3981                        });
3982                        glyphs.extend(synth(&" ".repeat(trail), Role::Body, end));
3983                    }
3984                    // A ragged row, or a column whose cell ended higher up: pad
3985                    // it out so the grid stays square.
3986                    _ => {
3987                        let at = cell.map(|c| c.end).unwrap_or(fallback);
3988                        glyphs.extend(synth(&" ".repeat(w + 2), Role::Body, at));
3989                    }
3990                }
3991            }
3992            glyphs.extend(synth("│", Role::Rule, fallback));
3993            // The row ends where its last stop does. A table row has no gap
3994            // between its final cell and the border, so inventing an end past
3995            // that would be a stop with nothing under it.
3996            let end_src = glyphs
3997                .iter()
3998                .rev()
3999                .find(|g| g.stop)
4000                .map_or(fallback, |g| g.src);
4001            let mark_ends = self.take_mark_ends(end_src);
4002            let math = self.take_math(&glyphs);
4003            self.rows.push(VRow {
4004                glyphs,
4005                end_src,
4006                decoration: false,
4007                code: false,
4008                code_lang: None,
4009                directive: false,
4010                directive_label: None,
4011                media: None,
4012                task: None,
4013                leaf_directive: None,
4014                heading: None,
4015                align: None,
4016                line_height: None,
4017                boundary: None,
4018                mark_ends,
4019                math,
4020            });
4021        }
4022    }
4023
4024    /// Render a block-level image, video, or audio as one placeholder row: the
4025    /// `🖼 alt` / `🎬 alt` / `🔊 alt` label styled [`Role::Image`], every glyph
4026    /// mapped to the media's start offset and a caret stop there (they share the
4027    /// offset, so the stop table dedups them to a single home in front of it, as
4028    /// a rule's dashes do), and the row's end stop set past it so the caret can
4029    /// also rest after it. The row carries a [`MediaMark`] so [`media_spans`]
4030    /// publishes it as a [`MediaInfo`] a capable frontend replaces with the real
4031    /// picture or player; a plain surface paints the label as-is. `pf` is the
4032    /// block prefix (a list indent, a quote gutter) the row opens with, exactly
4033    /// as every other block honours it.
4034    fn block_media(&mut self, img: usize, kind: MediaKind, wrapper: usize, pf: &[Glyph]) {
4035        let node = &self.nodes[img];
4036        let start = node.span.start;
4037        let end = node.span.end;
4038        // An `image`'s URL is twig's `destination`; a `<video>`/`<audio>` is a
4039        // generic element, so its URL is the `src` attribute — and may be absent
4040        // entirely, the element naming its candidates in child `<source>`s.
4041        let destination = match kind {
4042            MediaKind::Image => node.destination.clone().unwrap_or_default(),
4043            MediaKind::Video | MediaKind::Audio => attr_of(node, "src").unwrap_or_default(),
4044        };
4045        let poster = match kind {
4046            MediaKind::Video => attr_of(node, "poster").unwrap_or_default(),
4047            MediaKind::Image | MediaKind::Audio => String::new(),
4048        };
4049        // The `<source>`s under the media element itself, not under `wrapper`: a
4050        // `<video>` is its own container, unlike an `<img>`, whose `<picture>`
4051        // alternatives are its *siblings* and so only reachable from the wrapper.
4052        let sources = match kind {
4053            MediaKind::Image => self.media_sources(wrapper),
4054            MediaKind::Video | MediaKind::Audio => self.media_sources(img),
4055        };
4056        let alt = self.image_alt(img);
4057        let sigil = kind.sigil();
4058        let label = if alt.is_empty() {
4059            // With no alt, name the file — but a `<video>` with neither `src` nor
4060            // alt has only its `<source>`s to be named by, so fall back to the
4061            // first candidate rather than labelling the row a bare sigil.
4062            let named = if destination.is_empty() {
4063                sources
4064                    .first()
4065                    .map(|s| s.srcset.as_str())
4066                    .unwrap_or_default()
4067            } else {
4068                &destination
4069            };
4070            format!("{sigil} {}", media_label(named))
4071        } else {
4072            format!("{sigil} {alt}")
4073        };
4074        let style = Style::default().role(Role::Image);
4075        let mut glyphs = pf.to_vec();
4076        for ch in label.chars() {
4077            glyphs.push(Glyph {
4078                ch,
4079                style,
4080                src: start,
4081                stop: true,
4082            });
4083        }
4084        // How many rows the frontend wants for this picture: the label row plus
4085        // the blank fillers below it. Absent (a GUI that lays images out in
4086        // pixels, an image that didn't resolve, or a plain surface) means the
4087        // bare one-row placeholder.
4088        let rows = self
4089            .surface
4090            .media_rows
4091            .get(&destination)
4092            .copied()
4093            .unwrap_or(1)
4094            .max(1);
4095        // End past the image so the caret has a stop after it: the last glyph's
4096        // offset is the image *start*, not its extent, so `push_row`'s
4097        // last-glyph rule would strand the end stop inside the markup.
4098        self.push_row_at(glyphs, end);
4099        if let Some(row) = self.rows.last_mut() {
4100            row.media = Some(MediaMark {
4101                kind,
4102                destination,
4103                sources,
4104                alt,
4105                poster,
4106                rows,
4107            });
4108        }
4109        // Reserve the picture's remaining height as blank `decoration` rows: drawn
4110        // (so the frontend has the vertical room to paint the raster over them),
4111        // but holding no caret and contributing no stops — vertical motion steps
4112        // over them and the caret's only homes stay the stop in front of the image
4113        // and the one just past it, both on the label row above. They anchor at the
4114        // image's end offset so a click on the picture's lower half lands after it,
4115        // the nearest caret home. Mirrors how a table's box-rule rows reserve space
4116        // without ever holding the caret.
4117        for _ in 1..rows {
4118            self.rows.push(VRow {
4119                glyphs: Vec::new(),
4120                end_src: end,
4121                decoration: true,
4122                code: false,
4123                code_lang: None,
4124                directive: false,
4125                directive_label: None,
4126                media: None,
4127                task: None,
4128                leaf_directive: None,
4129                heading: None,
4130                align: None,
4131                line_height: None,
4132                boundary: None,
4133                mark_ends: Vec::new(),
4134                math: Vec::new(),
4135            });
4136        }
4137        self.last_off = end;
4138    }
4139
4140    /// The `<picture>` alternatives inside block-image `wrapper`, in document
4141    /// order — every `<source>` element in its subtree. Empty when there's no
4142    /// `<picture>`. Each is a `<source>`'s `media` + `srcset`; core keeps them
4143    /// verbatim and picks none (see [`MediaSource`]). A `<source>` with no
4144    /// `srcset` is dropped (nothing to load); its `media` may be empty (an
4145    /// unconditional override), which a frontend treats as always-matching.
4146    ///
4147    /// It scans the wrapper's whole subtree (via the forward `first_child` /
4148    /// `next_sibling` links, the reliable ones) rather than the `<img>`'s parent,
4149    /// for two reasons. A `<picture>` reaches core in two shapes: twig promotes a
4150    /// block `<picture>` to an `element(picture)` wrapping `[source, img]`, but
4151    /// leaves an inline one's tags as raw siblings — `[raw "<picture>", source,
4152    /// img, raw "</picture>"]` — so the `<source>`s sit at different depths in
4153    /// the two. And the editor's flat arena leaves a promoted inline node's
4154    /// `parent` back-pointer dangling on a phantom root, so only the wrapper
4155    /// (known at the call site) is a trustworthy anchor. A block image is the
4156    /// sole visible content of its wrapper, so every `<source>` under it is its
4157    /// picture's.
4158    fn media_sources(&self, wrapper: usize) -> Vec<MediaSource> {
4159        let mut out = Vec::new();
4160        self.collect_sources(wrapper, &mut out);
4161        out
4162    }
4163
4164    fn collect_sources(&self, id: usize, out: &mut Vec<MediaSource>) {
4165        for c in self.children(id) {
4166            let node = &self.nodes[c];
4167            if node.name.as_deref() == Some("source") {
4168                // `<picture>` spells its candidate `srcset`, `<video>`/`<audio>`
4169                // spell it `src`. Both mean "the URL to load", so they normalise
4170                // onto one field; `srcset` wins where (illegally) both appear.
4171                let url = attr_of(node, "srcset").or_else(|| attr_of(node, "src"));
4172                if let Some(srcset) = url {
4173                    out.push(MediaSource {
4174                        media: attr_of(node, "media").unwrap_or_default(),
4175                        srcset,
4176                        mime: attr_of(node, "type").unwrap_or_default(),
4177                    });
4178                }
4179            }
4180            self.collect_sources(c, out);
4181        }
4182    }
4183
4184    /// The single block-level media `id`'s subtree resolves to, or `None`.
4185    ///
4186    /// A wrapper is a block picture when the only *visible* thing under it is one
4187    /// image: whitespace-only text and structure-only elements (a `<picture>`'s
4188    /// `<source>`, which declares an alternate but paints nothing) don't count,
4189    /// and the search descends through wrapping elements (`<picture>`, a linking
4190    /// `<a>`). This is what makes `<p><img></p>`, a bare `<img>`, and
4191    /// `<h1><picture>…<img></picture></h1>` all render as one framed picture.
4192    /// Any real text, or a second image, means it isn't image-only — it falls
4193    /// back to inline rendering, where the image still shows as its alt text.
4194    ///
4195    /// [`FlatNode`]'s snapshot doesn't carry an element's tag name, so a
4196    /// `<source>` can't be skipped by name — but it needs no special case:
4197    /// contributing no image and no text, it's simply invisible to the scan.
4198    fn media_only(&self, id: usize) -> Option<(usize, MediaKind)> {
4199        let mut found = None;
4200        let mut count = 0usize;
4201        let mut has_text = false;
4202        self.scan_visual(id, &mut found, &mut count, &mut has_text);
4203        (count == 1 && !has_text).then(|| found.unwrap())
4204    }
4205
4206    /// Walk `id`'s subtree tallying visible leaves for [`media_only`]: each
4207    /// image, `<video>`, or `<audio>` (remembering the last, counting the total)
4208    /// and whether any non-whitespace text appears. Media isn't descended into —
4209    /// an image's inline children are alt text, and a `<video>`'s are its
4210    /// no-support fallback and its `<source>` declarations, none of which is
4211    /// document content.
4212    ///
4213    /// [`media_only`]: Self::media_only
4214    fn scan_visual(
4215        &self,
4216        id: usize,
4217        found: &mut Option<(usize, MediaKind)>,
4218        count: &mut usize,
4219        has_text: &mut bool,
4220    ) {
4221        for c in self.children(id) {
4222            let node = &self.nodes[c];
4223            match node.kind.as_str() {
4224                "image" => {
4225                    *found = Some((c, MediaKind::Image));
4226                    *count += 1;
4227                }
4228                // A `<video>`/`<audio>` reaches core as a generic `container`
4229                // (twig gives neither a semantic node, so `html_elements`
4230                // promotion leaves the tag name on `name`). Counted as media and
4231                // *not* descended into, so its `<source>` children and its
4232                // "your browser does not support…" fallback text neither add a
4233                // second count nor make the block look like text.
4234                "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
4235                    let kind = match element_tag(node) {
4236                        Some("audio") => MediaKind::Audio,
4237                        _ => MediaKind::Video,
4238                    };
4239                    *found = Some((c, kind));
4240                    *count += 1;
4241                }
4242                // Text leaves: only non-whitespace counts as visible content.
4243                // (Twig keeps the whitespace `str`s between HTML tags — the
4244                // newlines and indentation inside a `<picture>` — as real nodes.)
4245                "str" | "smart_punctuation" | "verbatim" | "inline_math" | "display_math" => {
4246                    if node.text.as_deref().is_some_and(|t| !t.trim().is_empty()) {
4247                        *has_text = true;
4248                    }
4249                }
4250                // Structural breaks carry no visible glyph of their own.
4251                "soft_break" | "hard_break" | "non_breaking_space" => {}
4252                // Any other wrapper (emphasis, a link, a `<picture>`) is
4253                // transparent to the scan — descend into it.
4254                _ => self.scan_visual(c, found, count, has_text),
4255            }
4256        }
4257    }
4258
4259    /// The single `display_math` that is all of `id`'s visible content, or
4260    /// `None` — [`media_only`](Self::media_only) for a formula. Whitespace-only
4261    /// text around it does not count (twig keeps the newlines either side of a
4262    /// `$$` on its own lines as `str`s); any other text, or a second formula,
4263    /// means the paragraph is prose with math in it, and falls through to the
4264    /// inline path.
4265    fn math_only(&self, id: usize) -> Option<usize> {
4266        let mut found = None;
4267        let mut count = 0usize;
4268        for c in self.children(id) {
4269            let node = &self.nodes[c];
4270            match node.kind.as_str() {
4271                "display_math" => {
4272                    found = Some(c);
4273                    count += 1;
4274                }
4275                "str" | "smart_punctuation" => {
4276                    if node.text.as_deref().is_some_and(|t| !t.trim().is_empty()) {
4277                        return None;
4278                    }
4279                }
4280                "soft_break" | "hard_break" | "non_breaking_space" => {}
4281                _ => return None,
4282            }
4283        }
4284        (count == 1).then(|| found.unwrap())
4285    }
4286
4287    /// A display formula on lines of its own, drawn on
4288    /// [`block_media`](Self::block_media)'s recipe: one placeholder row —
4289    /// `∑` and the TeX on one line, every glyph [`Role::Math`] at the
4290    /// formula's start and a caret stop there, the row ending past the
4291    /// formula so the caret can rest after it too — carrying a [`MathMark`]
4292    /// for [`math_spans`] to publish, and under it as many blank decoration
4293    /// rows as the frontend said the picture is tall
4294    /// ([`Surface::math_rows`]).
4295    ///
4296    /// On the caret's line the block is its source instead: the `$$`
4297    /// delimiters in [`Role::Delimiter`] and the TeX between them in
4298    /// [`Role::Code`], line for line, the way a fence draws — so a formula is
4299    /// edited where it stands and folds back to its picture when the caret
4300    /// leaves. That is the same rule an inline formula follows, and it is
4301    /// what makes a block-level formula need no equivalent of
4302    /// [`VisualMap::block_media_stop`]: both of the placeholder's caret homes
4303    /// are on the formula's own lines, and standing on either reveals it.
4304    fn block_math(&mut self, math: usize, pf: &[Glyph], pc: &[Glyph]) {
4305        self.saw_math.set(true);
4306        let node = &self.nodes[math];
4307        let (start, end) = (node.span.start, node.span.end);
4308        let tex = node.text.clone().unwrap_or_default();
4309        if self.math_revealed(&node.span) {
4310            let mut glyphs = Vec::new();
4311            self.inline_verbatim(math, Style::default(), &mut glyphs, true);
4312            self.emit_wrapped(glyphs, start, pf, pc);
4313            self.last_off = end;
4314            return;
4315        }
4316        let style = Style::default().role(Role::Math);
4317        let mut glyphs = pf.to_vec();
4318        // One line of label: the TeX with its newlines folded, so the row
4319        // reads as one thing however the source laid it out.
4320        let label: String = tex.split_whitespace().collect::<Vec<_>>().join(" ");
4321        for ch in format!("{MATH_ATOM} {label}").chars() {
4322            glyphs.push(Glyph {
4323                ch,
4324                style,
4325                src: start,
4326                stop: true,
4327            });
4328        }
4329        let rows = self
4330            .surface
4331            .math_rows
4332            .get(&tex)
4333            .copied()
4334            .unwrap_or(1)
4335            .max(1);
4336        self.push_row_at(glyphs, end);
4337        if let Some(row) = self.rows.last_mut() {
4338            row.math = vec![MathMark {
4339                tex,
4340                display: true,
4341                glyph: None,
4342                rows,
4343            }];
4344        }
4345        for _ in 1..rows {
4346            self.rows.push(VRow {
4347                glyphs: Vec::new(),
4348                end_src: end,
4349                decoration: true,
4350                code: false,
4351                code_lang: None,
4352                directive: false,
4353                directive_label: None,
4354                media: None,
4355                task: None,
4356                leaf_directive: None,
4357                heading: None,
4358                align: None,
4359                line_height: None,
4360                boundary: None,
4361                mark_ends: Vec::new(),
4362                math: Vec::new(),
4363            });
4364        }
4365        self.last_off = end;
4366    }
4367
4368    /// A leaf directive (`::name{…}`) as one placeholder row — the
4369    /// [`block_media`](Self::block_media) recipe, for the same reason: it is a
4370    /// block that renders as *a thing*, not as text, and the frontend paints
4371    /// whatever the host app's vocabulary makes of it.
4372    ///
4373    /// The row's glyphs are a `⧉ label` (or `⧉ name`) stand-in a plain surface
4374    /// paints as-is, every glyph anchored at the directive's start with a caret
4375    /// stop there, and the row ending past it so the caret can also rest after
4376    /// it. It carries a [`DirectiveMark`] for [`directive_spans`], and is marked
4377    /// [`directive`](VRow::directive) so a frontend already drawing the
4378    /// container form's panel frames this one identically for free.
4379    ///
4380    /// Before this, a leaf directive emitted no rows at all: it was invisible,
4381    /// held no caret, and vertical motion crossed a void where it stood.
4382    fn block_directive(&mut self, id: usize, pf: &[Glyph]) {
4383        let node = &self.nodes[id];
4384        let (start, end) = (node.span.start, node.span.end);
4385        let (name, attrs) = leaf_directive_identity(node);
4386        let label = self.image_alt(id); // its `[label]` children, flattened
4387        let shown = if label.is_empty() { &name } else { &label };
4388        let style = Style::default().role(Role::Image);
4389        let mut glyphs = pf.to_vec();
4390        for ch in format!("⧉ {shown}").chars() {
4391            glyphs.push(Glyph {
4392                ch,
4393                style,
4394                src: start,
4395                stop: true,
4396            });
4397        }
4398        // End past the directive so the caret has a stop after it — the same
4399        // reason `block_media` anchors its row at the image's end.
4400        self.push_row_at(glyphs, end);
4401        if let Some(row) = self.rows.last_mut() {
4402            row.directive = true;
4403            row.leaf_directive = Some(DirectiveMark {
4404                name,
4405                attrs,
4406                label,
4407                rows: 1,
4408            });
4409        }
4410        self.last_off = end;
4411    }
4412
4413    /// An image's alt text: the flattened text of its inline descendants (an
4414    /// image's children *are* its alt content), empty when it has none. Also a
4415    /// leaf directive's `[label]`, which is the same shape — inline children
4416    /// standing for the block.
4417    fn image_alt(&self, id: usize) -> String {
4418        let mut out = String::new();
4419        self.collect_text(id, &mut out);
4420        out
4421    }
4422
4423    /// Append every descendant's `text` to `out`, in document order. Inline text
4424    /// (`str`) nodes are leaves, so a node never contributes both its own text and
4425    /// a child's — no double counting.
4426    fn collect_text(&self, id: usize, out: &mut String) {
4427        for c in self.children(id) {
4428            if let Some(t) = &self.nodes[c].text {
4429                out.push_str(t);
4430            }
4431            self.collect_text(c, out);
4432        }
4433    }
4434
4435    fn inline_children(&self, id: usize, base: Style) -> Vec<Glyph> {
4436        let mut out = Vec::new();
4437        for c in self.children(id) {
4438            self.inline(c, base, &mut out);
4439        }
4440        out
4441    }
4442
4443    /// [`inline_children`](Self::inline_children) plus any trailing whitespace the
4444    /// block carries past its inline content (see [`trailing_ws_glyphs`]). Used
4445    /// for the leaf inline blocks — paragraphs and headings — whose own `span`
4446    /// bounds exactly one line of text, so the trailing gap is theirs. *Not* for
4447    /// a table cell, whose `span` is the whole row and would swallow the
4448    /// delimiters and neighbours between it and the row's end.
4449    ///
4450    /// [`trailing_ws_glyphs`]: Self::trailing_ws_glyphs
4451    fn inline_children_with_trailing(&self, id: usize, base: Style) -> Vec<Glyph> {
4452        let mut out = self.inline_children(id, base);
4453        out.extend(self.trailing_ws_glyphs(id, base));
4454        out
4455    }
4456
4457    /// Glyphs for whatever trailing whitespace a block's source carries past its
4458    /// last inline node — the space(s) at the end of `hello ` that Markdown and
4459    /// Djot drop from the `str` node as insignificant. twig still records them:
4460    /// a block's `content_span` ends at its last meaningful character while its
4461    /// `span` runs to the end of the line's text (before the terminating
4462    /// newline), so the gap between the two *is* that trailing whitespace.
4463    ///
4464    /// Emitting it as real caret-stop glyphs is what lets the caret be drawn
4465    /// past the last visible character. Without it, typing a space at the end of
4466    /// a paragraph moved the caret in the source but not on screen — the caret
4467    /// stuck on the last glyph until the next visible character reparsed the
4468    /// space into an interior `str` node that finally carried it.
4469    ///
4470    /// Restricted to spaces: only they are safe to synthesize one-cell-per-byte,
4471    /// and only they are what the parser silently strips. Anything else in the
4472    /// gap means the span accounting isn't what this assumes, so it's left alone.
4473    fn trailing_ws_glyphs(&self, id: usize, style: Style) -> Vec<Glyph> {
4474        let node = &self.nodes[id];
4475        let Some(content) = &node.content_span else {
4476            return Vec::new();
4477        };
4478        let (from, to) = (content.end, node.span.end);
4479        let Some(slice) = (from < to).then(|| self.source.get(from..to)).flatten() else {
4480            return Vec::new();
4481        };
4482        if slice.is_empty() || slice.bytes().any(|b| b != b' ') {
4483            return Vec::new();
4484        }
4485        slice
4486            .bytes()
4487            .enumerate()
4488            .map(|(i, _)| Glyph {
4489                ch: ' ',
4490                style,
4491                src: from + i,
4492                stop: true,
4493            })
4494            .collect()
4495    }
4496
4497    fn inline(&self, id: usize, base: Style, out: &mut Vec<Glyph>) {
4498        let node = &self.nodes[id];
4499        match node.kind.as_str() {
4500            "str" | "smart_punctuation" => push_escaped_text(
4501                out,
4502                node.text.as_deref().unwrap_or(""),
4503                node.span.clone(),
4504                self.source,
4505                base,
4506            ),
4507            "soft_break" | "hard_break" | "non_breaking_space" => {
4508                // A break renders as a real, caret-navigable glyph — but twig
4509                // gives it no span of its own (`0..0`), so the offset comes from
4510                // the text in front of it: one *past* the last glyph, which is
4511                // the newline the break stands for. Past, not on: sharing the
4512                // previous glyph's offset would put two stops on one byte, and a
4513                // caret that can't change offset can't move.
4514                let src = if node.span.start != 0 {
4515                    node.span.start
4516                } else {
4517                    out.last().map(|g| g.src + g.ch.len_utf8()).unwrap_or(0)
4518                };
4519                // A *hard* break renders as this run's break glyph — a newline
4520                // inside a table cell (its own line), the same space in prose the
4521                // frontend re-wraps. A soft break normally folds into a space;
4522                // under `LineFlow::Preserve` it renders as a `'\n'` too, so the
4523                // author's line break shows where it was written. Never inside a
4524                // cell (`break_glyph` is `'\n'` there): a cell is one line and
4525                // folds its own soft breaks regardless.
4526                let ch = if node.kind == Kind::HardBreak {
4527                    self.break_glyph.get()
4528                } else if node.kind == Kind::SoftBreak
4529                    && self.preserve_soft
4530                    && self.break_glyph.get() == ' '
4531                {
4532                    '\n'
4533                } else {
4534                    ' '
4535                };
4536                out.push(Glyph {
4537                    ch,
4538                    style: base,
4539                    src,
4540                    stop: true,
4541                });
4542            }
4543            // A cell's only spelling for an in-line break is a raw `<br>`; read it
4544            // back as one (outside a cell it stays the literal text it falls to
4545            // below). The tag's bytes carry no stop of their own — the line it
4546            // ends stops just before it, the next just after.
4547            "raw_inline" if self.break_glyph.get() == '\n' && is_br(node.text.as_deref()) => {
4548                out.push(Glyph {
4549                    ch: '\n',
4550                    style: base,
4551                    src: node.span.start,
4552                    stop: true,
4553                });
4554            }
4555            "emph" => self.inline_delimited(id, base.italic(), out),
4556            "strong" => self.inline_delimited(id, base.bold(), out),
4557            // A coloured highlight's emoji is spelling, not content: twig strips
4558            // it and records the colour on the node, so the glyphs are the
4559            // author's words and the colour rides the role. Revealed markup
4560            // still shows the emoji, because `delims` reads the source bytes
4561            // between the span and the content span — which is exactly the
4562            // `==🔴 ` the author typed.
4563            "mark" => {
4564                let color = MarkColor::from_attrs(&node.attrs);
4565                self.inline_delimited(id, base.role(Role::Mark(color)), out)
4566            }
4567            "insert" => self.inline_delimited(id, base.underline(), out),
4568            "delete" => self.inline_delimited(id, base.strikethrough(), out),
4569            // The one pair whose whole meaning is *where the glyphs sit*. Drawn
4570            // in the surrounding style otherwise, so `^**2**^` stays bold and a
4571            // superscript inside a heading keeps the heading's role — which is
4572            // exactly why this is a `Baseline` and not a `Role`.
4573            "superscript" => self.inline_delimited(id, base.baseline(Baseline::Super), out),
4574            "subscript" => self.inline_delimited(id, base.baseline(Baseline::Sub), out),
4575            "verbatim" => self.inline_verbatim(id, base, out, self.revealed(&node.span)),
4576            // A formula in a line. Three renderings, in order of preference:
4577            //
4578            // - On the caret's line it is its TeX in the code style with its
4579            //   delimiters shown — in *every* markup mode, because the
4580            //   content is not the picture and hiding the `$` alone would
4581            //   leave nothing to edit. `math_revealed` is `revealed` without
4582            //   the mode gate.
4583            // - On a surface that paints pictures in a line it is one atom
4584            //   glyph, `stop: true` at the formula's start, standing for the
4585            //   whole thing; the [`MathMark`] drained onto the row by
4586            //   [`take_math`](Self::take_math) says what the frontend draws
4587            //   there. The caret has the stop on the atom and the next glyph's
4588            //   past it, and nothing inside the markup.
4589            // - Elsewhere — a terminal — it is the code-styled TeX with the
4590            //   delimiters hidden, exactly the verbatim treatment, and what
4591            //   `inline_math` rendered as before there was anything else.
4592            //   `display_math` had no arm at all and fell to the default one,
4593            //   which pushed its text at the *node's* start, three bytes short
4594            //   of where the text sits.
4595            "inline_math" | "display_math" => {
4596                self.saw_math.set(true);
4597                if self.math_revealed(&node.span) {
4598                    self.inline_verbatim(id, base, out, true);
4599                } else if self.surface.inline_pictures {
4600                    let tex = node.text.clone().unwrap_or_default();
4601                    self.pending_math.borrow_mut().push((
4602                        node.span.start,
4603                        MathMark {
4604                            tex,
4605                            display: node.kind == Kind::DisplayMath,
4606                            glyph: None,
4607                            rows: 1,
4608                        },
4609                    ));
4610                    out.push(Glyph {
4611                        ch: MATH_ATOM,
4612                        style: base.role(Role::Math),
4613                        src: node.span.start,
4614                        stop: true,
4615                    });
4616                } else {
4617                    self.inline_verbatim(id, base, out, false);
4618                }
4619            }
4620            // An attributed span — the run-level half of the presentation
4621            // vocabulary. djot's `[text]{…}`, AsciiDoc's `[.a]#text#`, HTML's
4622            // and Markdown's `<span …>`: one node with a name twig hands back
4623            // for two of the four (see [`is_run_span`]), all four carrying the
4624            // author's `data-size`, `data-font` and `data-color` on the run
4625            // they cover.
4626            //
4627            // The keys are written over the surrounding style rather than
4628            // replacing it, so a span inside a block that names its own size
4629            // wins on size and keeps the block's face — the nearest-wins rule
4630            // the block walker applies through a `div`. A key the span does not
4631            // name is one the block still says.
4632            //
4633            // A `data-color` here is the text's *foreground*, where the same key
4634            // on a `mark` is a highlight's background: same vocabulary, same
4635            // enum, and no collision, because a `mark` is a `mark` and a span is
4636            // a span.
4637            //
4638            // Otherwise this is the plain `recurse` an anonymous container has
4639            // always had — no delimiters, because the `{…}` is markup and the
4640            // span's text is the author's words.
4641            "container" if is_run_span(node) && !self.children(id).is_empty() => {
4642                self.recurse(id, run_style(node, base, &self.faces), out)
4643            }
4644            // A text directive (`:name[label]{…}`) — the inline form of a generic
4645            // directive. Its `[label]` children are the visible text; the name and
4646            // the `{…}` attributes are the host app's vocabulary (diaryx's
4647            // `:vis[…]`) and stay hidden markup, exactly as a link's `](dest)` is.
4648            // Drawn in the surrounding style: a role of its own would need one
4649            // every frontend maps, and the bug this fixes is that the text was
4650            // invisible, not that it was unstyled.
4651            "container" if container_is_directive(node) && !self.children(id).is_empty() => {
4652                self.recurse(id, base, out)
4653            }
4654            // No `[label]`, so there are no children to render and recursing
4655            // emitted *nothing*: the directive's bytes vanished from the document
4656            // and left no caret stop behind. What to draw instead turns on
4657            // whether the syntax looks deliberate.
4658            //
4659            // Bare `:word` almost never is. twig matches a colon followed by any
4660            // letter-led word (`scanTextDirective`, deliberately matching remark),
4661            // so ordinary prose is full of them — `:see below`, a `:smile:`
4662            // shortcode, a stray colon before a word. Those are prose, and prose
4663            // renders as itself: every byte visible, every byte a caret stop, so a
4664            // colon typed by accident can be seen and deleted. Hiding them behind
4665            // a placeholder would be the invisible-and-unreachable failure this
4666            // arm exists to fix, just wearing a nicer glyph.
4667            "container" if container_is_directive(node) && node.attrs.is_empty() => {
4668                let span = node.span.clone();
4669                push_text(
4670                    out,
4671                    self.source.get(span.clone()).unwrap_or(""),
4672                    span.start,
4673                    base,
4674                );
4675            }
4676            // `{…}` attributes, though, are unmistakably deliberate — nobody
4677            // types `:vis{.family}` by accident, and diaryx writes exactly that
4678            // inline. So an attribute-bearing directive with no label draws as a
4679            // chip on `block_directive`'s recipe (`⧉ name attrs`, `Role::Image`),
4680            // the inline peer of the leaf form's placeholder row.
4681            //
4682            // Only the first glyph is a caret stop, and the whole chip shares the
4683            // directive's start offset: the caret treats it as one atomic thing
4684            // rather than walking hidden markup a byte at a time, and a paragraph
4685            // holding nothing but a chip still has a stop to be navigated to.
4686            "container" if container_is_directive(node) => {
4687                let start = node.span.start;
4688                let name = node.name.clone().unwrap_or_default();
4689                let shown = match directive_attr_label(&node.attrs) {
4690                    Some(attrs) if !name.is_empty() => format!("⧉ {name} {attrs}"),
4691                    Some(attrs) => format!("⧉ {attrs}"),
4692                    None => format!("⧉ {name}"),
4693                };
4694                let style = base.role(Role::Image);
4695                for (i, ch) in shown.chars().enumerate() {
4696                    out.push(Glyph {
4697                        ch,
4698                        style,
4699                        src: start,
4700                        stop: i == 0,
4701                    });
4702                }
4703            }
4704            // A footnote reference (`[^1]`). The label bracketed is what a reader
4705            // needs — bare, `note1` reads as a typo rather than a reference — so
4706            // the `^` is hidden as the spelling artefact it is (a link's
4707            // `](dest)` goes the same way) and the brackets are kept as
4708            // decoration: one shared offset, never a caret stop, like a table's
4709            // borders, so the caret walks the label alone.
4710            //
4711            // Styled `Role::Link`: a reference *is* a link to its definition, and
4712            // every frontend already paints that role. A role of its own would
4713            // need one in each of them, and what a frontend needs to tell the two
4714            // apart is not a paint colour but an answer to "what does clicking
4715            // here do" — which is [`Doc::footnote_at_caret`]'s job, not a glyph's.
4716            //
4717            // Raised, though, because that a reference is *set* differently from
4718            // the prose it interrupts is exactly what makes it read as a
4719            // reference. `[1]` at body size reads as bracketed text.
4720            "footnote_reference" => {
4721                let style = base.role(Role::Link);
4722                // Revealed, the reference is just its source bytes: the `^` that
4723                // is normally elided comes back and every byte becomes a real
4724                // stop, so the brackets stop being decoration and start being
4725                // text. That's the whole point of the mode, and it replaces the
4726                // hand-built chip below rather than decorating it — including the
4727                // raised baseline, since what's on screen there is source, and
4728                // source is set as prose.
4729                if self.revealed(&node.span) {
4730                    self.push_delim(out, &node.span, style);
4731                    return;
4732                }
4733                let style = style.baseline(Baseline::Super);
4734                // The label's own span, so its glyphs map to their true bytes.
4735                // Absent one, it starts past the `[^` that opens the reference.
4736                let (label, at) = match &node.content_span {
4737                    Some(c) => (self.source.get(c.clone()).unwrap_or(""), c.start),
4738                    None => (node.text.as_deref().unwrap_or(""), node.span.start + 2),
4739                };
4740                out.push(Glyph {
4741                    ch: '[',
4742                    style,
4743                    src: node.span.start,
4744                    stop: false,
4745                });
4746                push_text(out, label, at, style);
4747                out.push(Glyph {
4748                    ch: ']',
4749                    style,
4750                    src: node.span.end.saturating_sub(1),
4751                    stop: false,
4752                });
4753            }
4754            "link" | "url" | "email" => {
4755                let style = base.role(Role::Link);
4756                if self.children(id).is_empty() {
4757                    // A bare autolink (`<a@b.c>`, a naked URL): the destination
4758                    // *is* the visible text, so there is nothing elided to
4759                    // reveal and both modes draw the same thing.
4760                    push_text(
4761                        out,
4762                        node.destination
4763                            .as_deref()
4764                            .or(node.text.as_deref())
4765                            .unwrap_or("link"),
4766                        node.span.start,
4767                        style,
4768                    );
4769                } else {
4770                    // An inline link reveals asymmetrically — `[` before the
4771                    // label, `](dest)` after it — which the generic
4772                    // span-minus-content derivation already produces.
4773                    self.inline_delimited(id, style, out);
4774                }
4775            }
4776            _ => {
4777                if self.children(id).is_empty() {
4778                    if let Some(t) = &node.text {
4779                        push_text(out, t, node.span.start, base);
4780                    }
4781                } else {
4782                    self.recurse(id, base, out);
4783                }
4784            }
4785        }
4786    }
4787
4788    fn recurse(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
4789        for c in self.children(id) {
4790            self.inline(c, style, out);
4791        }
4792    }
4793
4794    /// Lay a block's inline `glyphs` into visual rows, prefixing the first with
4795    /// `pf` and the rest with `pc`. A preserved soft break arrives as a `'\n'`
4796    /// glyph (see the `soft_break` arm): a hard row boundary that splits the
4797    /// glyphs so each run lays out on its own and the author's line structure
4798    /// shows on screen. The `'\n'` is dropped from the row it closes and its
4799    /// source offset becomes that row's end stop — exactly how a table cell's
4800    /// in-line `<br>` is handled — so the caret can rest at the line's end
4801    /// without a zero-width control char leaking into what the frontends render.
4802    /// With no `'\n'` present (the folding default, and every build that isn't
4803    /// `LineFlow::Preserve`) there is one run and this is byte-identical to
4804    /// laying the glyphs out directly.
4805    fn emit_wrapped(&mut self, glyphs: Vec<Glyph>, block_start: usize, pf: &[Glyph], pc: &[Glyph]) {
4806        if !glyphs.iter().any(|g| g.ch == '\n') {
4807            self.emit_line(glyphs, block_start, pf, pc, None);
4808            return;
4809        }
4810        // Each run up to a '\n' is a line of its own: the first wears the block's
4811        // opening prefix, every later one the continuation prefix, and the break's
4812        // own offset ends the run's last row. The break glyph is dropped. A
4813        // trailing '\n' flushes its run and leaves nothing behind, so no spurious
4814        // blank row follows it.
4815        let mut run: Vec<Glyph> = Vec::new();
4816        let mut first = true;
4817        for g in glyphs {
4818            if g.ch == '\n' {
4819                let lead = if first { pf } else { pc };
4820                self.emit_line(std::mem::take(&mut run), block_start, lead, pc, Some(g.src));
4821                first = false;
4822            } else {
4823                run.push(g);
4824            }
4825        }
4826        if !run.is_empty() {
4827            let lead = if first { pf } else { pc };
4828            self.emit_line(run, block_start, lead, pc, None);
4829        }
4830    }
4831
4832    /// Word-wrap a single line of `glyphs` (no interior line breaks) to the
4833    /// available width and push the visual rows, prefixing the first with `pf`
4834    /// and the rest with `pc`. `end`, when set, is the source offset that ends
4835    /// the line's final row — the offset of the break that terminated it, which
4836    /// the caller has already stripped from `glyphs`; when `None` the row ends
4837    /// just past its last glyph, as an unbroken block's does.
4838    fn emit_line(
4839        &mut self,
4840        glyphs: Vec<Glyph>,
4841        block_start: usize,
4842        pf: &[Glyph],
4843        pc: &[Glyph],
4844        end: Option<usize>,
4845    ) {
4846        // The line's final row ends at `end` when a break gave one, else just
4847        // past its last glyph (`push_row`'s default).
4848        let push_last = |b: &mut Self, row: Vec<Glyph>| match end {
4849            Some(e) => b.push_row_at(row, e),
4850            None => b.push_row(row, block_start),
4851        };
4852
4853        // No column budget: emit the whole line as one row and let the frontend
4854        // wrap it at its own (pixel) width.
4855        let Some(width) = self.wrap else {
4856            let row = if glyphs.is_empty() {
4857                pf.to_vec()
4858            } else {
4859                concat(pf, &glyphs)
4860            };
4861            push_last(self, row);
4862            return;
4863        };
4864
4865        // Split into words (maximal non-space runs), each carrying the space
4866        // glyph that followed it (so its source offset is preserved).
4867        let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
4868        let mut word: Vec<Glyph> = Vec::new();
4869        for g in glyphs {
4870            if g.ch == ' ' {
4871                words.push((std::mem::take(&mut word), Some(g)));
4872            } else {
4873                word.push(g);
4874            }
4875        }
4876        if !word.is_empty() {
4877            words.push((word, None));
4878        }
4879        if words.is_empty() {
4880            // An empty block (or an empty preserved line) still occupies one
4881            // (prefixed) row.
4882            push_last(self, pf.to_vec());
4883            return;
4884        }
4885
4886        let mut line: Vec<Glyph> = Vec::new();
4887        let mut used = 0usize;
4888        let mut first = true;
4889        for (w, space) in words {
4890            let avail = width
4891                .saturating_sub(prefix_width(if first { pf } else { pc }))
4892                .max(1);
4893            let cells = glyphs_width(&w);
4894            if used > 0 && used + cells > avail {
4895                let row = concat(if first { pf } else { pc }, &line);
4896                self.push_row(row, block_start);
4897                line = Vec::new();
4898                used = 0;
4899                first = false;
4900            }
4901            used += cells;
4902            line.extend(w);
4903            if let Some(sp) = space {
4904                used += 1;
4905                line.push(sp);
4906            }
4907        }
4908        let row = concat(if first { pf } else { pc }, &line);
4909        push_last(self, row);
4910    }
4911
4912    /// The source offset of each line of a code block's `text`.
4913    ///
4914    /// `content` is the block's `content_span` — where twig says the body lives
4915    /// in the source, fences already excluded. Its lines run 1:1 with the
4916    /// rendered `text` lines, so no search is needed; each is anchored at the
4917    /// *end* of its source line, which places it past whatever indent `text` had
4918    /// stripped (a fenced block's fences, an indented one's leading spaces)
4919    /// without having to know how much there was.
4920    ///
4921    /// `None` when the body and the rendered lines don't line up — a coarse
4922    /// fallback the caller turns into the block's start offset.
4923    fn code_line_offsets(&self, content: &Range<usize>, lines: &[&str]) -> Option<Vec<usize>> {
4924        let mut src_lines: Vec<(usize, &str)> = Vec::new();
4925        let mut at = content.start;
4926        for l in self.source.get(content.start..content.end)?.split('\n') {
4927            src_lines.push((at, l));
4928            at += l.len() + 1;
4929        }
4930        if src_lines.len() != lines.len() {
4931            return None;
4932        }
4933        Some(
4934            lines
4935                .iter()
4936                .zip(&src_lines)
4937                .map(|(l, (start, sl))| start + sl.len().saturating_sub(l.len()))
4938                .collect(),
4939        )
4940    }
4941
4942    fn push_row(&mut self, glyphs: Vec<Glyph>, fallback: usize) {
4943        // Step past the character the *source* holds at the last glyph's offset,
4944        // not past the glyph's own `ch`. The two agree for ordinary text, but a
4945        // glyph is not always the character it stands on: `synth` decoration and
4946        // a substituted run (an image's `⧉ label`) share one offset by design.
4947        // Trusting `ch` there yields an offset inside a multi-byte character,
4948        // which every later slice of `source` panics on.
4949        let end_src = glyphs
4950            .last()
4951            .map(|g| {
4952                let at = g.src.min(self.source.len());
4953                at + self.source[at..].chars().next().map_or(0, char::len_utf8)
4954            })
4955            .unwrap_or(fallback);
4956        self.push_row_at(glyphs, end_src);
4957    }
4958
4959    /// Push a row with an explicit end stop, for content that knows its own
4960    /// extent better than its last glyph does.
4961    fn push_row_at(&mut self, glyphs: Vec<Glyph>, end_src: usize) {
4962        self.last_off = end_src;
4963        let mark_ends = self.take_mark_ends(end_src);
4964        let math = self.take_math(&glyphs);
4965        self.rows.push(VRow {
4966            glyphs,
4967            end_src,
4968            decoration: false,
4969            code: false,
4970            code_lang: None,
4971            directive: false,
4972            directive_label: None,
4973            media: None,
4974            task: None,
4975            leaf_directive: None,
4976            heading: None,
4977            align: None,
4978            line_height: None,
4979            boundary: None,
4980            mark_ends,
4981            math,
4982        });
4983    }
4984
4985    /// The quote's own trailing marker lines: the `>` / `> ` lines that lie past
4986    /// its last child but inside its span, one gutter row each.
4987    ///
4988    /// Pressing Enter at the end of `> a` writes `> a\n>\n> \n` — twig's
4989    /// spelling, and the right one. Those last two lines hold no block (a
4990    /// `block_quote`'s `content_span` still stops at its last child) so the
4991    /// children walk never reaches them, and they used to fall all the way to
4992    /// the document-level [`Builder::emit_trailing_blank_lines`], which knows no
4993    /// prefix: the gutter simply stopped, and a writer adding a line to a quote
4994    /// watched it draw as plain prose.
4995    ///
4996    /// This is only answerable since twig 3.2.0, where a Markdown `block_quote`'s
4997    /// span covers its own trailing marker lines (it reported `0..3` for that
4998    /// source and now reports `0..8`). Before that the lines belonged to no node
4999    /// at any level, and the only way to draw them was to sniff `>` off the raw
5000    /// source and re-derive the nesting depth by counting markers — format
5001    /// inference this crate exists to keep out of the render path.
5002    ///
5003    /// Each row is a real caret home rather than a decoration gap: the writer
5004    /// spelled every one of these lines with a marker of its own, so each is a
5005    /// line of the quote to stand on, not the spacing between two blocks (which
5006    /// is [`Builder::emit_separators_before`]'s, and falls *between* children
5007    /// where this never looks).
5008    fn emit_quote_trailing_lines(&mut self, pc: &[Glyph], end: usize) {
5009        let end = end.min(self.source.len());
5010        let mut at = self.rows.last().map_or(0, |r| r.end_src);
5011        // Walk line by line from the last child's end to the quote's, taking each
5012        // line's *end* as the row's offset — the caret home at the end of a line
5013        // is where one on an empty quoted line belongs, and it keeps every row's
5014        // offset distinct from its neighbours'.
5015        while at < end {
5016            let Some(k) = self.source[at..end].find('\n') else {
5017                break;
5018            };
5019            let line_start = at + k + 1;
5020            let line_end = self.source[line_start..end]
5021                .find('\n')
5022                .map_or(end, |i| line_start + i);
5023            self.push_row_at(pc.to_vec(), line_end);
5024            at = line_end;
5025        }
5026    }
5027
5028    /// The source offset the caret rests at on the blank line separating a block
5029    /// that ends at `prev_end` from the next block starting at `next_start`:
5030    /// just past the newline that terminates the previous block, but kept
5031    /// strictly before the next block so the offset is unique to this row.
5032    fn blank_line_offset(&self, prev_end: usize, next_start: usize) -> usize {
5033        let after_nl = self.source[prev_end..]
5034            .find('\n')
5035            .map_or(prev_end, |p| prev_end + p + 1);
5036        after_nl.min(next_start.saturating_sub(1)).max(prev_end)
5037    }
5038
5039    /// The source offset of each blank row between a block ending at `prev_end`
5040    /// and content starting at `next_start` — one per blank source line. The
5041    /// first newline terminates the previous block's line; every line it opens up
5042    /// to (but not including) the line that holds `next_start` is a blank row the
5043    /// caret can occupy. Offsets are unique and ascending so `pos_of_offset`
5044    /// resolves each to its own row. Empty when the two blocks are tight (no
5045    /// blank line between them).
5046    fn blank_rows_between(&self, prev_end: usize, next_start: usize) -> Vec<usize> {
5047        // Spans aren't always in tidy source order (e.g. a block after
5048        // frontmatter can start *before* the previous block's rendered content
5049        // ends). There's no blank line to place then — fall back to the clamped
5050        // single separator (an empty return) rather than slicing an inverted
5051        // range.
5052        if next_start <= prev_end {
5053            return Vec::new();
5054        }
5055        let gap = &self.source[prev_end..next_start];
5056        let Some(nl) = gap.find('\n') else {
5057            return Vec::new();
5058        };
5059        // The line holding `next_start` belongs to the next block; blank rows
5060        // stop before it.
5061        let next_line_start = self.source[..next_start].rfind('\n').map_or(0, |p| p + 1);
5062        let mut offs = Vec::new();
5063        let mut start = prev_end + nl + 1;
5064        while start < next_line_start {
5065            offs.push(start);
5066            match self.source[start..next_start].find('\n') {
5067                Some(k) => start += k + 1,
5068                None => break,
5069            }
5070        }
5071        offs
5072    }
5073
5074    /// Blank lines the user typed past the end of the last block (e.g. two
5075    /// `Enter`s to open a fresh paragraph) leave no AST node, so nothing renders
5076    /// and the caret appears stuck on the old line. Reconstruct one empty row
5077    /// per extra trailing newline from the source, each at its own offset, so
5078    /// the caret rides down onto the new line the moment it's created.
5079    ///
5080    /// `above` is the class of the last block in the document — the one this gap
5081    /// closes. A document with no blocks at all has nothing above these rows, and
5082    /// [`BlockClass::Paragraph`] is the honest answer there too: what they are is
5083    /// empty paragraphs, on both sides of the gap.
5084    fn emit_trailing_blank_lines(&mut self, above: BlockClass, hidden_end: usize) {
5085        // With no rows at all the count starts past any hidden frontmatter, not
5086        // at 0: its newlines are not trailing blank lines, and counting them
5087        // opened phantom rows *inside* the metadata for a frontmatter-only file.
5088        //
5089        // Or past the last hidden block, if that is later: a closing comment
5090        // draws no row, and its lines are not blank lines the author opened.
5091        let last_end = self
5092            .rows
5093            .last()
5094            .map_or(hidden_end, |r| r.end_src)
5095            .max(self.stepped_over);
5096        if last_end >= self.source.len() {
5097            return;
5098        }
5099        // The first newline after the last content just terminates that line, so
5100        // a lone trailing `\n` (an ordinary file ending) opens no blank row. A
5101        // *second* newline opens an empty paragraph: render it the way a block
5102        // boundary is rendered — a blank spacer row, then the empty paragraph row
5103        // the caret rests on — so the just-pressed-Enter view already shows the
5104        // gap it will keep once text is typed, and typing doesn't shift the line
5105        // down. One row per trailing newline (each its own caret offset), the
5106        // last landing at the document end where the caret sits.
5107        let extra = self.source[last_end..].matches('\n').count();
5108        if extra < 2 {
5109            return;
5110        }
5111        for k in 1..=extra {
5112            self.rows.push(VRow {
5113                glyphs: Vec::new(),
5114                end_src: last_end + k,
5115                // As between two blocks: the first blank row is the gap that
5116                // closes the block above, not somewhere to type. Nothing follows
5117                // to need a gap of its own, though, so every row after it is a
5118                // real empty paragraph — the end of the document bounds the last
5119                // one the way a following block would. Preserve flow makes even
5120                // that first row navigable, as it does every blank line.
5121                decoration: !self.preserve_soft && k == 1,
5122                code: false,
5123                code_lang: None,
5124                directive: false,
5125                directive_label: None,
5126                media: None,
5127                task: None,
5128                leaf_directive: None,
5129                heading: None,
5130                align: None,
5131                line_height: None,
5132                // The one drawn row here is a block boundary like any other —
5133                // "rendered the way a block boundary is rendered" is the whole
5134                // point of it — so it says so, and a frontend spacing boundaries
5135                // spaces this one the same. The rows below it are navigable empty
5136                // paragraphs, not gaps.
5137                boundary: (!self.preserve_soft && k == 1).then_some(Boundary {
5138                    above,
5139                    below: BlockClass::Paragraph,
5140                }),
5141                mark_ends: Vec::new(),
5142                math: Vec::new(),
5143            });
5144        }
5145    }
5146}
5147
5148// ── display width ────────────────────────────────────────────────────────────
5149//
5150// Two things a row can be counted in, and they are not the same number:
5151//
5152//   *glyphs*, one per codepoint — how the text is stored here, and what an
5153//   index into `VRow::glyphs` means; and
5154//   *columns*, one per terminal cell — where the text is drawn, and what every
5155//   `col` in this crate means.
5156//
5157// `你` is one glyph in two columns. Counting columns with `glyphs.len()` (or,
5158// in the source view, `chars().count()`) is the same number only for the ASCII
5159// that most fixtures are written in, and drifts one cell per wide character
5160// everywhere else — the caret drawn a column short of the text it types into.
5161// Everything below converts between the two; nothing else should have to.
5162
5163/// The display width of `s` in terminal cells.
5164///
5165/// Measured per grapheme cluster, because that is the unit a surface advances
5166/// by: `👨‍👩‍👧` is five codepoints measuring 2 + 0 + 2 + 0 + 2 cells one at a
5167/// time, but the character they spell is drawn in 2. Both frontends already
5168/// measure it that way — ratatui asks `unicode-width` per cluster, and the GUI
5169/// asks its own text system — so the caret only lands where the text is if this
5170/// agrees with them.
5171pub fn text_width(s: &str) -> usize {
5172    UnicodeWidthStr::width(s)
5173}
5174
5175/// One grapheme cluster of a laid-out row: the glyphs that spell it, and the
5176/// cells it is drawn in.
5177///
5178/// The cluster, not the glyph, is what has a width. A row's glyphs are one per
5179/// codepoint, so an accented letter or an emoji is several of them drawn in one
5180/// character's worth of cells — the glyph that opens the cluster claims those
5181/// cells, and the ones continuing it are drawn *inside* them rather than beside
5182/// them. It's the same cluster the stop table is built on: the opening glyph is
5183/// the one a caret can rest on, and so the only one whose column it can be
5184/// drawn at.
5185struct Cluster {
5186    /// Index of the glyph that opens it.
5187    glyph: usize,
5188    /// The display column it starts at.
5189    col: usize,
5190    /// How many cells it is drawn in. Zero for a cluster with no width of its
5191    /// own (a lone joiner), which therefore sits at no column at all.
5192    cells: usize,
5193}
5194
5195/// Walk a row's glyphs as the clusters they spell, in column order.
5196fn clusters(glyphs: &[Glyph]) -> Vec<Cluster> {
5197    let text: String = glyphs.iter().map(|g| g.ch).collect();
5198    let mut out = Vec::new();
5199    let (mut glyph, mut col) = (0, 0);
5200    for cluster in text.graphemes(true) {
5201        let cells = text_width(cluster);
5202        out.push(Cluster { glyph, col, cells });
5203        // One glyph per codepoint, so a cluster spans exactly its own.
5204        glyph += cluster.chars().count();
5205        col += cells;
5206    }
5207    out
5208}
5209
5210/// The display width of a run of glyphs.
5211fn glyphs_width(glyphs: &[Glyph]) -> usize {
5212    clusters(glyphs).last().map_or(0, |c| c.col + c.cells)
5213}
5214
5215/// A cell's display width — the widest of its lines, since an in-cell `\n` break
5216/// splits it into several. Sizes the column that must hold every line.
5217fn cell_width(glyphs: &[Glyph]) -> usize {
5218    glyphs
5219        .split(|g| g.ch == '\n')
5220        .map(glyphs_width)
5221        .max()
5222        .unwrap_or(0)
5223}
5224
5225/// Whether a raw inline HTML tag is a line break (`<br>`, `<br/>`, `<br />`,
5226/// case-insensitively) — the one tag a table cell reads as an in-cell break.
5227fn is_br(text: Option<&str>) -> bool {
5228    let Some(t) = text else { return false };
5229    matches!(
5230        t.trim().to_ascii_lowercase().replace(' ', "").as_str(),
5231        "<br>" | "<br/>"
5232    )
5233}
5234
5235impl VRow {
5236    /// The row's width in display columns — and so the column of the caret
5237    /// placed past its last glyph, which is the rightmost column it can occupy.
5238    fn width(&self) -> usize {
5239        glyphs_width(&self.glyphs)
5240    }
5241
5242    /// The display column glyph `i` is drawn at. Glyphs continuing a cluster
5243    /// report the column of the glyph that opened it, since that is where they
5244    /// are drawn; none of them is ever a stop, so no caret is placed by it.
5245    fn col_of_glyph(&self, i: usize) -> usize {
5246        clusters(&self.glyphs)
5247            .iter()
5248            .rev()
5249            .find(|c| c.glyph <= i)
5250            .map_or(0, |c| c.col)
5251    }
5252
5253    /// The glyph drawn at display column `col`, or `None` past the row's last
5254    /// cell.
5255    ///
5256    /// A column landing on the *second* cell of a wide glyph resolves to that
5257    /// glyph: half a character is not a place to be, so clicking either cell of
5258    /// `你` means `你`, and the caret comes to rest at its start — the column it
5259    /// would be drawn at anyway. That rule is what makes the mapping invertible:
5260    /// every offset has one column, and every column has one offset.
5261    fn glyph_at_col(&self, col: usize) -> Option<usize> {
5262        clusters(&self.glyphs)
5263            .into_iter()
5264            .find(|c| col < c.col + c.cells)
5265            .map(|c| c.glyph)
5266    }
5267}
5268
5269// ── helpers ──────────────────────────────────────────────────────────────────
5270
5271/// The caret home inside an *empty* table cell (`col`, 0-based) whose node
5272/// `span` is `src` starting at byte `start`. twig gives an empty cell no
5273/// `content_span`, so its interior is read from the pipes: the home is one
5274/// space past the pipe that opens the cell — mimicking the `| ` padding a
5275/// filled cell has — and never at or past the pipe that closes it. So
5276/// `|  |  |` gives the two cells distinct, editable homes instead of both
5277/// collapsing onto the row's start.
5278///
5279/// Two shapes of span are read. A twig from 3.3.3 gave every cell of a row
5280/// the *row's* span, so the cell's own pipes are the `col`-th and
5281/// `col+1`-th unescaped `|` in it; a later twig spans a cell from the pipe
5282/// that opens it to the one that closes it, exclusive, so the span holds at
5283/// most that one pipe, at its start, and the closing one is the byte past
5284/// its end. The two are told apart by the pipes the span holds — a row's
5285/// span has several, or one that is not at its start.
5286fn empty_cell_offset(src: &str, start: usize, col: usize) -> usize {
5287    let bytes = src.as_bytes();
5288    let mut pipes = Vec::new();
5289    for (i, &b) in bytes.iter().enumerate() {
5290        if b == b'|' && (i == 0 || bytes[i - 1] != b'\\') {
5291            pipes.push(i);
5292        }
5293    }
5294    let whole_row = pipes.len() > 1 || pipes.first().is_some_and(|&i| i != 0);
5295    let (open, close) = if whole_row {
5296        (pipes.get(col).copied(), pipes.get(col + 1).copied())
5297    } else {
5298        (pipes.first().copied(), Some(src.len()))
5299    };
5300    match (open, close) {
5301        (Some(open), Some(close)) => {
5302            let lo = open + 1; // just inside the opening pipe
5303            let hi = close.saturating_sub(1); // just inside the closing pipe
5304            let inside = if hi < lo {
5305                lo
5306            } else {
5307                (open + 2).clamp(lo, hi)
5308            };
5309            start + inside
5310        }
5311        (Some(open), None) => start + open + 1,
5312        _ => start,
5313    }
5314}
5315
5316/// One laid-out table cell: its rendered text, the source range that text
5317/// occupies (`start`/`end` are the caret anchors decoration points at), and the
5318/// column alignment its padding honours.
5319///
5320/// `glyphs` is the cell's inline content *unwrapped* — the box-drawn rows wrap
5321/// it to a column width, but a frontend laying the grid out itself needs the
5322/// text before that decision was made.
5323#[derive(Clone)]
5324pub struct TableCell {
5325    pub glyphs: Vec<Glyph>,
5326    pub start: usize,
5327    pub end: usize,
5328    pub align: Alignment,
5329}
5330
5331/// One row of a table's grid, as the document spells it — not as it's drawn.
5332#[derive(Clone)]
5333pub struct TableRow {
5334    /// A header row: drawn bold, and ruled off from the body below it.
5335    pub head: bool,
5336    pub cells: Vec<TableCell>,
5337}
5338
5339/// A table's structure, published alongside the box-drawn rows that spell it.
5340///
5341/// The rows in [`VisualMap::rows`] are the *default monospace* picture of a
5342/// table: every border a `│`, every column a whole number of character cells.
5343/// That picture is exactly right on any monospace surface, and unfixable off one
5344/// — in a proportional font the `│`s of two rows land at different x and the grid
5345/// shears. So a frontend that draws its own geometry reads this instead: the
5346/// cells, their alignment, and which rows are the head, with no opinion about
5347/// how wide a column is or what a border looks like.
5348///
5349/// Both are always built. The TUI paints `rows` and ignores this; the GUI skips
5350/// `rows` for the span in `rows_span` and draws from here. They describe the
5351/// same cells, so the caret lands on the same offsets either way.
5352#[derive(Clone)]
5353pub struct TableInfo {
5354    /// The `VisualMap::rows` this table's picture occupies, borders included —
5355    /// what a frontend drawing its own table skips over.
5356    pub rows_span: Range<usize>,
5357    /// The end of the table node's source span, and the offset its trailing
5358    /// caret stop sits at — the one caret home past the last cell, held by the
5359    /// bottom border row's end. Typing there opens a paragraph under the table
5360    /// rather than joining the block; see `Doc::open_paragraph_at_block_edge`.
5361    pub end_src: usize,
5362    /// The block prefix every row of this table carries — a blockquote's `│ `
5363    /// gutter, a list item's indent. Empty for a table at the top level.
5364    ///
5365    /// A frontend drawing its own grid has to render this and start the table
5366    /// past it, exactly as the picture does; a table nested in a quote that
5367    /// draws flush at the left margin has left the quote.
5368    pub prefix: Vec<Glyph>,
5369    pub grid: Vec<TableRow>,
5370}
5371
5372/// A fenced or indented code block, named by the [`VisualMap::rows`] it occupies.
5373///
5374/// Unlike a table, the rows *are* the block's content — a frontend still paints
5375/// them, it just draws a border and a tinted background around the whole span
5376/// and lets the code inside scroll horizontally instead of wrapping. So this
5377/// carries only the row range; there's no structural alternative to the picture
5378/// the way [`TableInfo`] is one. Derived from [`VRow::code`] — see
5379/// [`code_block_spans`].
5380#[derive(Clone, Debug, PartialEq, Eq)]
5381pub struct CodeBlockInfo {
5382    /// The contiguous run of [`VisualMap::rows`] this code block spans, blank
5383    /// code lines included.
5384    pub rows_span: Range<usize>,
5385    /// The block's language, from a fenced block's info string — what a frontend
5386    /// paints as a small label on the box (`` ```rust `` → `Some("rust")`).
5387    /// `None` for a fence written without one, or an indented block. Editing it
5388    /// goes through [`crate::Doc::set_code_language`], which re-finds the fence
5389    /// in the AST, so this stays a display string.
5390    pub lang: Option<String>,
5391}
5392
5393/// A block-level image (`![alt](url)` on its own line), named by the single
5394/// [`VisualMap::rows`] row it occupies.
5395///
5396/// Like [`CodeBlockInfo`], the row *is* the block's default rendering — a plain
5397/// surface paints the `🖼 alt` placeholder glyphs as-is. An image-capable
5398/// frontend instead **skips the row in `rows_span`** and paints the resolved
5399/// picture there, exactly as it skips a [`TableInfo`]'s box-drawn rows. Derived
5400/// from [`VRow::media`] by [`media_spans`], so it survives the row reuse of
5401/// [`BlockCache`] and [`build_spliced`].
5402#[derive(Clone, Debug, PartialEq, Eq)]
5403pub struct MediaInfo {
5404    /// The [`VisualMap::rows`] rows this media's placeholder occupies — what a
5405    /// capable frontend replaces with the picture or player.
5406    pub rows_span: Range<usize>,
5407    /// Whether this is a picture, a movie, or a sound — which widget the
5408    /// frontend builds over [`rows_span`](MediaInfo::rows_span). A frontend that
5409    /// handles only some kinds leaves the rest as core's placeholder rows, which
5410    /// already read sensibly on their own.
5411    pub kind: MediaKind,
5412    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
5413    /// the AST. A frontend resolves a relative path against the document's own
5414    /// directory; core does no I/O. For a `<picture>` this is the `<img>`
5415    /// fallback — the source used when no [`sources`](MediaInfo::sources) media
5416    /// query matches (or the frontend has no theme). Empty when a `<video>`/
5417    /// `<audio>` carries no `src` and names its candidates in `<source>`s
5418    /// instead; [`resolve`](MediaInfo::resolve) already accounts for that.
5419    pub destination: String,
5420    /// The `<source>` alternatives in document order, or empty for a plain
5421    /// image. See [`MediaSource`]; a theme- or codec-aware frontend picks one and
5422    /// otherwise loads [`destination`](MediaInfo::destination).
5423    pub sources: Vec<MediaSource>,
5424    /// The media's alt text, flattened from its inline children (empty when it
5425    /// has none).
5426    pub alt: String,
5427    /// A `<video poster="…">`'s still frame, or empty when there is none — an
5428    /// image destination, resolved exactly as [`destination`] is.
5429    ///
5430    /// [`destination`]: MediaInfo::destination
5431    pub poster: String,
5432}
5433
5434/// One leaf directive (`::name{…}`) as a frontend sees it: which rows its
5435/// placeholder occupies, its type, and its attributes. A plain surface paints
5436/// the `⧉ name` placeholder glyphs as-is; a frontend that knows the host app's
5437/// vocabulary **skips the rows in `rows_span`** and paints the real thing there,
5438/// exactly as an image-capable one does with [`MediaInfo`]. Derived from
5439/// [`VRow::leaf_directive`] by [`directive_spans`].
5440///
5441/// Core resolves nothing here — it has no idea what an `embed` or a `toc` is,
5442/// and deliberately so: the directive vocabulary belongs to the app on top.
5443#[derive(Clone, Debug, PartialEq, Eq)]
5444pub struct DirectiveInfo {
5445    /// The [`VisualMap::rows`] rows this directive's placeholder occupies — the
5446    /// label row plus any blank fillers under it.
5447    pub rows_span: Range<usize>,
5448    /// The directive's type (`embed`, `toc`, `vis`), no leading colons.
5449    pub name: String,
5450    /// Its `{…}` attributes in source order; a bare one has a `None` value.
5451    pub attrs: Vec<(String, Option<String>)>,
5452    /// Its `[label]` text, flattened from its inline children (empty when it has
5453    /// none) — what the placeholder row shows.
5454    pub label: String,
5455}
5456
5457/// One formula as a frontend sees it: where its picture goes, and the TeX to
5458/// typeset for it. Two shapes, told apart by [`glyph`](MathInfo::glyph):
5459///
5460/// - An **inline atom** — `$E = mc^2$` in a line of prose — is one
5461///   [`Role::Math`] glyph on `row` at index `glyph`, standing for the whole
5462///   formula. A frontend that paints pictures in a line typesets the TeX at
5463///   the run's font size and draws the picture in the glyph's place, as wide
5464///   as the picture is and with the text baseline through it at its height —
5465///   a run delegate on Apple, an inline element on the web. The glyph is a
5466///   caret stop at the formula's start; the stop after it is the next glyph's.
5467/// - A **display block** — a paragraph holding nothing but `$$…$$` — is the
5468///   placeholder row (`∑ tex`, every glyph at the formula's start) plus the
5469///   blank fillers `rows_span` reserves under it, exactly a [`MediaInfo`]'s
5470///   shape. A frontend skips those rows and paints the picture there, centred
5471///   on the measure.
5472///
5473/// Either way the frontend supplies the *width*: core lays out in glyphs and
5474/// cannot know how wide a typeset formula is, which is why an inline atom is
5475/// one glyph and not a run of them. Only in a **column-wrapped** build does
5476/// that matter to the wrap: a terminal never asks for atoms (see
5477/// [`Surface::inline_pictures`]), and the web re-fits a row the picture
5478/// overflows.
5479///
5480/// A plain surface paints the glyphs as they are — `∑` for an atom, the
5481/// labelled row for a block — and needs none of this. Derived from
5482/// [`VRow::math`] by [`math_spans`], so it survives the row reuse of
5483/// [`BlockCache`] and [`build_spliced`].
5484#[derive(Clone, Debug, PartialEq, Eq)]
5485pub struct MathInfo {
5486    /// The [`VisualMap::rows`] rows this formula occupies: `row..row + 1` for
5487    /// an atom, the placeholder row and its fillers for a block.
5488    pub rows_span: Range<usize>,
5489    /// The row the atom glyph, or the block's placeholder label, is on.
5490    pub row: usize,
5491    /// The atom's index into that row's glyphs, or `None` for a block.
5492    pub glyph: Option<usize>,
5493    /// The TeX between the delimiters, verbatim.
5494    pub tex: String,
5495    /// Display style rather than text style — see [`MathMark::display`].
5496    pub display: bool,
5497    /// The formula's source start: where a click on its picture lands the
5498    /// caret, and the same offset every placeholder glyph carries.
5499    pub src: usize,
5500}
5501
5502impl DirectiveInfo {
5503    /// The value of attribute `key`, if it has one with a value. The convenience
5504    /// a frontend reaches for first (`info.attr("src")`), since almost every
5505    /// directive that draws as something real is pointed at by one attribute.
5506    pub fn attr(&self, key: &str) -> Option<&str> {
5507        self.attrs
5508            .iter()
5509            .find(|(k, _)| k == key)
5510            .and_then(|(_, v)| v.as_deref())
5511    }
5512}
5513
5514impl MediaInfo {
5515    /// The image URL to load under `scheme`: the first [`sources`] `<source>`
5516    /// whose media query matches, else the [`destination`] `<img>` fallback. The
5517    /// pick is a `<source>`'s first `srcset` URL or the destination — a frontend
5518    /// resolves whichever it gets against the document directory exactly as it
5519    /// resolves `destination`, and reserves/keys the picture under `destination`
5520    /// regardless, so a theme switch just re-picks without disturbing the layout.
5521    ///
5522    /// Only `prefers-color-scheme` is understood (that's what a light/dark banner
5523    /// uses); a `<source>` with any other media query is skipped, and one with no
5524    /// media at all always matches (an unconditional override). With no matching
5525    /// source — including every frontend that can't/doesn't theme and passes
5526    /// [`ColorScheme::Light`] to a dark-only picture — it's the plain `<img>`.
5527    ///
5528    /// [`sources`]: MediaInfo::sources
5529    /// [`destination`]: MediaInfo::destination
5530    pub fn resolve(&self, scheme: ColorScheme) -> &str {
5531        if let Some(url) = self
5532            .sources
5533            .iter()
5534            .find(|s| media_matches(&s.media, scheme))
5535            .and_then(|s| first_srcset_url(&s.srcset))
5536        {
5537            return url;
5538        }
5539        // A `<video>`/`<audio>` may carry no `src` of its own, naming its
5540        // candidates only in child `<source>`s — none of which matched above,
5541        // because a codec-typed `<source>` has no media query and core judges no
5542        // MIME types. Falling through to an empty destination would hand the
5543        // frontend nothing to load, so take the first candidate URL instead and
5544        // let the frontend reject it if it can't decode it. An `<img>` never
5545        // reaches this: its `src` is the picture.
5546        if self.destination.is_empty()
5547            && let Some(url) = self
5548                .sources
5549                .iter()
5550                .find_map(|s| first_srcset_url(&s.srcset))
5551        {
5552            return url;
5553        }
5554        &self.destination
5555    }
5556
5557    /// The **still picture** that stands for this media under `scheme`, for a
5558    /// frontend that can rasterize an image but not play a movie — a terminal, or
5559    /// a GUI still growing its player. `None` when there is no picture to draw,
5560    /// which is the honest answer for audio and for a poster-less video: the
5561    /// caller leaves core's labelled placeholder row, which already reads as
5562    /// *a thing that isn't text*.
5563    ///
5564    /// This exists so those frontends never hand a `.mp4` to an image decoder.
5565    /// That fails harmlessly today (a failed decode falls back to the same
5566    /// placeholder), but it spends a file read and a decode attempt per frame to
5567    /// arrive where this gets in one match.
5568    pub fn still(&self, scheme: ColorScheme) -> Option<&str> {
5569        match self.kind {
5570            MediaKind::Image => Some(self.resolve(scheme)),
5571            // A `poster` is an image destination, so it resolves the same way —
5572            // but it is named directly and has no `<source>` alternatives of its
5573            // own, so it needs no theme matching.
5574            MediaKind::Video if !self.poster.is_empty() => Some(&self.poster),
5575            MediaKind::Video | MediaKind::Audio => None,
5576        }
5577    }
5578}
5579
5580/// A frontend's active color scheme — what a `<picture>`'s `prefers-color-scheme`
5581/// `<source>`s are matched against by [`MediaInfo::resolve`]. A frontend with no
5582/// notion of theme passes [`Light`](ColorScheme::Light), the web's own default.
5583#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5584pub enum ColorScheme {
5585    Light,
5586    Dark,
5587}
5588
5589/// Whether a `<source media="…">` query applies under `scheme`. Empty media is
5590/// an unconditional `<source>` (always matches); otherwise only a
5591/// `prefers-color-scheme: dark|light` feature is understood — anything else
5592/// (a width query, `print`, …) doesn't match, so resolution falls through to the
5593/// next source or the `<img>`. Deliberately lax about the surrounding syntax
5594/// (`(prefers-color-scheme: dark)`, `screen and (prefers-color-scheme:dark)`):
5595/// it keys off the feature and its value, which is all the theme case needs.
5596fn media_matches(media: &str, scheme: ColorScheme) -> bool {
5597    let media = media.trim();
5598    if media.is_empty() {
5599        return true;
5600    }
5601    let lower = media.to_ascii_lowercase();
5602    let Some(after) = lower
5603        .split_once("prefers-color-scheme")
5604        .map(|(_, rest)| rest)
5605    else {
5606        return false;
5607    };
5608    // Skip the `:` and any spaces to reach the value word.
5609    let value = after.trim_start_matches([':', ' ', '\t']);
5610    let wanted = match scheme {
5611        ColorScheme::Light => "light",
5612        ColorScheme::Dark => "dark",
5613    };
5614    value.starts_with(wanted)
5615}
5616
5617/// The first URL in a `srcset`: its first comma-separated candidate, before any
5618/// `1x`/`2x`/width descriptor. The theme case only ever puts one URL per
5619/// `<source>`, so the first candidate is the picture.
5620fn first_srcset_url(srcset: &str) -> Option<&str> {
5621    let first = srcset.split(',').next()?.trim();
5622    first.split_whitespace().next().filter(|u| !u.is_empty())
5623}
5624
5625/// The narrowest a column may be squeezed. Below a few characters a column
5626/// stops carrying text and just shreds it one letter per line, which is worse
5627/// than letting the grid run wide.
5628const MIN_COL_WIDTH: usize = 3;
5629
5630/// Shrink `widths` until the grid fits `avail` screen columns, taking from the
5631/// widest column each time so the loss is shared out rather than falling on
5632/// whichever column happens to be last. No column goes below
5633/// [`MIN_COL_WIDTH`]; a table with more columns than the surface has room for
5634/// still overflows, which is the honest outcome — there's nothing left to give.
5635fn fit_widths(widths: &mut [usize], avail: usize) {
5636    // Chrome: each column is its content plus a gutter either side, and every
5637    // column is closed by a `│` — with one more opening the row.
5638    let budget = avail.saturating_sub(3 * widths.len() + 1);
5639    while widths.iter().sum::<usize>() > budget {
5640        let Some(w) = widths.iter_mut().filter(|w| **w > MIN_COL_WIDTH).max() else {
5641            return;
5642        };
5643        *w -= 1;
5644    }
5645}
5646
5647/// Word-wrap `glyphs` into lines of at most `width` columns, hard-breaking any
5648/// single word too long to fit.
5649///
5650/// Unlike a paragraph — where an overlong word just trails off the end of the
5651/// line — a table column is a hard boundary: a glyph past it lands on top of
5652/// the border, or on the next cell. So the width here is a promise, and a word
5653/// that won't keep it is broken.
5654///
5655/// The space at a break is dropped rather than hung past the edge. Its offset
5656/// isn't lost: the caller gives every line an end stop just past its last
5657/// glyph, which is exactly where that space was.
5658///
5659/// `width` is in display columns, and a break only ever falls between grapheme
5660/// clusters. Both matter to more than the picture: the caller anchors each
5661/// line's end stop just past its last glyph, so a line cut mid-cluster would
5662/// put a caret stop inside a character — reachable by Down or a click, and the
5663/// next Backspace would take the cluster apart from the middle.
5664///
5665/// An explicit in-cell break (a `\n` glyph, from a `<br>`) is a hard boundary:
5666/// each run between the breaks wraps on its own and the results stack. The break
5667/// glyphs are dropped — the caller's per-line end stop already sits exactly where
5668/// each break was, so no offset is lost.
5669fn wrap_glyphs(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
5670    if glyphs.iter().any(|g| g.ch == '\n') {
5671        return glyphs
5672            .split(|g| g.ch == '\n')
5673            .flat_map(|seg| wrap_segment(seg, width))
5674            .collect();
5675    }
5676    wrap_segment(glyphs, width)
5677}
5678
5679/// [`wrap_glyphs`] for a run with no explicit breaks — the word-wrap proper.
5680fn wrap_segment(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
5681    let width = width.max(1);
5682    // Words are maximal non-space runs, each carrying the space that followed it
5683    // — which survives only if the next word joins it on this line.
5684    let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
5685    let mut word: Vec<Glyph> = Vec::new();
5686    for g in glyphs {
5687        if g.ch == ' ' {
5688            words.push((std::mem::take(&mut word), Some(g.clone())));
5689        } else {
5690            word.push(g.clone());
5691        }
5692    }
5693    if !word.is_empty() {
5694        words.push((word, None));
5695    }
5696
5697    let mut lines: Vec<Vec<Glyph>> = Vec::new();
5698    let mut line: Vec<Glyph> = Vec::new();
5699    let mut used = 0usize;
5700    let mut gap: Option<Glyph> = None;
5701    for (word, space) in words {
5702        for chunk in hard_break(&word, width) {
5703            let sep = gap.is_some() as usize;
5704            let cells = glyphs_width(chunk);
5705            if !line.is_empty() && used + sep + cells > width {
5706                lines.push(std::mem::take(&mut line));
5707                used = 0;
5708                gap = None; // the break swallows the space
5709            }
5710            if let Some(sp) = gap.take() {
5711                line.push(sp);
5712                used += 1;
5713            }
5714            line.extend_from_slice(chunk);
5715            used += cells;
5716        }
5717        gap = space;
5718    }
5719    // An empty cell is still one (empty) line — it has an end the caret can
5720    // sit at, which is how you type into it.
5721    if !line.is_empty() || lines.is_empty() {
5722        lines.push(line);
5723    }
5724    lines
5725}
5726
5727/// Break a single word into pieces of at most `width` columns, cutting only
5728/// between grapheme clusters — the replacement for slicing it into fixed runs
5729/// of glyphs, which measures a wide character as one column and can cut an
5730/// emoji in half.
5731///
5732/// A cluster wider than the whole column still gets a piece to itself: there is
5733/// nowhere legal to cut it, and overflowing by a cell is better than splitting a
5734/// character. An empty word yields no pieces at all, which is what keeps a
5735/// double space from opening a line of its own.
5736fn hard_break(word: &[Glyph], width: usize) -> Vec<&[Glyph]> {
5737    let mut out = Vec::new();
5738    if word.is_empty() {
5739        return out;
5740    }
5741    let (mut start, mut used) = (0usize, 0usize);
5742    for c in clusters(word) {
5743        if used > 0 && used + c.cells > width {
5744            out.push(&word[start..c.glyph]);
5745            start = c.glyph;
5746            used = 0;
5747        }
5748        used += c.cells;
5749    }
5750    out.push(&word[start..]);
5751    out
5752}
5753
5754/// A table rule spanning `widths`, e.g. `┌──────┬─────┐`. Each column is its
5755/// content width plus the one-space gutter on either side.
5756fn rule_text(widths: &[usize], left: char, mid: char, right: char) -> String {
5757    let mut s = String::new();
5758    s.push(left);
5759    for (i, w) in widths.iter().enumerate() {
5760        if i > 0 {
5761            s.push(mid);
5762        }
5763        for _ in 0..w + 2 {
5764            s.push('─');
5765        }
5766    }
5767    s.push(right);
5768    s
5769}
5770
5771/// Push real document text: each glyph maps to its own source byte, and the one
5772/// that opens a grapheme cluster is the caret stop for the whole cluster.
5773///
5774/// Per cluster rather than per codepoint because a cluster is the character the
5775/// user sees, and it's the unit backspace and delete already step by. A stop
5776/// inside 👨‍👩‍👧 — five codepoints strung together with joiners — is a caret
5777/// parked in the middle of a character: one press of Right lands there, and the
5778/// next Backspace severs a joiner from what it joined, leaving a dangling ZWJ in
5779/// the source. The rest of the cluster still gets its glyph (it has to be
5780/// drawn); it just isn't somewhere to stand.
5781fn push_text(out: &mut Vec<Glyph>, text: &str, base_src: usize, style: Style) {
5782    for (gi, cluster) in text.grapheme_indices(true) {
5783        for (ci, ch) in cluster.char_indices() {
5784            out.push(Glyph {
5785                ch,
5786                style,
5787                src: base_src + gi + ci,
5788                stop: ci == 0,
5789            });
5790        }
5791    }
5792}
5793
5794/// [`push_text`] for one line of a highlighted code block: the same glyphs at
5795/// the same offsets, each additionally carrying the [`Token`] of the span it
5796/// falls in — `spans` being the line's entry from [`code_tokens`], ascending
5797/// byte ranges *into `text`*. A byte between spans keeps `style` as it is.
5798///
5799/// Offsets are what matters here: a token changes how a glyph is painted and
5800/// nothing about where it is or which source byte it stands on, so a caret
5801/// walks a highlighted block exactly as it walks an unhighlighted one.
5802fn push_code_text(
5803    out: &mut Vec<Glyph>,
5804    text: &str,
5805    base_src: usize,
5806    style: Style,
5807    spans: &[(Range<usize>, Token)],
5808) {
5809    let mut spans = spans.iter().peekable();
5810    for (gi, cluster) in text.grapheme_indices(true) {
5811        // Spans are ascending, so the one covering this cluster's first byte
5812        // is at or after the one that covered the last; step past those ended.
5813        while spans.peek().is_some_and(|(r, _)| r.end <= gi) {
5814            spans.next();
5815        }
5816        let token = spans
5817            .peek()
5818            .filter(|(r, _)| r.contains(&gi))
5819            .map(|(_, t)| *t);
5820        // A cluster is classed whole, by its first byte: a grammar that split
5821        // an emoji's scalars between two tokens would otherwise split the
5822        // glyph, and no grammar means to.
5823        let style = style.token(token);
5824        for (ci, ch) in cluster.char_indices() {
5825            out.push(Glyph {
5826                ch,
5827                style,
5828                src: base_src + gi + ci,
5829                stop: ci == 0,
5830            });
5831        }
5832    }
5833}
5834
5835/// One line's highlighting — `crate::syntax::LineTokens`, spelled here so the
5836/// shape exists whether or not the feature that fills it does.
5837type LineTokens = Vec<(Range<usize>, Token)>;
5838
5839/// The syntax highlighting for a code block's lines, or `None` when the fence's
5840/// language is not one the grammars know. Without the `syntax` feature nothing
5841/// is known, and every code glyph draws in the plain code colour.
5842#[cfg(feature = "syntax")]
5843fn code_tokens(lang: &str, lines: &[&str]) -> Option<Vec<LineTokens>> {
5844    crate::syntax::highlight(lang, lines)
5845}
5846
5847#[cfg(not(feature = "syntax"))]
5848fn code_tokens(_lang: &str, _lines: &[&str]) -> Option<Vec<LineTokens>> {
5849    None
5850}
5851
5852/// Emit an inline `str`/`smart_punctuation` run, mapping every visible char back
5853/// to its *true* source byte even when the source carries backslash escapes the
5854/// parsed `text` dropped (`\*` → `*`). The naive `span.start + text_offset`
5855/// mapping [`push_text`] uses drifts by one byte after each escape, so a caret or
5856/// click past an escaped `*` would land on the wrong character; walking the text
5857/// against its source keeps them aligned, and the hidden escape backslash gets no
5858/// glyph of its own (it is a spelling artefact, not something the caret lands on).
5859fn push_escaped_text(
5860    out: &mut Vec<Glyph>,
5861    text: &str,
5862    span: Range<usize>,
5863    source: &str,
5864    style: Style,
5865) {
5866    let end = span.end.min(source.len());
5867    let src = source.get(span.start..end).unwrap_or("");
5868    // Fast path — no dropped bytes, so text and source align 1:1 (the common
5869    // case: prose with no escapes). Byte lengths equal ⇒ no backslash was eaten.
5870    if src.len() == text.len() {
5871        push_text(out, text, span.start, style);
5872        return;
5873    }
5874    // Slow path: some `\` was consumed. Walk char-by-char, skipping a backslash
5875    // in the source exactly when it escapes the next visible char (a real escape),
5876    // never when it is a literal backslash the parse kept (that case has equal
5877    // lengths and takes the fast path above).
5878    let sb = src.as_bytes();
5879    let mut si = 0usize;
5880    'text: for (_, cluster) in text.grapheme_indices(true) {
5881        for (ci, ch) in cluster.char_indices() {
5882            // The text outlasted the source it is being mapped onto. In a
5883            // consistent document that cannot happen on this path: the slow path
5884            // is only entered when the two lengths differ, and everything that
5885            // makes them differ makes the *source* the longer one — an escape
5886            // backslash the parse ate, or source folded into a neighbouring node.
5887            // A `smart_punctuation` node reports its canonical ASCII spelling
5888            // (`--`, `...`, `"`), which is never longer than what was written.
5889            //
5890            // So reaching here means `span` was measured against a document that
5891            // `source` is no longer, and there is no honest offset left to give
5892            // the remaining characters. Stop: the row comes out short, which is
5893            // a wrong picture of a document that is already inconsistent. The
5894            // alternative was `si` stepping past the end and the slice below
5895            // panicking — which is what it did, in a paint loop.
5896            if si >= sb.len() {
5897                break 'text;
5898            }
5899            // Advance to the source character this one came from, stepping over
5900            // whatever the parse dropped on the way. An escape backslash is the
5901            // common case, but not the only one: a span can cover source that
5902            // was folded into a neighbouring node (smart punctuation next to a
5903            // bracket gives `text: "]"` over a source span of `"…]"`). Advancing
5904            // by the *text* character's length assumed escapes were the only
5905            // divergence, so one dropped multi-byte character desynchronized
5906            // every glyph after it — placing `]` inside the `…` before it.
5907            while si < sb.len() && !src[si..].starts_with(ch) {
5908                si += src[si..].chars().next().map_or(1, char::len_utf8);
5909            }
5910            out.push(Glyph {
5911                ch,
5912                style,
5913                src: span.start + si.min(src.len()),
5914                stop: ci == 0,
5915            });
5916            si += src[si..]
5917                .chars()
5918                .next()
5919                .map_or(ch.len_utf8(), char::len_utf8);
5920        }
5921    }
5922}
5923
5924/// Build synthetic decoration glyphs (a bullet, a gutter) all pointing at `src`,
5925/// each carrying `role` so the frontend can style it (`Role::Body` for plain
5926/// padding). Synthetic glyphs are never caret stops — they share one offset, so
5927/// the caret steps over them (a click still lands at `src`).
5928fn synth(text: &str, role: Role, src: usize) -> Vec<Glyph> {
5929    let style = Style::default().role(role);
5930    text.chars()
5931        .map(|ch| Glyph {
5932            ch,
5933            style,
5934            src,
5935            stop: false,
5936        })
5937        .collect()
5938}
5939
5940fn concat(a: &[Glyph], b: &[Glyph]) -> Vec<Glyph> {
5941    let mut v = a.to_vec();
5942    v.extend_from_slice(b);
5943    v
5944}
5945
5946/// The columns a row's prefix (a bullet, a quote gutter, an indent) takes up
5947/// before the text it introduces — what the wrap budget has left to spend.
5948fn prefix_width(prefix: &[Glyph]) -> usize {
5949    glyphs_width(prefix)
5950}
5951
5952/// The label shown for an image with no alt text: the final path segment of its
5953/// destination (`img/cat.png` → `cat.png`), the whole destination when it has no
5954/// separator, and `"image"` when it's empty. A `data:` URI (which has no useful
5955/// tail) shows its scheme so the placeholder isn't a wall of base64.
5956fn media_label(dest: &str) -> String {
5957    if dest.is_empty() {
5958        return "image".to_string();
5959    }
5960    if dest.starts_with("data:") {
5961        return "data:…".to_string();
5962    }
5963    // Trim a query/fragment so a URL's `?v=2#frag` doesn't ride along.
5964    let clean = dest.split(['?', '#']).next().unwrap_or(dest);
5965    let tail = clean
5966        .trim_end_matches('/')
5967        .rsplit(['/', '\\'])
5968        .next()
5969        .unwrap_or(clean);
5970    if tail.is_empty() {
5971        dest.to_string()
5972    } else {
5973        tail.to_string()
5974    }
5975}
5976
5977/// A directive's attributes read as a human label — what a frontend puts on a
5978/// container's tinted panel, and what an attribute-bearing inline directive
5979/// shows in its chip.
5980///
5981/// Reads BOTH conventions diaryx content actually uses: twig's own dot-prefixed
5982/// classes (`{.public .family}`, arriving as one combined `class` attr) and bare
5983/// pandoc-style words with no leading dot (`{public family}` — what
5984/// `diaryx_core::visibility`'s publish-time filter and apps/web's directive
5985/// serializer both write, and which twig parses as one valueless attribute
5986/// each). Reading only `.class` would leave every *existing* diaryx `:::vis{…}`
5987/// block unlabeled. A `key=value` attr is configuration rather than a name, so
5988/// it contributes nothing. `None` when nothing readable is left.
5989fn directive_attr_label(attrs: &[(String, Option<String>)]) -> Option<String> {
5990    let mut parts: Vec<String> = Vec::new();
5991    for (k, v) in attrs {
5992        if k == "class" {
5993            if let Some(v) = v
5994                && !v.is_empty()
5995            {
5996                parts.push(v.clone());
5997            }
5998        } else if v.as_deref().unwrap_or("").is_empty() {
5999            parts.push(k.clone());
6000        }
6001    }
6002    (!parts.is_empty()).then(|| parts.join(" "))
6003}
6004
6005fn heading_style(level: u32) -> Style {
6006    // Just the role — a frontend decides how a heading of this level *looks*
6007    // (the terminal cycles a color and bolds it, the GUI scales the font). The
6008    // author wrote no emphasis here, so core records none. `level as u8` is safe:
6009    // Markdown/Djot cap headings at 6.
6010    Style::default().role(Role::Heading(level.min(255) as u8))
6011}
6012
6013/// Is this `container` node a *directive* (`:::note{…}`, `::embed{…}`,
6014/// `:vis[…]`) rather than an HTML element (`<video>`, `<picture>`, `<div>`)?
6015///
6016/// twig 2.8 folded `div`/`span`/`directive`/`element` into one `container` kind,
6017/// and left nothing that separated them: `kind`, `name` and `directive_form` all
6018/// agree, field for field, on an HTML `<div>` and a Markdown `:::div`. Leaf
6019/// answered it by sniffing the span for whichever of `:` or `<` came first.
6020/// twig 3.0 records the answer at parse time as [`ContainerOrigin`], so this is
6021/// now the parser's own knowledge rather than a guess rebuilt from the bytes it
6022/// consumed.
6023pub(crate) fn container_is_directive(node: &FlatNode) -> bool {
6024    node.origin == Some(ContainerOrigin::Directive)
6025}
6026
6027/// The tag a `container` node carries when it is an HTML element rather than a
6028/// directive — `Some("video")` for a promoted `<video>`, `None` for a `:::note`
6029/// or for any node that is not a container at all.
6030pub(crate) fn element_tag(node: &FlatNode) -> Option<&str> {
6031    (node.origin == Some(ContainerOrigin::Element))
6032        .then_some(node.name.as_deref())
6033        .flatten()
6034}
6035
6036/// A leaf directive's name and whatever attributes are not part of spelling
6037/// it — the two things a [`DirectiveMark`] carries, which twig hands back
6038/// differently per format and which a frontend must not be able to tell apart.
6039///
6040/// Markdown's `::page-break` is a `Leaf`-form directive *named* `page-break`
6041/// with no attributes, and this returns it verbatim. Djot has no leaf form:
6042/// `insert_directive` writes the same document as an empty `::: page-break`
6043/// fence, whose container is anonymous (a djot div carries no name) and whose
6044/// name arrives as the fence's one class. So where the node has no name of its
6045/// own the first `class` token *is* the name, and whatever else the class said
6046/// — an author's `::: page-break {.wide}` — stays an attribute.
6047fn leaf_directive_identity(node: &FlatNode) -> (String, Vec<(String, Option<String>)>) {
6048    let named = node.name.clone().unwrap_or_default();
6049    if !named.is_empty() {
6050        return (named, node.attrs.clone());
6051    }
6052    let class = node
6053        .attrs
6054        .iter()
6055        .find(|(k, _)| k == "class")
6056        .and_then(|(_, v)| v.as_deref())
6057        .unwrap_or_default();
6058    let mut tokens = class.split_whitespace();
6059    let Some(name) = tokens.next().map(str::to_string) else {
6060        return (named, node.attrs.clone());
6061    };
6062    let rest = tokens.collect::<Vec<_>>().join(" ");
6063    let attrs = node
6064        .attrs
6065        .iter()
6066        .filter_map(|(k, v)| {
6067            if k != "class" {
6068                return Some((k.clone(), v.clone()));
6069            }
6070            (!rest.is_empty()).then(|| (k.clone(), Some(rest.clone())))
6071        })
6072        .collect();
6073    (name, attrs)
6074}
6075
6076/// Is this inline `container` an **attributed span** — the node leaf's run-level
6077/// vocabulary rides — rather than a named directive?
6078///
6079/// The four formats spell one span four ways and twig hands the name back for
6080/// two of them: HTML's and Markdown's `<span …>` arrive named `span` with
6081/// `Element` origin, while djot's `[text]{…}` and AsciiDoc's `[.a]#text#`
6082/// arrive anonymous (an empty name) with `Directive` origin. All four are the
6083/// same node to `wrap_range_attrs`, which is what writes them, so they are the
6084/// same node here.
6085///
6086/// A *named* directive is not one, whatever its name: a Markdown `:span[…]{…}`
6087/// is a directive the parser read as a directive, twig's own
6088/// `wrap_range_attrs` says so, and it keeps the handling it has.
6089///
6090/// **Anonymous is not enough**, and the form is what finishes the question:
6091/// a djot fenced div (`{.center}` / `:::` / … / `:::`) is anonymous too, with
6092/// the same `Directive` origin, and is a *block* — `Container` form against the
6093/// span's `Text`. Reading one as a span made every gesture and every query lie
6094/// about it: `set_text_color` over a word inside such a div copied the whole
6095/// div's attribute set — its `id` along with the rest — onto the new span, and
6096/// `alignment_at_caret` reported the div's `.center` as a *run's* answer while
6097/// the walker drew none. So the anonymous arm asks the form [`is_inline`] asks.
6098pub(crate) fn is_run_span(node: &FlatNode) -> bool {
6099    if node.kind != Kind::Container {
6100        return false;
6101    }
6102    match node.name.as_deref() {
6103        None | Some("") => node.directive_form == Some(DirectiveForm::Text),
6104        Some("span") => node.origin == Some(ContainerOrigin::Element),
6105        Some(_) => false,
6106    }
6107}
6108
6109/// `base` with an attributed span's three run-level keys written over it — the
6110/// nearest-wins fold [`is_run_span`] describes, for one span. `faces` is the
6111/// build's intern table, as it is for [`Presentation::under`].
6112fn run_style(node: &FlatNode, base: Style, faces: &RefCell<FaceTable>) -> Style {
6113    Style {
6114        size: FontSize::from_attrs(&node.attrs).or(base.size),
6115        font: faces
6116            .borrow_mut()
6117            .face_from_attrs(&node.attrs)
6118            .or(base.font),
6119        color: TextColor::from_attrs(&node.attrs).or(base.color),
6120        ..base
6121    }
6122}
6123
6124pub(crate) fn is_inline(node: &FlatNode) -> bool {
6125    // A directive is inline only in its `text` form (`:name[label]{…}`); the
6126    // `leaf` and `container` forms are blocks. All three report the same `kind`,
6127    // so the form is the only thing telling them apart — and getting it wrong
6128    // costs a whole paragraph: a text directive misread as a block makes its
6129    // paragraph fail the "all children inline" test in `block`, and the line is
6130    // then walked as a container of blocks, rendering as empty rows with no
6131    // caret home at all.
6132    //
6133    // An HTML element shares the `container` kind, and twig sets the same form
6134    // on the two tags the lightweight formats have a generic spelling for: a
6135    // `<span>` is `Text` and a `<div>` is `Container`, while a `<video>` or a
6136    // `<picture>` has no form at all. So the form answers for an element as it
6137    // answers for a directive, and the origin is not consulted — which is what
6138    // makes a `<span …>` inside a paragraph an inline node.
6139    //
6140    // It has to. `wrap_range_attrs` spells an attributed run as exactly that
6141    // span in Markdown and HTML, and a paragraph holding one whose kids were
6142    // not all inline failed the test below and was walked as a container of
6143    // blocks: the text either side of the span rendered as nothing at all.
6144    if node.kind == Kind::Container {
6145        return node.directive_form == Some(DirectiveForm::Text);
6146    }
6147    is_inline_kind(&node.kind)
6148}
6149
6150/// [`is_inline`] by kind alone — for the ancestor walks, whose `QueryMatch`es
6151/// carry no `directive_form`. It answers `false` for every directive, which its
6152/// callers must (and do) reconcile: they pair it with `is_block_container`,
6153/// which claims every directive, so the pair's verdict is the same one a form
6154/// would have given. Anything looking at a *directive itself* wants [`is_inline`]
6155/// and a real node.
6156pub(crate) fn is_inline_kind(kind: &Kind) -> bool {
6157    matches!(
6158        kind,
6159        Kind::Str
6160            | Kind::SoftBreak
6161            | Kind::HardBreak
6162            | Kind::NonBreakingSpace
6163            | Kind::Emph
6164            | Kind::Strong
6165            | Kind::Mark
6166            | Kind::Insert
6167            | Kind::Delete
6168            | Kind::Verbatim
6169            | Kind::InlineMath
6170            | Kind::DisplayMath
6171            | Kind::Url
6172            | Kind::Email
6173            | Kind::Link
6174            | Kind::Image
6175            | Kind::SmartPunctuation
6176            | Kind::Superscript
6177            | Kind::Subscript
6178            | Kind::FootnoteReference
6179    )
6180}
6181
6182/// Assert two maps are identical down to every glyph, stop, and table span — the
6183/// contract `build_cached` and `build_spliced` must hold against `build`. Lives
6184/// at module scope (not in `mod tests`) so the Doc-driven differential test in
6185/// `doc.rs` can reach it and the private `stops` field it compares.
6186#[cfg(test)]
6187pub(crate) fn assert_maps_eq(a: &VisualMap, b: &VisualMap, ctx: &str) {
6188    assert_eq!(a.rows.len(), b.rows.len(), "row count ({ctx})");
6189    for (i, (ra, rb)) in a.rows.iter().zip(&b.rows).enumerate() {
6190        assert_eq!(ra.end_src, rb.end_src, "row {i} end_src ({ctx})");
6191        assert_eq!(ra.decoration, rb.decoration, "row {i} decoration ({ctx})");
6192        // The incremental walk labels a boundary from a query match's kind
6193        // string and the whole-arena walk from a `FlatNode`'s; this is what says
6194        // the two doors reach the same answer.
6195        assert_eq!(ra.boundary, rb.boundary, "row {i} boundary ({ctx})");
6196        assert_eq!(ra.code, rb.code, "row {i} code ({ctx})");
6197        assert_eq!(ra.code_lang, rb.code_lang, "row {i} code_lang ({ctx})");
6198        assert_eq!(ra.align, rb.align, "row {i} align ({ctx})");
6199        assert_eq!(
6200            ra.line_height, rb.line_height,
6201            "row {i} line_height ({ctx})"
6202        );
6203        assert_eq!(
6204            ra.glyphs.len(),
6205            rb.glyphs.len(),
6206            "row {i} glyph count ({ctx})"
6207        );
6208        for (j, (ga, gb)) in ra.glyphs.iter().zip(&rb.glyphs).enumerate() {
6209            assert_eq!(
6210                (ga.ch, ga.src, ga.stop, ga.style),
6211                (gb.ch, gb.src, gb.stop, gb.style),
6212                "row {i} glyph {j} ({ctx})"
6213            );
6214        }
6215    }
6216    assert_eq!(a.content_start, b.content_start, "content_start ({ctx})");
6217    assert_eq!(a.stops, b.stops, "stops ({ctx})");
6218    assert_eq!(a.mark_ends, b.mark_ends, "mark_ends ({ctx})");
6219    assert_eq!(a.tables.len(), b.tables.len(), "table count ({ctx})");
6220    for (i, (ta, tb)) in a.tables.iter().zip(&b.tables).enumerate() {
6221        assert_eq!(ta.rows_span, tb.rows_span, "table {i} rows_span ({ctx})");
6222        assert_eq!(ta.end_src, tb.end_src, "table {i} end_src ({ctx})");
6223    }
6224    assert_eq!(a.code_blocks, b.code_blocks, "code_blocks ({ctx})");
6225    assert_eq!(a.media, b.media, "images ({ctx})");
6226}
6227
6228#[cfg(test)]
6229mod tests {
6230    use super::*;
6231    use crate::style::{FontFamily, LineSpacing, SizeStep};
6232    use twig::{Editor, Format, NodeId};
6233
6234    fn map(src: &str) -> VisualMap {
6235        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6236        build_t(&ed.nodes().unwrap(), src, Some(80))
6237    }
6238
6239    /// [`map`] over a Djot source. Djot is the format that spells superscript
6240    /// and subscript at all — Markdown has no syntax for either.
6241    fn map_djot(src: &str) -> VisualMap {
6242        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
6243        build_t(&ed.nodes().unwrap(), src, Some(80))
6244    }
6245
6246    /// The baseline every glyph spelling `ch` was built with, in row order —
6247    /// how a test reads a raised or lowered run off the map without caring
6248    /// which row it landed on.
6249    fn baselines_of(m: &VisualMap, ch: char) -> Vec<Baseline> {
6250        m.rows
6251            .iter()
6252            .flat_map(|r| r.glyphs.iter())
6253            .filter(|g| g.ch == ch)
6254            .map(|g| g.style.baseline)
6255            .collect()
6256    }
6257
6258    /// [`map`] at a chosen wrap width.
6259    fn map_at(src: &str, wrap: Option<usize>) -> VisualMap {
6260        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6261        build_t(&ed.nodes().unwrap(), src, wrap)
6262    }
6263
6264    /// [`map`], but with twig's `directives` extension on (off by twig's own
6265    /// default) — the `:::name{.class}` fenced-div containers leaf-core's
6266    /// `"directive"` wysiwyg arm renders.
6267    fn map_directives(src: &str) -> VisualMap {
6268        let mut ed = Editor::new_ext(
6269            src.as_bytes(),
6270            Format::Markdown,
6271            twig::MarkdownExtensions {
6272                directives: true,
6273                ..Default::default()
6274            },
6275        )
6276        .unwrap();
6277        build_t(&ed.nodes().unwrap(), src, Some(80))
6278    }
6279
6280    /// [`map`] in `format`, parsed the way every leaf document is — the
6281    /// extensions [`crate::doc::parse_extensions`] turns on, which is what
6282    /// pairs a Markdown `<div …>` with its `</div>` into a container and makes
6283    /// `::page-break` a directive rather than a paragraph of colons.
6284    fn map_leaf(src: &str, format: Format) -> VisualMap {
6285        let mut ed =
6286            Editor::new_ext(src.as_bytes(), format, crate::doc::parse_extensions()).unwrap();
6287        build_t(&ed.nodes().unwrap(), src, Some(80))
6288    }
6289
6290    /// The alignment and line spacing of every row that draws text, in order —
6291    /// how a test reads a block property off the map.
6292    fn line_facts(m: &VisualMap) -> Vec<(Option<Align>, Option<LineHeight>)> {
6293        m.rows
6294            .iter()
6295            .filter(|r| r.glyphs.iter().any(|g| !g.ch.is_whitespace()))
6296            .map(|r| (r.align, r.line_height))
6297            .collect()
6298    }
6299
6300    /// The style of the glyph spelling `ch`, first occurrence — how a test reads
6301    /// a run property off the map.
6302    fn style_of(m: &VisualMap, ch: char) -> Style {
6303        m.rows
6304            .iter()
6305            .flat_map(|r| r.glyphs.iter())
6306            .find(|g| g.ch == ch)
6307            .unwrap_or_else(|| panic!("no glyph {ch:?} in the map"))
6308            .style
6309    }
6310
6311    /// [`map`] with soft breaks preserved (`LineFlow::Preserve`).
6312    fn map_preserve(src: &str, wrap: Option<usize>) -> VisualMap {
6313        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6314        build(
6315            &ed.nodes().unwrap(),
6316            src,
6317            wrap,
6318            true,
6319            &Surface::default(),
6320            None,
6321        )
6322    }
6323
6324    /// The cache-free reference [`build`], with no per-image height overrides —
6325    /// every block image stays its default one-row placeholder. The tests that
6326    /// need a taller image drive it through [`crate::Doc::set_media_rows`] instead.
6327    fn build_t(nodes: &[FlatNode], src: &str, wrap: Option<usize>) -> VisualMap {
6328        build(nodes, src, wrap, false, &Surface::default(), None)
6329    }
6330
6331    /// An arena and a string that disagree — spans reaching past the source they
6332    /// are built against.
6333    ///
6334    /// [`crate::Doc`] keeps the two in step, so this is a "cannot happen" that
6335    /// nonetheless *did*: `examples/bench` timed a loop of `edit_range` and then
6336    /// went on handing the grown editor's spans to a builder holding the string
6337    /// from before it, and every run ended in a slice panic rather than a
6338    /// number. `push_escaped_text` was already written to survive the mismatch —
6339    /// it clamps the span's end and falls back to an empty slice — and this is
6340    /// the half of that intent it did not carry through.
6341    ///
6342    /// Rendering the wrong thing is the acceptable answer here; panicking in a
6343    /// paint loop is not.
6344    #[test]
6345    fn a_source_shorter_than_the_arena_built_over_it_renders_rather_than_panicking() {
6346        // An escape puts the run on `push_escaped_text`'s slow path — the fast
6347        // path is a length comparison that a truncated source fails anyway.
6348        let src = "alpha \\*beta\\* gamma delta epsilon\n";
6349        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6350        let nodes = ed.nodes().unwrap();
6351
6352        // Every truncation of it, so the cut lands before, inside and after the
6353        // escaped run rather than only where one hand-picked index put it.
6354        for cut in 0..=src.len() {
6355            if !src.is_char_boundary(cut) {
6356                continue;
6357            }
6358            let map = build_t(&nodes, &src[..cut], Some(80));
6359            for row in &map.rows {
6360                for g in &row.glyphs {
6361                    assert!(
6362                        g.src <= src.len(),
6363                        "cut {cut}: glyph {:?} points past the source at {}",
6364                        g.ch,
6365                        g.src
6366                    );
6367                }
6368            }
6369        }
6370    }
6371
6372    fn rendered(m: &VisualMap) -> String {
6373        m.rows
6374            .iter()
6375            .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
6376            .collect::<Vec<_>>()
6377            .join("\n")
6378    }
6379
6380    /// Render a source both ways: `build` over the whole marshalled arena (the
6381    /// reference), and `build_cached` driven the way [`crate::Doc`] drives it —
6382    /// top-level blocks from `child_spans`, per-block subtrees on a miss.
6383    fn render_both(
6384        ed: &mut Editor,
6385        src: &str,
6386        wrap: Option<usize>,
6387        cache: &mut BlockCache,
6388    ) -> (VisualMap, VisualMap) {
6389        let all = ed.nodes().unwrap();
6390        let surface = Surface::default();
6391        let plain = build(&all, src, wrap, false, &surface, None);
6392        let top = top_blocks(ed);
6393        let cached = build_cached(&top, src, wrap, false, &surface, None, cache, |id| {
6394            ed.subtree(NodeId(id)).unwrap_or_default()
6395        });
6396        (plain, cached)
6397    }
6398
6399    /// The whole correctness claim of the block cache: `build_cached` produces a
6400    /// byte-identical map to `build`, on a fresh cache *and* — the case that
6401    /// actually exercises reuse-and-shift plus per-block subtree marshalling — on
6402    /// a warm cache after the source has been edited underneath it.
6403    /// **Every glyph must stand on the character it claims.** A row's source
6404    /// extent is computed from its last glyph's offset, so a glyph carrying an
6405    /// offset that is not its own character's start yields a row end inside a
6406    /// multi-byte character — and every later slice of the source panics on it.
6407    ///
6408    /// Reproduces a real crash from a journal entry: a bracketed elision inside
6409    /// a blockquote (`[…]`) gave the closing bracket a `text` of `"]"` over a
6410    /// source span covering `"…]"`, because the parse folded the ellipsis into a
6411    /// neighbouring node. `push_escaped_text` walked that span assuming a
6412    /// dropped backslash was the only way text and source could diverge, so the
6413    /// `]` landed on the `…`'s first byte:
6414    /// `byte index 1236 is not a char boundary; it is inside '…'`.
6415    #[test]
6416    fn a_glyph_never_lands_inside_the_character_before_it() {
6417        let src = "> engage with it rather than look away. […]\n>\n> The through-line\n";
6418        let vmap = map(src);
6419        for (r, row) in vmap.rows.iter().enumerate() {
6420            assert!(
6421                src.is_char_boundary(row.end_src.min(src.len())),
6422                "row {r} ends at {} — inside a character",
6423                row.end_src
6424            );
6425            for g in &row.glyphs {
6426                assert!(
6427                    src.is_char_boundary(g.src.min(src.len())),
6428                    "row {r} has {:?} at {}, which is inside a character",
6429                    g.ch,
6430                    g.src
6431                );
6432            }
6433        }
6434        // The elision survives, and its bracket sits on the real `]`.
6435        let text: String = vmap
6436            .rows
6437            .iter()
6438            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
6439            .collect();
6440        assert!(text.contains("[…]"), "the elision should render: {text:?}");
6441        let close = vmap
6442            .rows
6443            .iter()
6444            .flat_map(|r| r.glyphs.iter())
6445            .find(|g| g.ch == ']')
6446            .expect("a closing bracket");
6447        assert_eq!(
6448            src[close.src..].chars().next(),
6449            Some(']'),
6450            "the bracket glyph should stand on the source's own `]`"
6451        );
6452    }
6453
6454    #[test]
6455    fn build_cached_matches_build() {
6456        let docs = [
6457            "# Title\n\nThe quick brown fox.\n\nAnother paragraph here.\n",
6458            "## H\n\n- one\n- two\n- three\n\n> a quote\n> continued\n",
6459            "para one\n\n```\ncode\nlines\n```\n\nafter code\n",
6460            "| a | b |\n|---|---|\n| 1 | 2 |\n\ntext after a table\n",
6461            "line\n- \nsetext?\n\nreal para\n\n\n\ntrailing blanks\n",
6462            "> quote with **bold** and a [link](https://x.dev)\n>\n> - item\n> - item2\n\ntail\n",
6463            "intro\n\n![a cat](img/cat.png)\n\nbetween\n\n![](https://x.dev/logo.svg)\n\nend\n",
6464            "- text item\n- ![alt](pic.png)\n- more text\n",
6465            // Footnotes: twig parses each definition as a root beside `doc`, so
6466            // these are the docs where the reference build and the incremental
6467            // one could disagree about what the top-level blocks even are.
6468            "A claim[^1] and another[^src].\n\n[^1]: First note.\n\n[^src]: Second.\n\ntail\n",
6469            "note[^a]\n\n[^a]: body **bold**\n    wrapped on\n    three lines\n\nafter\n",
6470            // No trailing newline. twig closes the document's last block on the
6471            // virtual newline it supplies at EOF, so that block's `span.end` is
6472            // `source.len() + 1` — a range that slices no bytes at all. Keying
6473            // the block cache off such a slice made every last block hash alike;
6474            // see [`block_bytes`].
6475            "# Title\n\nThe quick brown fox.\n\nA tail with no newline",
6476            "A claim[^1] and another[^src].\n\n[^1]: First note.\n[^src]: Second, ending the file.",
6477            // Comments draw nothing. The per-block builder the cached path
6478            // renders one with starts at offset 0 and, drawing nothing, never
6479            // moved — so the walk went on from 0 and spelled every line of the
6480            // document as a blank row. One at the start, one between blocks,
6481            // one at the end, so each position is covered.
6482            "<!-- lead -->\n\npara\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n\n<!-- trail -->\n",
6483            // A Markdown `<div>` ends with a hidden `</div>` line the walk
6484            // steps over — between blocks and closing the file, so both the
6485            // separator after it and the trailing count are covered.
6486            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
6487            "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n",
6488            // Link reference definitions: roots beside `doc` like footnotes,
6489            // but drawing nothing. Alone between blocks, glued under a
6490            // paragraph, and closing the file under a comment — the README
6491            // shape.
6492            "see [a] and [b]\n\n[a]: /a\n\nmid\n[b]: /b \"bee\"\n\nend [c]\n\n<!-- links -->\n[c]: /c\n",
6493        ];
6494        for wrap in [None, Some(80usize), Some(20)] {
6495            for src in docs {
6496                let ctx = format!("wrap={wrap:?} src={src:?}");
6497                let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6498                let mut cache = BlockCache::default();
6499
6500                // 1) Fresh cache equals the cache-free build.
6501                let (plain, cached) = render_both(&mut ed, src, wrap, &mut cache);
6502                assert_maps_eq(&plain, &cached, &format!("fresh {ctx}"));
6503
6504                // 2) Type a char mid-document, reparse, rebuild with the now-warm
6505                //    cache: the edited block is re-marshalled and re-rendered,
6506                //    every block below it is reused shifted, and the result must
6507                //    still match a from-scratch build.
6508                let at = (src.len() / 2..=src.len())
6509                    .find(|&i| src.is_char_boundary(i))
6510                    .unwrap();
6511                ed.edit_range(at, at, "Z").unwrap();
6512                let src2 = ed.source_str().unwrap();
6513                let (plain2, cached2) = render_both(&mut ed, &src2, wrap, &mut cache);
6514                assert_maps_eq(&plain2, &cached2, &format!("after insert {ctx}"));
6515
6516                // 3) Delete it again: offsets shift back the other way, and the
6517                //    warm cache must not hand back stale shifted rows.
6518                ed.edit_range(at, at + 1, "").unwrap();
6519                let src3 = ed.source_str().unwrap();
6520                let (plain3, cached3) = render_both(&mut ed, &src3, wrap, &mut cache);
6521                assert_maps_eq(&plain3, &cached3, &format!("after delete {ctx}"));
6522            }
6523        }
6524    }
6525
6526    /// A document that does not end in a newline is the one place twig hands
6527    /// leaf a top-level span that addresses no source: the last block is closed
6528    /// on the virtual newline the parser supplies at EOF, so its `span.end` is
6529    /// `source.len() + 1`. The block cache keys on the bytes under that span, and
6530    /// reading the out-of-range slice as *no bytes* broke it two ways at once —
6531    /// [`block_bytes`] has the full account. Both ways are checked here, because
6532    /// they fail independently.
6533    #[test]
6534    fn a_block_running_past_the_last_byte_still_keys_the_cache_by_its_own_bytes() {
6535        // One: two overrunning blocks collide. A footnote definition is a root
6536        // beside `doc` that [`top_blocks`] merges into the top level, while the
6537        // `section` above it spans the definition's bytes too — so when the
6538        // definition ends the file, both blocks end past it. The second was
6539        // served the first's rows, and the definition rendered as a copy of the
6540        // heading.
6541        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.";
6542        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
6543        let (plain, cached) = render_both(&mut ed, src, Some(80), &mut BlockCache::default());
6544        assert_maps_eq(&plain, &cached, "a definition ending the file");
6545        let text = rendered(&cached);
6546        assert!(
6547            text.ends_with("[note] A note with a word for a label."),
6548            "the last definition should render itself: {text:?}"
6549        );
6550        assert_eq!(
6551            text.matches("A heading with a reference").count(),
6552            1,
6553            "the heading should render exactly once: {text:?}"
6554        );
6555
6556        // Two: one overrunning block goes stale. Its bytes are its cache key, so
6557        // a block that keeps hashing the same however it is edited is served the
6558        // rows built before the edit — the whole last line frozen as the user
6559        // types in it.
6560        let mut cache = BlockCache::default();
6561        let first = "first para\n\n# A heading\n\nlast para with no newline";
6562        let mut ed = Editor::new_str(first, Format::Djot).unwrap();
6563        let (_, warm) = render_both(&mut ed, first, Some(80), &mut cache);
6564        assert!(rendered(&warm).ends_with("last para with no newline"));
6565
6566        let second = "first para\n\n# A heading\n\nDIFFERENT text without a newline";
6567        let mut ed = Editor::new_str(second, Format::Djot).unwrap();
6568        let (plain, cached) = render_both(&mut ed, second, Some(80), &mut cache);
6569        assert_maps_eq(&plain, &cached, "edited last block, warm cache");
6570        let text = rendered(&cached);
6571        assert!(
6572            text.ends_with("DIFFERENT text without a newline"),
6573            "the warm cache served the pre-edit rows: {text:?}"
6574        );
6575    }
6576
6577    #[test]
6578    fn resolves_markup_to_plain_text() {
6579        let text = rendered(&map("# Title\n\na **bold** word\n"));
6580        assert!(!text.contains('#'), "heading marker shown: {text:?}");
6581        assert!(!text.contains("**"), "strong delimiters shown: {text:?}");
6582        assert!(text.contains("Title") && text.contains("bold word"));
6583    }
6584
6585    #[test]
6586    fn every_glyph_points_at_its_source_byte() {
6587        let src = "a **bold** c\n";
6588        let m = map(src);
6589        for row in &m.rows {
6590            for g in &row.glyphs {
6591                // A real (non-synthetic) glyph's source byte is the glyph's char.
6592                if g.src < src.len()
6593                    && src.is_char_boundary(g.src)
6594                    && let Some(sc) = src[g.src..].chars().next()
6595                    && sc == g.ch
6596                {
6597                    continue;
6598                }
6599                // Synthetic prefixes (none here) would be the only exceptions.
6600                panic!("glyph {:?} at src {} doesn't match source", g.ch, g.src);
6601            }
6602        }
6603    }
6604
6605    #[test]
6606    fn offset_and_position_round_trip_on_visible_text() {
6607        let m = map("hello world\n");
6608        let (r, c) = m.pos_of_offset(6); // the 'w'
6609        assert_eq!(m.offset_of_pos(r, c), 6);
6610    }
6611
6612    #[test]
6613    fn visible_utf16_indices_count_the_text_the_system_sees() {
6614        // Hidden delimiters, a two-unit emoji, and a block gap — every way the
6615        // visible text's UTF-16 length parts company with a source byte count.
6616        let src = "a **b\u{1F600}** c\n\nd\n";
6617        let m = map(src);
6618        let end = m.snap_to_stop(src.len());
6619        let text = m.visible_text(0, end);
6620        assert_eq!(text, "a b\u{1F600} c\nd");
6621
6622        // Forward: the index of each offset is where that character sits in
6623        // the visible string, in UTF-16 units.
6624        for (i, (src_off, _)) in m.visible_items(0, end).iter().enumerate() {
6625            let expect: usize = text.chars().take(i).map(char::len_utf16).sum();
6626            assert_eq!(
6627                m.visible_utf16_len(0, *src_off),
6628                expect,
6629                "utf16 index of source offset {src_off}"
6630            );
6631            // And back: the index resolves to the offset it came from.
6632            assert_eq!(m.offset_at_visible_utf16(end, expect), Some(*src_off));
6633        }
6634        // Inside the emoji's surrogate pair resolves to the emoji.
6635        let emoji_src = src.find('\u{1F600}').unwrap();
6636        let emoji_idx = m.visible_utf16_len(0, emoji_src);
6637        assert_eq!(
6638            m.offset_at_visible_utf16(end, emoji_idx + 1),
6639            Some(emoji_src)
6640        );
6641        // At or past the end is nobody's character.
6642        let total = m.visible_utf16_len(0, end);
6643        assert_eq!(total, text.encode_utf16().count());
6644        assert_eq!(m.offset_at_visible_utf16(end, total), None);
6645    }
6646
6647    /// The documents the lookups are checked against their reference scans
6648    /// on: every shape that puts rows out of source order or a stop out of
6649    /// step with a glyph. A wrapped table, whose cells' second lines sit
6650    /// below the next column's first; a wide grapheme and an emoji outside
6651    /// the BMP; hidden delimiters and a link's hidden destination; a list
6652    /// with synthetic markers; a code block; an image row whose label glyphs
6653    /// all share one offset; an empty paragraph, a heading, and a wrapped
6654    /// paragraph — at a narrow width so the table and the prose both wrap,
6655    /// and unwrapped, which is how a GUI builds it.
6656    fn lookup_maps() -> Vec<(String, VisualMap)> {
6657        let table = "| left cell that wraps | right |\n|---|---|\n| a longer cell than the column can hold | b |\n| `k` | 你好 |\n\n";
6658        let srcs = [
6659            "hello world\n",
6660            "a **b\u{1F600}** c\n\nd\n",
6661            "- one *two*\n- three\n\n\n# Title\n\nend [link](https://e.org/x) tail\n",
6662            &format!("{table}```\nx\ny\n```\n\n![alt](a.png)\n\ntail 你好 **bold** here\n"),
6663            "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",
6664        ];
6665        let mut out = Vec::new();
6666        for src in srcs {
6667            for wrap in [Some(14), None] {
6668                out.push((format!("{src:?} at {wrap:?}"), map_at(src, wrap)));
6669            }
6670        }
6671        out
6672    }
6673
6674    /// `pos_of_offset` as it was written before the walk learnt to dismiss a
6675    /// row from its ends: every row read through, the nearest stop kept.
6676    fn pos_of_offset_by_scan(m: &VisualMap, off: usize) -> (usize, usize) {
6677        let mut best: Option<(usize, usize, usize)> = None;
6678        for (r, row) in m.rows.iter().enumerate() {
6679            if row.decoration {
6680                continue;
6681            }
6682            let cand = row
6683                .glyphs
6684                .iter()
6685                .enumerate()
6686                .find(|(_, g)| g.stop && g.src >= off)
6687                .map(|(i, g)| (g.src, r, row.col_of_glyph(i)))
6688                .or_else(|| (row.end_src >= off).then_some((row.end_src, r, row.width())));
6689            if let Some(c) = cand
6690                && best.is_none_or(|b| c.0 <= b.0)
6691            {
6692                best = Some(c);
6693            }
6694        }
6695        match best {
6696            Some((_, r, c)) => (r, c),
6697            None => {
6698                let r = m.last_stop_row();
6699                (r, m.row_width(r))
6700            }
6701        }
6702    }
6703
6704    /// `visible_items` as it was written before the spelling was tabulated:
6705    /// every stop glyph in the range gathered, sorted, and paired up.
6706    fn visible_items_by_scan(m: &VisualMap, from: usize, to: usize) -> Vec<(usize, Option<char>)> {
6707        let (lo, hi) = m.visible_span(from, to);
6708        let from = m.snap_to_glyph_stop(from);
6709        let mut glyphs: Vec<(usize, char)> = m
6710            .rows
6711            .iter()
6712            .filter(|r| !r.decoration)
6713            .flat_map(|r| r.glyphs.iter())
6714            .filter(|g| g.stop && g.src >= from && g.src < to)
6715            .map(|g| (g.src, g.ch))
6716            .collect();
6717        glyphs.sort_by_key(|&(src, _)| src);
6718        glyphs.dedup_by_key(|&mut (src, _)| src);
6719        let cell_ends: Vec<usize> = m
6720            .tables
6721            .iter()
6722            .flat_map(|t| t.grid.iter())
6723            .flat_map(|r| r.cells.iter())
6724            .map(|c| c.end)
6725            .collect();
6726        m.stops[lo..hi]
6727            .iter()
6728            .map(|&s| {
6729                let ch = glyphs
6730                    .iter()
6731                    .find(|&&(src, _)| src == s)
6732                    .filter(|_| !cell_ends.contains(&s))
6733                    .map(|&(_, ch)| ch);
6734                (s, ch)
6735            })
6736            .collect()
6737    }
6738
6739    #[test]
6740    fn pos_of_offset_agrees_with_reading_every_row_through() {
6741        for (name, m) in lookup_maps() {
6742            let len = m.rows.iter().map(|r| r.end_src).max().unwrap_or(0) + 2;
6743            for off in 0..=len {
6744                assert_eq!(
6745                    m.pos_of_offset(off),
6746                    pos_of_offset_by_scan(&m, off),
6747                    "offset {off} of {name}"
6748                );
6749            }
6750        }
6751    }
6752
6753    #[test]
6754    fn the_tabulated_spelling_agrees_with_gathering_the_glyphs() {
6755        for (name, m) in lookup_maps() {
6756            let end = m.stops.last().copied().unwrap_or(0);
6757            // Whole text, and every window a frontend might ask for.
6758            let mut spans = vec![(0, end)];
6759            for &a in m.stops.iter().step_by(3) {
6760                spans.push((a, end));
6761                spans.push((0, a));
6762                spans.push((a, (a + 5).min(end)));
6763            }
6764            for (from, to) in spans {
6765                let items = visible_items_by_scan(&m, from, to);
6766                assert_eq!(
6767                    m.visible_items(from, to),
6768                    items,
6769                    "items {from}..{to} of {name}"
6770                );
6771                let utf16: usize = items
6772                    .iter()
6773                    .map(|(_, ch)| ch.map_or(1, char::len_utf16))
6774                    .sum();
6775                assert_eq!(
6776                    m.visible_utf16_len(from, to),
6777                    utf16,
6778                    "utf16 {from}..{to} of {name}"
6779                );
6780            }
6781            // And back: every UTF-16 index in the text resolves to the stop
6782            // that spells it, as the scan would have found it.
6783            let items = visible_items_by_scan(&m, 0, end);
6784            let mut seen = 0;
6785            for (src, ch) in &items {
6786                for u in seen..seen + ch.map_or(1, char::len_utf16) {
6787                    assert_eq!(
6788                        m.offset_at_visible_utf16(end, u),
6789                        Some(*src),
6790                        "index {u} of {name}"
6791                    );
6792                }
6793                seen += ch.map_or(1, char::len_utf16);
6794            }
6795            assert_eq!(
6796                m.offset_at_visible_utf16(end, seen),
6797                None,
6798                "past the end of {name}"
6799            );
6800        }
6801    }
6802
6803    #[test]
6804    fn visible_text_spends_exactly_one_character_on_every_stop() {
6805        // A list (whose items' ends no gap row follows), a table (whose cells'
6806        // ends draw a gutter space), and a code block (one row per line):
6807        // every place the text used to part company with the stop count, in
6808        // both directions. `UITextInput`'s tokenizer indexes this text by
6809        // that count, so the two must agree exactly between any two stops.
6810        let src = "- one\n- two\n\n| a | b |\n| - | - |\n| c | d |\n\n```\nx\ny\n```\n\nend\n";
6811        let m = map(src);
6812        let end = m.snap_to_stop(src.len());
6813        // The table's trailing stop draws no glyph, so it is spelled as a line
6814        // end too: to the system the table ends on a blank line, which is
6815        // where the caret past it stands.
6816        assert_eq!(m.visible_text(0, end), "one\ntwo\na\nb\nc\nd\n\nx\ny\nend");
6817        // Between any two stops, one character per hop.
6818        let first = m.snap_to_glyph_stop(0);
6819        let stops: Vec<usize> = std::iter::successors(Some(first), |&o| m.stop_after(o)).collect();
6820        for (i, &a) in stops.iter().enumerate() {
6821            for (j, &b) in stops.iter().enumerate().skip(i) {
6822                assert_eq!(
6823                    m.visible_text(a, b).chars().count(),
6824                    j - i,
6825                    "text between stops {a} and {b}"
6826                );
6827            }
6828        }
6829        // A cell's end is spelled as a line end, not the space it draws, so a
6830        // tap landing past `a`'s last letter has nothing to step over into `b`.
6831        let a_end = src.find("a |").unwrap() + 1;
6832        assert_eq!(m.visible_text(a_end, a_end + 1), "\n");
6833    }
6834
6835    #[test]
6836    fn unwrapped_mode_emits_one_row_per_paragraph() {
6837        // A long paragraph that would wrap under a column budget stays a single
6838        // row when wrap is None (the GUI wraps it at pixel width instead).
6839        let long = "one two three four five six seven eight nine ten eleven twelve\n";
6840        let mut ed = Editor::new_str(long, Format::Markdown).unwrap();
6841        let wrapped = build_t(&ed.nodes().unwrap(), long, Some(12));
6842        let unwrapped = build_t(&ed.nodes().unwrap(), long, None);
6843        assert!(wrapped.num_rows() > 1, "narrow column should wrap");
6844        assert_eq!(unwrapped.num_rows(), 1, "no budget should keep it one row");
6845        // Every glyph's source byte is preserved in the single row.
6846        let text: String = unwrapped.rows[0].glyphs.iter().map(|g| g.ch).collect();
6847        assert_eq!(text.trim_end(), long.trim_end());
6848    }
6849
6850    fn line_texts(m: &VisualMap) -> Vec<String> {
6851        m.rows
6852            .iter()
6853            .map(|r| {
6854                // Trim the trailing whitespace a row may carry — the zero-width
6855                // '\n' that closes a preserved line, and any space glyph left at
6856                // a wrap boundary (both real caret stops, neither visible text).
6857                r.glyphs
6858                    .iter()
6859                    .map(|g| g.ch)
6860                    .collect::<String>()
6861                    .trim_end()
6862                    .to_string()
6863            })
6864            .collect()
6865    }
6866
6867    #[test]
6868    fn preserve_lays_each_soft_break_on_its_own_row() {
6869        // A soft break (a bare newline inside a paragraph) folds into a space by
6870        // default — the whole paragraph is one reflowed row...
6871        let src = "one two\nthree four\n";
6872        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6873        let folded = build_t(&ed.nodes().unwrap(), src, None);
6874        assert_eq!(folded.num_rows(), 1, "fold: one reflowed row");
6875        assert_eq!(
6876            line_texts(&folded),
6877            vec!["one two three four"],
6878            "break folded to a space"
6879        );
6880
6881        // ...and under Preserve it renders where it was written, a row per line.
6882        let kept = map_preserve(src, None);
6883        assert_eq!(
6884            line_texts(&kept),
6885            vec!["one two", "three four"],
6886            "preserve: a row per line"
6887        );
6888    }
6889
6890    #[test]
6891    fn a_preserved_break_keeps_the_newline_offset_as_a_caret_stop() {
6892        // The break must leave a caret stop at the newline byte, or the caret
6893        // could not rest at the end of the first line. The '\n' glyph is dropped
6894        // from the row (so nothing stray renders); its offset (7 here) becomes the
6895        // row's end stop instead — the same offset the folded space would carry.
6896        let src = "one two\nthree four\n";
6897        let m = map_preserve(src, None);
6898        assert!(
6899            !m.rows[0].glyphs.iter().any(|g| g.ch == '\n'),
6900            "the break glyph is dropped"
6901        );
6902        assert_eq!(
6903            m.rows[0].end_src, 7,
6904            "the first row ends at the newline byte"
6905        );
6906        assert!(m.is_stop(7), "the newline offset is a caret stop");
6907        // Row end offsets stay strictly ascending — no two rows pin one offset.
6908        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
6909        assert!(
6910            offs.windows(2).all(|w| w[0] < w[1]),
6911            "offsets not unique: {offs:?}"
6912        );
6913    }
6914
6915    #[test]
6916    fn preserved_lines_wrap_independently() {
6917        // Each preserved line wraps to the column on its own; the break between
6918        // them is hard, so a word never crosses it — "gamma" and "delta" could
6919        // share a row on width alone but the soft break keeps them apart.
6920        let src = "alpha beta gamma\ndelta epsilon\n";
6921        let m = map_preserve(src, Some(12));
6922        assert_eq!(
6923            line_texts(&m),
6924            vec!["alpha beta", "gamma", "delta", "epsilon"],
6925            "each source line wraps on its own"
6926        );
6927    }
6928
6929    #[test]
6930    fn an_empty_paragraph_between_blocks_renders_its_own_rows() {
6931        // "A", then two blank lines (an empty paragraph opened with Enter), then
6932        // "B": the empty paragraph must be navigable rows, not collapsed onto B.
6933        // Rows: "A", spacer, empty-paragraph, spacer, "B" — each blank row a
6934        // distinct source offset.
6935        let m = map("A\n\n\n\nB\n");
6936        let text: Vec<String> = m
6937            .rows
6938            .iter()
6939            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6940            .collect();
6941        assert_eq!(text, vec!["A", "", "", "", "B"], "got {text:?}");
6942        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
6943        // Strictly ascending — no two rows share an offset (else the caret pins).
6944        assert!(
6945            offs.windows(2).all(|w| w[0] < w[1]),
6946            "offsets not unique: {offs:?}"
6947        );
6948    }
6949
6950    #[test]
6951    fn a_tight_block_boundary_still_gets_one_separator() {
6952        // A heading directly above text (no blank line between) keeps the single
6953        // conventional separator row, as before.
6954        let m = map("# H\ntext\n");
6955        let text: Vec<String> = m
6956            .rows
6957            .iter()
6958            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6959            .collect();
6960        assert_eq!(text, vec!["H", "", "text"], "got {text:?}");
6961    }
6962
6963    #[test]
6964    fn an_escaped_delimiter_renders_without_its_backslash_and_maps_true_offsets() {
6965        // `a\*b` renders the three visible chars `a * b` — the escape backslash
6966        // is hidden — and every glyph points at its real source byte, so a caret
6967        // past the escape lands right (the `*` at source 2, `b` at source 3, not
6968        // the drifted 1/2 the naive text-offset mapping gave).
6969        let m = map("a\\*b\n");
6970        let row: Vec<(char, usize)> = m.rows[0].glyphs.iter().map(|g| (g.ch, g.src)).collect();
6971        assert_eq!(row, vec![('a', 0), ('*', 2), ('b', 3)], "got {row:?}");
6972    }
6973
6974    #[test]
6975    fn an_escaped_hash_stays_a_paragraph_and_shows_the_hash() {
6976        // `\# hi` is a paragraph beginning with a literal `#`, not a heading —
6977        // the backslash is hidden, the `#` shown at its true offset.
6978        let m = map("\\# hi\n");
6979        let text: String = m.rows[0].glyphs.iter().map(|g| g.ch).collect();
6980        assert_eq!(text, "# hi");
6981        assert_eq!(
6982            m.rows[0].glyphs[0].src, 1,
6983            "the # is at source byte 1, past the \\"
6984        );
6985    }
6986
6987    #[test]
6988    fn a_tight_nested_list_hangs_its_sublist_directly_under_the_item() {
6989        // A list item's own text and the sub-list nested under it are written on
6990        // adjacent source lines, so the rich view butts them together — no
6991        // fabricated blank row. Regression: the synthetic "breathe" separator
6992        // used to open a gap between `• a` and its `  • b`.
6993        assert_eq!(rendered(&map("- a\n  - b\n")), "• a\n  • b");
6994    }
6995
6996    #[test]
6997    fn a_loose_nested_list_keeps_its_real_blank_line() {
6998        // A genuine blank source line (a loose list) still parts the item from
6999        // its sub-list — only the *fabricated* separator is suppressed, never a
7000        // real one the author typed. The gap row wears the item's continuation
7001        // prefix (the two-space indent), so it renders as "  ", not empty.
7002        assert_eq!(rendered(&map("- a\n\n  - b\n")), "• a\n  \n  • b");
7003    }
7004
7005    #[test]
7006    fn frontmatter_is_hidden_and_the_document_opens_into_its_content() {
7007        // Leading YAML frontmatter renders nothing — no phantom blank rows for
7008        // its lines, no leading gap — and `content_start` points at the first
7009        // real block so the caret floor can keep out of the hidden metadata.
7010        let fm = "---\nconfig: prov.yaml\ncontents:\n- '[Sample](sample.md)'\n---\n";
7011        let src = format!("{fm}# leaf\n\nA line.\n");
7012        let m = map(&src);
7013        let text = rendered(&m);
7014        assert!(
7015            !text.contains("config"),
7016            "frontmatter body leaked: {text:?}"
7017        );
7018        assert!(!text.contains("prov"), "frontmatter body leaked: {text:?}");
7019        assert_eq!(
7020            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7021            "leaf"
7022        );
7023        assert_eq!(
7024            m.content_start,
7025            fm.len(),
7026            "floor should be the first real block"
7027        );
7028    }
7029
7030    #[test]
7031    fn a_frontmatter_only_document_puts_the_floor_after_the_frontmatter() {
7032        // Nothing to render, so the caret floor is the end of the hidden
7033        // frontmatter — not 0, which is *before* the opening `---` and made the
7034        // first keystroke in a fresh metadata-only note land ahead of it. And
7035        // the frontmatter's own newlines are not trailing blank lines: they used
7036        // to open phantom rows at offsets 1..4, inside the metadata.
7037        let src = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
7038        let m = map(src);
7039        assert_eq!(m.content_start, src.len(), "floor must clear the metadata");
7040        assert!(
7041            m.rows.is_empty(),
7042            "frontmatter must render no rows: {:?}",
7043            rendered(&m)
7044        );
7045        assert!(
7046            m.stops.is_empty(),
7047            "no stop may sit inside the metadata: {:?}",
7048            m.stops
7049        );
7050    }
7051
7052    #[test]
7053    fn a_frontmatter_only_document_still_counts_its_real_blank_lines() {
7054        // Two blank lines after the frontmatter are the author's empty paragraph
7055        // and still render, counted from the metadata's end rather than from 0.
7056        let fm = "---\ntitle: n\n---\n";
7057        let m = map(&format!("{fm}\n\n"));
7058        assert_eq!(m.content_start, fm.len());
7059        assert_eq!(m.rows.len(), 2, "the two trailing newlines each open a row");
7060        assert!(
7061            m.rows.iter().all(|r| r.end_src > fm.len()),
7062            "rows must sit past the frontmatter"
7063        );
7064    }
7065
7066    #[test]
7067    fn a_document_without_frontmatter_has_a_zero_floor() {
7068        let m = map("# leaf\n\nbody\n");
7069        assert_eq!(m.content_start, 0);
7070    }
7071
7072    #[test]
7073    fn trailing_spaces_become_caret_stops_so_the_caret_can_be_drawn_past_them() {
7074        // Markdown/Djot drop the trailing space in `hello ` from the `str` node,
7075        // so without help the row would end at `hello` and the caret couldn't be
7076        // drawn past column 5 — typing a space at a line's end wouldn't move it
7077        // on screen until the next visible character reparsed the space into an
7078        // interior node. The builder recovers it from the block's span/content_span
7079        // gap and emits it as a real, caret-stoppable glyph.
7080        let m = map("hello \n");
7081        assert_eq!(
7082            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7083            "hello "
7084        );
7085        assert_eq!(
7086            m.rows[0].end_src, 6,
7087            "the row now ends past the trailing space"
7088        );
7089        // The caret can rest both on and past the space.
7090        assert_eq!(m.pos_of_offset(5), (0, 5), "between 'o' and the space");
7091        assert_eq!(m.pos_of_offset(6), (0, 6), "past the space");
7092        // Two trailing spaces, both stops.
7093        let m = map("hello  \n");
7094        assert_eq!(
7095            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7096            "hello  "
7097        );
7098        assert_eq!(m.pos_of_offset(7), (0, 7));
7099    }
7100
7101    #[test]
7102    fn a_headings_trailing_space_is_a_caret_stop_too() {
7103        // The hidden `# ` marker means `# hi ` renders as `hi ` in three columns;
7104        // the caret past the trailing space lands on the third.
7105        let m = map("# hi \n");
7106        assert_eq!(
7107            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7108            "hi "
7109        );
7110        assert_eq!(m.pos_of_offset(5), (0, 3));
7111    }
7112
7113    #[test]
7114    fn a_table_cells_trailing_padding_is_not_mistaken_for_block_trailing_space() {
7115        // A cell's own `span` is the whole row, so the trailing-whitespace
7116        // recovery must not run for cells or it would swallow the `│` delimiters
7117        // and neighbours between the cell text and the row's end. The grid stays
7118        // exactly as before.
7119        let text = rendered(&map(TABLE));
7120        assert!(
7121            text.contains("│ Pear │   3 │"),
7122            "cell padding disturbed:\n{text}"
7123        );
7124    }
7125
7126    #[test]
7127    fn a_click_below_the_last_row_lands_on_the_last_stop_not_offset_zero() {
7128        // A drag into the empty space under a short document used to resolve to
7129        // offset 0 — the wrong direction, and not even a caret stop when the
7130        // document opens on hidden frontmatter (its `content_start` floor is not
7131        // a stop), which crashed the caret invariant. It now lands on the last
7132        // stop: the end of the document, where dragging downward should reach.
7133        let fm = "---\ntitle: n\n---\n";
7134        let m = map(&format!("{fm}# Hi\n\nbody\n"));
7135        let below = m.num_rows() + 5;
7136        let off = m.offset_of_pos(below, 0);
7137        assert!(
7138            m.is_stop(off),
7139            "offset {off} from a below-content click is not a stop"
7140        );
7141        assert_eq!(
7142            off,
7143            m.stops.last().copied().unwrap(),
7144            "should be the document's last stop"
7145        );
7146        assert!(
7147            off > fm.len(),
7148            "must not fall onto the hidden frontmatter floor"
7149        );
7150    }
7151
7152    #[test]
7153    fn offset_of_pos_is_a_stop_for_every_row_including_past_the_end() {
7154        // The invariant the caret motion asserts: whatever cell a click names,
7155        // the offset it resolves to is one the caret can actually rest at.
7156        for src in [
7157            "hello \n",
7158            "# A heading here \n\nbody text goes on \n",
7159            "---\nk: v\n---\n# Title\n\nprose here that wraps a bit \n",
7160        ] {
7161            let m = map(src);
7162            for row in 0..m.num_rows() + 3 {
7163                for col in 0..30 {
7164                    let off = m.offset_of_pos(row, col);
7165                    assert!(
7166                        m.is_stop(off),
7167                        "row {row} col {col} → {off} is not a stop in {src:?}"
7168                    );
7169                }
7170            }
7171        }
7172    }
7173
7174    /// `| Name | Qty |` with Name left-aligned and Qty right-aligned.
7175    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
7176
7177    #[test]
7178    fn a_table_renders_as_an_aligned_grid() {
7179        let text = rendered(&map(TABLE));
7180        assert_eq!(
7181            text,
7182            "┌──────┬─────┐\n\
7183             │ Name │ Qty │\n\
7184             ├──────┼─────┤\n\
7185             │ Pear │   3 │\n\
7186             │ Fig  │  12 │\n\
7187             └──────┴─────┘",
7188            "got:\n{text}"
7189        );
7190    }
7191
7192    #[test]
7193    fn table_columns_honour_their_alignment() {
7194        // Centre and default(left) come straight from twig's cell.alignment —
7195        // the delimiter row it's spelled in is consumed and has no node.
7196        let text = rendered(&map("| A | Bee |\n| --- | :---: |\n| x | y |\n"));
7197        assert!(text.contains("│ x │  y  │"), "centred column: {text:?}");
7198    }
7199
7200    #[test]
7201    fn table_borders_are_decoration_the_caret_never_lands_on() {
7202        let m = map(TABLE);
7203        // The top and header rules are whole decoration rows.
7204        for r in [0, 2] {
7205            assert!(m.rows[r].decoration, "row {r} should be a decoration rule");
7206            assert!(
7207                !m.rows[r].glyphs.iter().any(|g| g.stop),
7208                "row {r} has a stop"
7209            );
7210        }
7211        // The bottom border is the exception: no glyph of it is a stop, but
7212        // its end is the table's trailing caret home — the one place the caret
7213        // can stand past the last cell.
7214        let bottom = &m.rows[5];
7215        assert!(
7216            !bottom.decoration,
7217            "the bottom border holds the trailing stop"
7218        );
7219        assert!(
7220            !bottom.glyphs.iter().any(|g| g.stop),
7221            "the bottom border's glyphs are not stops"
7222        );
7223        assert!(m.is_stop(bottom.end_src), "the trailing stop is a stop");
7224        assert!(m.table_end_stop(bottom.end_src));
7225        assert_eq!(
7226            bottom.end_src,
7227            TABLE.trim_end_matches('\n').len(),
7228            "the trailing stop is the table's own end, before its newline"
7229        );
7230        assert!(
7231            !m.table_end_stop(TABLE.rfind("12").unwrap() + 2),
7232            "a cell's end is not the trailing stop"
7233        );
7234        // A content row's `│` and padding are decoration; only the cell text
7235        // and each cell's one end-stop are stops.
7236        let header = &m.rows[1];
7237        assert!(!header.decoration);
7238        for g in &header.glyphs {
7239            if g.ch == '│' {
7240                assert!(!g.stop, "a border is not a caret stop");
7241            }
7242        }
7243        let stops: String = header
7244            .glyphs
7245            .iter()
7246            .filter(|g| g.stop)
7247            .map(|g| g.ch)
7248            .collect();
7249        assert_eq!(stops, "Name Qty ", "cell text plus one end-stop space each");
7250    }
7251
7252    #[test]
7253    fn a_cell_maps_to_its_own_source_text() {
7254        let m = map(TABLE);
7255        // "Pear" starts at byte 32 in TABLE; the caret there draws on the 'P'.
7256        let pear = TABLE.find("Pear").unwrap();
7257        let (r, c) = m.pos_of_offset(pear);
7258        assert_eq!(m.rows[r].glyphs[c].ch, 'P');
7259        assert_eq!(m.offset_of_pos(r, c), pear, "round trips");
7260    }
7261
7262    #[test]
7263    fn a_wide_table_is_cut_to_fit_and_its_cells_wrap() {
7264        // Columns wider than the surface used to run off the right edge, where
7265        // nothing could reach them. They're cut to the budget instead, and the
7266        // text wraps down inside the column — the header rule stays put, and
7267        // an alignment holds on every line of a wrapped cell, not just the first.
7268        let src = "| Ingredient | Notes |\n|---|---:|\n\
7269                   | flour milled coarse | sift it twice |\n| salt | a pinch |\n";
7270        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7271        let m = build_t(&ed.nodes().unwrap(), src, Some(30));
7272        let text = rendered(&m);
7273        assert_eq!(
7274            text,
7275            "┌──────────────┬─────────────┐\n\
7276             │ Ingredient   │       Notes │\n\
7277             ├──────────────┼─────────────┤\n\
7278             │ flour milled │     sift it │\n\
7279             │ coarse       │       twice │\n\
7280             │ salt         │     a pinch │\n\
7281             └──────────────┴─────────────┘",
7282            "got:\n{text}"
7283        );
7284        for (r, row) in m.rows.iter().enumerate() {
7285            assert!(
7286                row.glyphs.len() <= 30,
7287                "row {r} overflows: {}",
7288                row.glyphs.len()
7289            );
7290        }
7291    }
7292
7293    #[test]
7294    fn a_column_too_narrow_for_a_word_breaks_it_rather_than_spilling() {
7295        // A paragraph lets an overlong word trail off the end of the line; a
7296        // table column can't — a glyph past the border lands on the border.
7297        let src = "| A | B |\n|---|---|\n| antidisestablishmentarianism | x |\n";
7298        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7299        let m = build_t(&ed.nodes().unwrap(), src, Some(20));
7300        for (r, row) in m.rows.iter().enumerate() {
7301            assert!(
7302                row.glyphs.len() <= 20,
7303                "row {r} overflows: {}",
7304                row.glyphs.len()
7305            );
7306        }
7307        // Broken across lines, but whole: every letter is still drawn, at its
7308        // own source byte, where the caret can reach it.
7309        let word = "antidisestablishmentarianism";
7310        let at = src.find(word).unwrap();
7311        for (i, ch) in word.char_indices() {
7312            assert!(
7313                m.rows
7314                    .iter()
7315                    .flat_map(|r| r.glyphs.iter())
7316                    .any(|g| g.stop && g.src == at + i && g.ch == ch),
7317                "{ch:?} at {} was lost to the break",
7318                at + i
7319            );
7320        }
7321    }
7322
7323    #[test]
7324    fn a_code_block_maps_each_line_to_its_own_source_text() {
7325        // Every glyph used to point at the block's start, which made the whole
7326        // block one offset — visible, but impossible to put a caret inside.
7327        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
7328        let m = map(src);
7329        for row in &m.rows {
7330            for g in row.glyphs.iter().filter(|g| g.stop) {
7331                assert_eq!(
7332                    src[g.src..].chars().next(),
7333                    Some(g.ch),
7334                    "glyph {:?} at {} isn't the source byte it claims",
7335                    g.ch,
7336                    g.src
7337                );
7338            }
7339        }
7340    }
7341
7342    #[test]
7343    fn an_indented_code_block_maps_past_its_stripped_indent() {
7344        // twig strips the four-space indent, so `text` isn't a source slice and
7345        // the lines have to be re-found. Offsets land on the code, not the indent.
7346        let src = "    indented\n    code\n";
7347        let m = map(src);
7348        let stops: Vec<(char, usize)> = m
7349            .rows
7350            .iter()
7351            .flat_map(|r| r.glyphs.iter().filter(|g| g.stop).map(|g| (g.ch, g.src)))
7352            .collect();
7353        assert_eq!(
7354            stops[0],
7355            ('i', 4),
7356            "first line should start past the indent"
7357        );
7358        assert!(
7359            stops.contains(&('c', 17)),
7360            "second line misplaced: {stops:?}"
7361        );
7362    }
7363
7364    #[test]
7365    fn a_fenced_block_whose_code_echoes_its_info_string_maps_to_the_code() {
7366        // The one case that defeats a forward search: the opening fence
7367        // ```` ```rust ```` ends with the same text as the code under it.
7368        let src = "```rust\nrust\n```\n";
7369        let m = map(src);
7370        let first = m.rows[0].glyphs.iter().find(|g| g.stop).unwrap();
7371        assert_eq!(first.src, 8, "matched the info string, not the code");
7372    }
7373
7374    #[test]
7375    fn a_code_block_carries_no_gutter_and_is_published_as_a_row_span() {
7376        // The old `▏ ` gutter is gone: a code row is the block prefix (none, at
7377        // the top level) plus the code text, and the whole run is named in
7378        // `code_blocks` so a frontend can box it.
7379        let src = "para\n\n```\ncode\nlines\n```\n\nafter\n";
7380        let m = map(src);
7381        assert_eq!(m.code_blocks.len(), 1, "one code block");
7382        let span = m.code_blocks[0].rows_span.clone();
7383        let rows: Vec<String> = m.rows[span.clone()]
7384            .iter()
7385            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7386            .collect();
7387        assert_eq!(rows, vec!["code".to_string(), "lines".to_string()]);
7388        assert!(!rendered(&m).contains('▏'), "gutter still drawn");
7389        assert!(
7390            m.rows[span].iter().all(|r| r.code),
7391            "every row in the span is flagged code"
7392        );
7393    }
7394
7395    #[test]
7396    fn an_empty_last_line_in_a_code_block_is_a_row_of_its_own() {
7397        // `trim_end_matches('\n')` cut the block's terminator *and* the newline
7398        // that spells a trailing empty line, so the row the Return had just made
7399        // never appeared and the caret on it fell through to the block below.
7400        // Every empty line is a row, wherever in the block it falls.
7401        let src = "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n";
7402        let m = map(src);
7403        let span = m.code_blocks[0].rows_span.clone();
7404        let rows: Vec<String> = m.rows[span.clone()]
7405            .iter()
7406            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7407            .collect();
7408        assert_eq!(
7409            rows,
7410            vec!["alpha".to_string(), "beta".to_string(), String::new()],
7411            "the empty last line gets a row"
7412        );
7413        assert!(
7414            m.rows[span.clone()].iter().all(|r| r.code),
7415            "the empty row is flagged code like the rest of the block"
7416        );
7417        // And it is the *source's* empty line, not a coarse fallback to the
7418        // block start: the offset the caret resolves to is the one Return made.
7419        let empty = span.end - 1;
7420        assert_eq!(
7421            m.rows[empty].end_src,
7422            src.find("beta\n\n").unwrap() + "beta\n".len(),
7423            "the empty row maps to the line the Return opened"
7424        );
7425
7426        // Nothing is invented where there is no empty line, and a second one is
7427        // a second row.
7428        assert_eq!(
7429            map("```\nalpha\nbeta\n```\n").code_blocks[0]
7430                .rows_span
7431                .len(),
7432            2,
7433            "a block that ends at its last code line keeps two rows"
7434        );
7435        assert_eq!(
7436            map("```\nalpha\n\n\n```\n").code_blocks[0].rows_span.len(),
7437            3,
7438            "two trailing empty lines are two rows"
7439        );
7440    }
7441
7442    #[test]
7443    fn a_directive_container_is_tinted_and_labeled_on_its_first_row() {
7444        // diaryx's `:::vis{.public .family}` visibility block, and any other
7445        // `:::name{.class}` fenced div — core is agnostic of `name`.
7446        let src = ":::vis{.public .family}\nhello\n\nworld\n:::\nafter\n";
7447        let m = map_directives(src);
7448
7449        let content_rows: Vec<usize> = (0..m.rows.len()).filter(|&i| m.rows[i].directive).collect();
7450        assert!(!content_rows.is_empty(), "some row is flagged directive");
7451
7452        let after_rows: Vec<usize> = (0..m.rows.len())
7453            .filter(|&i| !content_rows.contains(&i) && !m.rows[i].glyphs.is_empty())
7454            .collect();
7455        assert!(
7456            after_rows.iter().all(|&i| !m.rows[i].directive),
7457            "content outside the fence isn't tinted"
7458        );
7459
7460        let labels: Vec<&str> = content_rows
7461            .iter()
7462            .filter_map(|&i| m.rows[i].directive_label.as_deref())
7463            .collect();
7464        assert_eq!(
7465            labels,
7466            vec!["public family"],
7467            "only the first row carries the label"
7468        );
7469
7470        assert_eq!(
7471            rendered(&m)
7472                .lines()
7473                .filter(|l| !l.is_empty())
7474                .collect::<Vec<_>>(),
7475            vec!["hello", "world", "after"],
7476            "fence markers don't leak into the rendered text"
7477        );
7478    }
7479
7480    #[test]
7481    fn a_bare_word_directive_is_labeled_same_as_dot_classes() {
7482        // diaryx_core::visibility's own `:::vis{public family}` — no leading
7483        // dots — is what apps/web's directive serializer and the native
7484        // publish-time filter both actually write today, distinct from twig's
7485        // `.class` convention. Both must label the same way so every existing
7486        // diaryx `:::vis{...}` block reads, not just newly dot-authored ones.
7487        let src = ":::vis{public family}\nhello\n:::\n";
7488        let m = map_directives(src);
7489        let label = m.rows.iter().find_map(|r| r.directive_label.clone());
7490        assert_eq!(label.as_deref(), Some("public family"));
7491    }
7492
7493    #[test]
7494    fn a_text_directive_keeps_its_paragraph_visible() {
7495        // Regression: an inline `:name[label]{…}` used to make its paragraph
7496        // fail the "all children inline" test, so the whole line was walked as
7497        // a container of blocks and rendered as empty rows with NO caret stops —
7498        // the text vanished from the editor and the caret couldn't enter it.
7499        // diaryx's inline `:vis[…]` is exactly this shape.
7500        let src = "Text with :abbr[HTML]{title=\"HyperText\"} inline.\n";
7501        let m = map_directives(src);
7502        assert_eq!(rendered(&m).trim_end(), "Text with HTML inline.");
7503        // Every character of the line is a caret home, markup excluded — the
7504        // label reads as ordinary text, the way a link's does.
7505        let stops: usize = m
7506            .rows
7507            .iter()
7508            .map(|r| r.glyphs.iter().filter(|g| g.stop).count())
7509            .sum();
7510        assert_eq!(stops, "Text with HTML inline.".chars().count());
7511        // It is inline, so it is not the container form's tinted panel.
7512        assert!(m.rows.iter().all(|r| !r.directive));
7513    }
7514
7515    #[test]
7516    fn a_text_directives_label_maps_to_its_true_source_bytes() {
7517        // Regression (needs twig-doc >= 2.5.0): twig parses a `[label]` as a
7518        // detached slice, and until it rebased the enclosing scan's segments
7519        // onto it every node inside the label reported a span of `(0,0)`. Read
7520        // by anything that trusts a span that means "byte 0", so the label's
7521        // glyphs mapped to the START OF THE DOCUMENT — a click on the label put
7522        // the caret at the top of the file, its stops collided with the real
7523        // first line's, and an edit there landed on the wrong bytes entirely.
7524        //
7525        // The sibling test `a_text_directive_keeps_its_paragraph_visible` only
7526        // counts stops, which is exactly why this went unnoticed: the right
7527        // NUMBER of stops at completely wrong offsets.
7528        let src = "x :abbr[HTML]{title=\"y\"} z\n";
7529        let m = map_directives(src);
7530        let stops: Vec<(char, usize)> = m
7531            .rows
7532            .iter()
7533            .flat_map(|r| &r.glyphs)
7534            .filter(|g| g.stop)
7535            .map(|g| (g.ch, g.src))
7536            .collect();
7537        // `HTML` sits at 8..12. The name, brackets and `{…}` are hidden markup
7538        // the caret steps over, so the line's stops run 0, 1, 8..12, then 24.
7539        assert_eq!(
7540            stops,
7541            [
7542                ('x', 0),
7543                (' ', 1),
7544                ('H', 8),
7545                ('T', 9),
7546                ('M', 10),
7547                ('L', 11),
7548                (' ', 24),
7549                ('z', 25)
7550            ]
7551        );
7552    }
7553
7554    #[test]
7555    fn every_glyph_in_a_directive_label_points_at_its_source_byte() {
7556        // The `every_glyph_points_at_its_source_byte` invariant, extended over
7557        // directive labels now that their offsets are real. Nested markup is
7558        // included: its delimiters are hidden, so the visible glyphs must skip
7559        // them and still name their own bytes.
7560        let src = "x :abbr[a *b* c] y and :vis[family only] z\n";
7561        let m = map_directives(src);
7562        for g in m.rows.iter().flat_map(|r| &r.glyphs).filter(|g| g.stop) {
7563            let at = src[g.src..].chars().next();
7564            assert_eq!(
7565                at,
7566                Some(g.ch),
7567                "glyph {:?} claims byte {}, which is {at:?}",
7568                g.ch,
7569                g.src
7570            );
7571        }
7572        assert_eq!(rendered(&m).trim_end(), "x a b c y and family only z");
7573    }
7574
7575    #[test]
7576    fn a_directive_labels_nested_emphasis_keeps_both_its_style_and_its_offsets() {
7577        let src = "x :abbr[a *b* c] y\n";
7578        let m = map_directives(src);
7579        let b = m
7580            .rows
7581            .iter()
7582            .flat_map(|r| &r.glyphs)
7583            .find(|g| g.ch == 'b')
7584            .expect("the emphasised char");
7585        assert!(b.style.italic, "the label's *b* lost its emphasis");
7586        assert_eq!(b.src, 11, "the label's *b* lost its source byte");
7587    }
7588
7589    #[test]
7590    fn a_bare_colon_word_renders_as_the_prose_it_almost_always_is() {
7591        // Regression: twig matches a colon followed by any letter-led word, so
7592        // ordinary prose is full of "text directives" nobody meant to write.
7593        // With no `[label]` there are no children, and the arm recursed into
7594        // them — rendering *nothing*. The word vanished from the document with
7595        // no caret stop left behind, so it could not even be deleted.
7596        for src in ["a :word b\n", "note :see below\n", ":smile: hi\n"] {
7597            let m = map_directives(src);
7598            assert_eq!(
7599                rendered(&m).trim_end(),
7600                src.trim_end(),
7601                "prose was eaten: {src:?}"
7602            );
7603        }
7604    }
7605
7606    #[test]
7607    fn a_bare_colon_word_keeps_every_byte_a_caret_stop() {
7608        let src = "a :word b\n";
7609        let m = map_directives(src);
7610        // Nothing here is markup, so nothing is hidden: each byte maps to
7611        // itself and can be stood on, which is what makes the colon deletable.
7612        let stops: Vec<(char, usize)> = m
7613            .rows
7614            .iter()
7615            .flat_map(|r| &r.glyphs)
7616            .filter(|g| g.stop)
7617            .map(|g| (g.ch, g.src))
7618            .collect();
7619        assert_eq!(
7620            stops,
7621            "a :word b"
7622                .chars()
7623                .enumerate()
7624                .map(|(i, c)| (c, i))
7625                .collect::<Vec<_>>()
7626        );
7627    }
7628
7629    #[test]
7630    fn an_attribute_bearing_text_directive_draws_a_chip() {
7631        // `{…}` is deliberate in a way a bare colon is not — diaryx writes
7632        // `:vis{.family}` inline — so this one reads as an embed, on the same
7633        // `⧉ label` recipe the leaf form's placeholder row uses.
7634        // Both attribute conventions label it: twig's dot-prefixed classes and
7635        // the bare pandoc-style words diaryx also writes.
7636        for src in ["a :vis{.family} b\n", "a :vis{family} b\n"] {
7637            let m = map_directives(src);
7638            assert_eq!(rendered(&m).trim_end(), "a ⧉ vis family b", "{src:?}");
7639        }
7640        // A `key=value` attr is configuration, not a name, so it adds nothing.
7641        let m = map_directives("a :foo{title=\"x\"} b\n");
7642        assert_eq!(rendered(&m).trim_end(), "a ⧉ foo b");
7643    }
7644
7645    #[test]
7646    fn a_directive_chip_is_one_atomic_caret_stop_at_its_own_offset() {
7647        let src = "a :vis{.family} b\n";
7648        let m = map_directives(src);
7649        let stops: Vec<usize> = m
7650            .rows
7651            .iter()
7652            .flat_map(|r| &r.glyphs)
7653            .filter(|g| g.stop)
7654            .map(|g| g.src)
7655            .collect();
7656        // The chip contributes exactly one stop, at the directive's start (2),
7657        // so the caret steps over it whole instead of walking hidden markup a
7658        // byte at a time. `{.family}`'s bytes (3..15) are never stood on.
7659        assert_eq!(stops, [0, 1, 2, 15, 16]);
7660    }
7661
7662    #[test]
7663    fn a_paragraph_holding_only_a_chip_is_still_navigable() {
7664        // With no stop of its own the row would be unreachable — the caret
7665        // could never be put on the line to edit or delete the directive.
7666        let m = map_directives(":vis{.family}\n");
7667        assert!(
7668            m.row_is_navigable(0),
7669            "a chip-only paragraph has no caret home"
7670        );
7671        assert_eq!(
7672            m.offset_of_pos(0, 0),
7673            0,
7674            "its caret home isn't the directive's start"
7675        );
7676    }
7677
7678    #[test]
7679    fn a_ratio_or_a_clock_time_is_never_a_directive() {
7680        // twig requires a letter after the colon, so these stay prose — the
7681        // verbatim arm must not be reached for them at all.
7682        let src = "ratio 3:4 and 10:30\n";
7683        assert_eq!(
7684            rendered(&map_directives(src)).trim_end(),
7685            "ratio 3:4 and 10:30"
7686        );
7687    }
7688
7689    #[test]
7690    fn a_leaf_directive_is_a_placeholder_row_with_its_attrs_published() {
7691        // `::name{…}` is a standalone block with no body — an embed, a table of
7692        // contents. It used to emit no rows at all: invisible, no caret home,
7693        // vertical motion crossing a void. Now it draws the image recipe's
7694        // placeholder and publishes what the host app needs to paint the real
7695        // thing.
7696        let src = "before\n\n::embed{src=\"demo.html\" height=\"400\"}\n\nafter\n";
7697        let m = map_directives(src);
7698
7699        let row = m
7700            .rows
7701            .iter()
7702            .position(|r| r.leaf_directive.is_some())
7703            .expect("a placeholder row");
7704        assert_eq!(
7705            m.rows[row].glyphs.iter().map(|g| g.ch).collect::<String>(),
7706            "⧉ embed"
7707        );
7708        assert!(
7709            m.rows[row].glyphs.iter().any(|g| g.stop),
7710            "the caret can land on it"
7711        );
7712        assert!(
7713            m.rows[row].directive,
7714            "a frontend frames it like the container form"
7715        );
7716
7717        assert_eq!(m.directives.len(), 1);
7718        let info = &m.directives[0];
7719        assert_eq!(info.name, "embed");
7720        assert_eq!(info.rows_span, row..row + 1);
7721        assert_eq!(info.attr("src"), Some("demo.html"));
7722        assert_eq!(info.attr("height"), Some("400"));
7723        assert_eq!(info.attr("nope"), None);
7724        // The prose around it is untouched.
7725        assert!(rendered(&m).contains("before") && rendered(&m).contains("after"));
7726    }
7727
7728    #[test]
7729    fn a_leaf_directive_shows_its_label_and_honours_its_prefix() {
7730        // A `[label]` names the placeholder (the way an image's alt does), and a
7731        // quoted directive keeps the quote's gutter — it is a block like any
7732        // other, not a special case that escapes its container.
7733        let m = map_directives("::embed[Audience demo]{src=\"demo.html\"}\n");
7734        assert_eq!(rendered(&m).trim_end(), "⧉ Audience demo");
7735        assert_eq!(m.directives[0].label, "Audience demo");
7736
7737        let quoted = map_directives("> ::embed{src=\"x.html\"}\n");
7738        assert_eq!(rendered(&quoted).trim_end(), "│ ⧉ embed");
7739        assert_eq!(quoted.directives[0].name, "embed");
7740    }
7741
7742    #[test]
7743    fn a_container_directive_is_still_a_panel_not_a_placeholder() {
7744        // The three forms must not bleed into each other: only the leaf form is
7745        // a placeholder, and only the container form tints the blocks it wraps.
7746        let m = map_directives(":::note{.warning}\nBody\n:::\n");
7747        assert!(
7748            m.directives.is_empty(),
7749            "a container publishes no placeholder"
7750        );
7751        assert!(m.rows.iter().all(|r| r.leaf_directive.is_none()));
7752        assert_eq!(rendered(&m).trim_end(), "Body");
7753        assert!(
7754            m.rows
7755                .iter()
7756                .any(|r| r.directive && r.directive_label.as_deref() == Some("warning"))
7757        );
7758    }
7759
7760    /// A production-path build with both extensions on — the only way to put a
7761    /// promoted HTML element and a directive in one document, which is what the
7762    /// `container` kind made necessary to tell apart. Returns the whole `Doc`
7763    /// because [`VisualMap`] is not `Clone`; read `doc.vmap`.
7764    fn doc_built(src: &str) -> crate::Doc {
7765        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
7766        doc.build_visual(80);
7767        doc
7768    }
7769
7770    /// Every `container` node in `src`, parsed the way production does (both
7771    /// extensions on), paired with what [`container_is_directive`] makes of it.
7772    fn containers(src: &str) -> Vec<(String, bool, Option<DirectiveForm>)> {
7773        let mut ed = Editor::new_ext(
7774            src.as_bytes(),
7775            Format::Markdown,
7776            twig::MarkdownExtensions {
7777                directives: true,
7778                html_elements: true,
7779                ..Default::default()
7780            },
7781        )
7782        .unwrap();
7783        ed.nodes()
7784            .unwrap()
7785            .iter()
7786            .filter(|n| n.kind == Kind::Container)
7787            .map(|n| {
7788                (
7789                    n.name.clone().unwrap_or_default(),
7790                    container_is_directive(n),
7791                    n.directive_form,
7792                )
7793            })
7794            .collect()
7795    }
7796
7797    #[test]
7798    fn a_directive_and_an_html_element_are_told_apart_by_spelling_not_by_form() {
7799        // twig 2.8 folded `div`/`span`/`directive`/`element` into one `container`
7800        // kind. `directive_form` reads as though it separates them and does not:
7801        // a block-level `<div>` reports `Some(DirectiveForm::Container)` exactly
7802        // as a `:::note` does. Trusting it would draw directive chrome — a tinted
7803        // panel, a `.class` audience label — on every pasted Slack/Docs div.
7804        for (src, name, want) in [
7805            (":::note{.a}\nbody\n:::\n", "note", true),
7806            ("::embed{src=x}\n", "embed", true),
7807            ("a :vis[hi]{.b} b\n", "vis", true),
7808            ("<div class=\"x\">\nhi\n</div>\n", "div", false),
7809            ("<video src=\"v.mp4\" controls></video>\n", "video", false),
7810            ("<audio src=\"a.mp3\" controls></audio>\n", "audio", false),
7811            ("<figure>\n\nhi\n\n</figure>\n", "figure", false),
7812            // The `:` in an attribute must not read as a directive opener: the
7813            // `<` of the tag comes first, and first one wins.
7814            (
7815                "<video src=\"http://x.test/v.mp4\" controls></video>\n",
7816                "video",
7817                false,
7818            ),
7819            (
7820                "<source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\n",
7821                "source",
7822                false,
7823            ),
7824        ] {
7825            let found = containers(src);
7826            let hit = found.iter().find(|(n, ..)| n == name);
7827            let Some((_, is_directive, form)) = hit else {
7828                panic!("no `{name}` container in {src:?} — found {found:?}");
7829            };
7830            assert_eq!(*is_directive, want, "{name} in {src:?} (form was {form:?})");
7831        }
7832
7833        // And the reason this can't just read the field: for the one collision
7834        // that matters, the field says the same thing for both.
7835        let div = containers("<div class=\"x\">\nhi\n</div>\n");
7836        let note = containers(":::note{.a}\nbody\n:::\n");
7837        assert_eq!(
7838            div[0].2, note[0].2,
7839            "if these ever differ, `directive_form` became usable and this rule can go"
7840        );
7841    }
7842
7843    #[test]
7844    fn a_directive_nested_in_a_quote_or_list_is_still_a_directive() {
7845        // A container's span opens with its *block prefix*, not its own markup —
7846        // `> ::embed{…}` starts at the `>`. Reading only the first byte to tell a
7847        // directive from an element (both `container` since 2.8) therefore misses
7848        // every nested one, and the placeholder silently renders as nothing.
7849        for (src, ctx) in [
7850            ("> ::embed{src=\"x\"}\n", "quoted"),
7851            ("- ::embed{src=\"x\"}\n", "listed"),
7852            (">> ::embed{src=\"x\"}\n", "twice quoted"),
7853        ] {
7854            let m = map_directives(src);
7855            assert_eq!(m.directives.len(), 1, "{ctx} directive was lost");
7856            assert_eq!(m.directives[0].name, "embed", "{ctx}");
7857        }
7858    }
7859
7860    #[test]
7861    fn a_video_is_still_media_and_not_a_directive() {
7862        // The other side of the same coin: `<video>` is a `container` too, and
7863        // must reach `block_media` rather than the directive arms.
7864        let doc = doc_built("<video src=\"clip.mp4\" controls></video>\n");
7865        assert_eq!(doc.vmap.media.len(), 1, "the video is block media");
7866        assert!(
7867            doc.vmap.rows.iter().all(|r| !r.directive),
7868            "the video drew directive chrome"
7869        );
7870    }
7871
7872    #[test]
7873    fn a_directive_needs_the_extension_flag() {
7874        // `map` (twig's default extensions) leaves `directives` off — the fence
7875        // renders as literal paragraph text, same as any other unrecognized
7876        // punctuation, never corrupting or panicking.
7877        let src = ":::vis{.public}\nhello\n:::\n";
7878        let m = map(src);
7879        assert!(m.rows.iter().all(|r| !r.directive));
7880        assert!(rendered(&m).contains(":::vis{.public}"));
7881    }
7882
7883    #[test]
7884    fn a_footnote_reference_keeps_its_paragraph_visible() {
7885        // Regression: `footnote_reference` was in neither `is_inline_kind` nor
7886        // the inline walker, so a paragraph carrying one failed the "all children
7887        // inline" test, was walked as a container of blocks, and rendered as
7888        // empty rows with no caret stop anywhere — the whole line vanished.
7889        let src = "A claim[^1] and more.\n";
7890        let m = map(src);
7891        assert_eq!(rendered(&m).trim_end(), "A claim[1] and more.");
7892        // The `^` is spelling, not text: hidden the way a link's `](dest)` is.
7893        assert!(!rendered(&m).contains('^'));
7894    }
7895
7896    #[test]
7897    fn a_footnote_reference_is_raised_and_the_prose_around_it_is_not() {
7898        // What makes `[1]` read as a reference rather than as bracketed text.
7899        // The brackets ride with the label: the chip is one raised mark.
7900        let m = map("A claim[^1] and more.\n");
7901        assert_eq!(baselines_of(&m, '1'), vec![Baseline::Super]);
7902        assert_eq!(baselines_of(&m, '['), vec![Baseline::Super]);
7903        assert_eq!(baselines_of(&m, ']'), vec![Baseline::Super]);
7904        assert_eq!(baselines_of(&m, 'A'), vec![Baseline::Normal]);
7905    }
7906
7907    #[test]
7908    fn a_footnote_reference_keeps_the_link_role_it_had() {
7909        // The raised baseline is added to the role, not swapped for it: every
7910        // frontend already paints `Role::Link`, and a reference is one.
7911        let m = map("A claim[^1].\n");
7912        let label = m
7913            .rows
7914            .iter()
7915            .flat_map(|r| &r.glyphs)
7916            .find(|g| g.ch == '1')
7917            .unwrap();
7918        assert_eq!(label.style.role, Role::Link);
7919        assert_eq!(label.style.baseline, Baseline::Super);
7920    }
7921
7922    /// The [`Role`] of the first glyph spelling `ch` — how a test reads one
7923    /// run's styling off a map without caring which row it landed on.
7924    fn role_of(m: &VisualMap, ch: char) -> Role {
7925        m.rows
7926            .iter()
7927            .flat_map(|r| r.glyphs.iter())
7928            .find(|g| g.ch == ch)
7929            .unwrap_or_else(|| panic!("no glyph spelling {ch:?}"))
7930            .style
7931            .role
7932    }
7933
7934    #[test]
7935    fn a_markdown_highlight_is_a_mark_and_a_coloured_one_names_its_colour() {
7936        // twig 3.3's `highlight`/`highlight_colors`, which `parse_extensions`
7937        // turns on for every leaf document: `==text==` is a `mark` in Markdown
7938        // and not the literal `==` it used to be, and `==🔴 text==` is one
7939        // carrying a colour.
7940        //
7941        // `doc_built` rather than `map`, deliberately — the extensions are
7942        // leaf's choice, not twig's default, so a test that parsed bare
7943        // Markdown here would be testing a document leaf never builds.
7944        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
7945        assert_eq!(role_of(&doc.vmap, 'y'), Role::Mark(None));
7946        assert_eq!(
7947            role_of(&doc.vmap, 'r'),
7948            Role::Mark(Some(MarkColor::Red)),
7949            "the `data-color` twig stripped the emoji into"
7950        );
7951        assert_eq!(role_of(&doc.vmap, 'P'), Role::Body);
7952    }
7953
7954    #[test]
7955    fn the_emoji_that_named_a_highlight_is_markup_and_never_drawn() {
7956        // The colour is *spelling*: twig strips the emoji out of the mark's
7957        // content, so the reader sees the words and the wash, never the circle.
7958        // Drawing it would put a character in the rendered text that the author
7959        // wrote as syntax — the same mistake as drawing an emphasis's `*`.
7960        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
7961        let drawn: String = doc.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
7962        assert_eq!(drawn, "Plain yes and red ok");
7963    }
7964
7965    #[test]
7966    fn a_superscript_and_a_subscript_sit_off_the_baseline() {
7967        // Regression: both rendered flat, so the toolbar's superscript button
7968        // produced markup that looked exactly like the text around it.
7969        let m = map_djot("H~2~O and x^2^\n");
7970        assert_eq!(baselines_of(&m, '2'), vec![Baseline::Sub, Baseline::Super]);
7971        assert_eq!(baselines_of(&m, 'H'), vec![Baseline::Normal]);
7972        assert_eq!(baselines_of(&m, 'O'), vec![Baseline::Normal]);
7973    }
7974
7975    #[test]
7976    fn a_raised_glyph_keeps_the_style_it_was_raised_out_of() {
7977        // Why this is a `Baseline` and not a `Role`: raising a glyph says where
7978        // it sits, and must not cost it what it already was.
7979        let m = map_djot("# Heading x^2^\n");
7980        let two = m
7981            .rows
7982            .iter()
7983            .flat_map(|r| &r.glyphs)
7984            .find(|g| g.ch == '2')
7985            .unwrap();
7986        assert_eq!(two.style.baseline, Baseline::Super);
7987        assert_eq!(two.style.role, Role::Heading(1), "still heading text");
7988    }
7989
7990    #[test]
7991    fn a_footnote_references_brackets_are_decoration_and_only_its_label_is_a_stop() {
7992        let src = "see[^note] here\n";
7993        let m = map(src);
7994        // `[^note]` spans 3..10, its label `note` 5..9. The caret walks the
7995        // label; the brackets are drawn but never stood on, as a table's are,
7996        // and the `[^`/`]` bytes are stepped over like any hidden delimiter.
7997        let stops: Vec<usize> = m
7998            .rows
7999            .iter()
8000            .flat_map(|r| &r.glyphs)
8001            .filter(|g| g.stop)
8002            .map(|g| g.src)
8003            .collect();
8004        for off in 5..9 {
8005            assert!(
8006                stops.contains(&off),
8007                "label byte {off} isn't a caret stop: {stops:?}"
8008            );
8009        }
8010        for off in [3usize, 4, 9] {
8011            assert!(
8012                !stops.contains(&off),
8013                "delimiter byte {off} is a caret stop: {stops:?}"
8014            );
8015        }
8016    }
8017
8018    #[test]
8019    fn a_task_item_draws_its_box_where_the_bullet_would_be() {
8020        // Regression: the `[ ] ` is markup twig consumes — the item's paragraph
8021        // content starts past it — so a task item used to render as `• todo`,
8022        // identical to a plain bullet and with no way to see it was ticked.
8023        let m = map("- [ ] todo\n- [x] done\n- plain\n");
8024        assert_eq!(rendered(&m), "☐ todo\n☑ done\n• plain");
8025
8026        // The tick rides the item's first row, for a GUI that paints its own box.
8027        let ticks: Vec<Option<bool>> = m.rows.iter().map(|r| r.task).collect();
8028        assert_eq!(ticks, [Some(false), Some(true), None]);
8029    }
8030
8031    #[test]
8032    fn a_task_items_box_survives_a_wrap_and_marks_only_the_first_row() {
8033        let m = map_at(
8034            "- [x] a much longer task that has to wrap somewhere\n",
8035            Some(20),
8036        );
8037        assert!(m.rows.len() > 1, "the item should wrap: {:?}", rendered(&m));
8038        assert_eq!(m.rows[0].task, Some(true));
8039        assert!(
8040            m.rows[1..].iter().all(|r| r.task.is_none()),
8041            "only the first row"
8042        );
8043        // The continuation lines hang under the box, not under column zero.
8044        assert!(
8045            rendered(&m)
8046                .lines()
8047                .nth(1)
8048                .is_some_and(|l| l.starts_with("  "))
8049        );
8050    }
8051
8052    #[test]
8053    fn a_bracket_in_an_items_prose_is_not_a_checkbox() {
8054        // `task_checked` finds the box past the list marker; a plain item whose
8055        // text merely contains a bracket has none, and must keep its bullet.
8056        let m = map("- see [1] below\n");
8057        assert_eq!(rendered(&m), "• see [1] below");
8058        assert_eq!(m.rows[0].task, None);
8059    }
8060
8061    #[test]
8062    fn a_footnote_definition_renders_where_it_was_written() {
8063        // Regression: twig parses `[^1]: …` as a root *beside* `doc` — not a
8064        // child of it — so the walk from `doc` never reached one and every byte
8065        // of the note's body rendered as nothing at all.
8066        let src = "A claim[^1].\n\n[^1]: The note body.\n\nAfter.\n";
8067        let m = map(src);
8068        let text = rendered(&m);
8069        assert!(
8070            text.contains("The note body."),
8071            "the note body is invisible: {text:?}"
8072        );
8073        // In source order — between the paragraph that cites it and the one
8074        // after — not hoisted to the end, and marked to match its reference.
8075        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
8076        assert_eq!(lines, ["A claim[1].", "[1] The note body.", "After."]);
8077    }
8078
8079    #[test]
8080    fn a_footnote_definitions_body_maps_to_its_own_source_bytes() {
8081        let src = "x[^a].\n\n[^a]: body\n";
8082        let m = map(src);
8083        // `body` sits at 14..18. Its glyphs must map there — a marker that ate
8084        // the offsets would put the caret in the wrong place on every click.
8085        let body: Vec<(char, usize)> = m
8086            .rows
8087            .iter()
8088            .flat_map(|r| &r.glyphs)
8089            .filter(|g| g.stop && g.src >= 14)
8090            .map(|g| (g.ch, g.src))
8091            .collect();
8092        assert_eq!(body, [('b', 14), ('o', 15), ('d', 16), ('y', 17)]);
8093    }
8094
8095    #[test]
8096    fn an_empty_footnote_definition_still_shows_its_marker() {
8097        // The instant `[^1]: ` has been typed and nothing after it. `blocks`
8098        // renders no child, so without the explicit marker row the definition
8099        // wouldn't appear at all until something was typed into it.
8100        let src = "x[^1]\n\n[^1]:\n";
8101        let m = map(src);
8102        assert!(
8103            rendered(&m).contains("[1] "),
8104            "no marker row: {:?}",
8105            rendered(&m)
8106        );
8107    }
8108
8109    #[test]
8110    fn a_footnote_definition_wearing_a_long_label_indents_its_wrapped_body() {
8111        let src = "x[^src]\n\n[^src]: one two three four five six seven\n";
8112        let m = map_at(src, Some(24));
8113        let text = rendered(&m);
8114        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
8115        // Continuation lines hang under the marker, as a list item's do — the
8116        // indent is the marker's own width, not a fixed one.
8117        assert_eq!(lines[1].trim_end(), "[src] one two three four");
8118        assert!(
8119            lines[2].starts_with("      "),
8120            "body doesn't hang: {:?}",
8121            lines[2]
8122        );
8123        assert_eq!(lines[2].trim(), "five six seven");
8124    }
8125
8126    #[test]
8127    fn a_code_block_leaves_exactly_one_blank_row_below_it() {
8128        // The closing fence line used to be miscounted as a blank separator,
8129        // opening a phantom second gap under the block. One block boundary is
8130        // one blank row, code block or not.
8131        let src = "para\n\n```\ncode\n```\n\nafter\n";
8132        let m = map(src);
8133        let code_end = m.code_blocks[0].rows_span.end;
8134        let after = m
8135            .rows
8136            .iter()
8137            .position(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "after")
8138            .unwrap();
8139        assert_eq!(
8140            after - code_end,
8141            1,
8142            "exactly one row between code and 'after'"
8143        );
8144    }
8145
8146    #[test]
8147    fn a_fenced_block_publishes_its_language_on_its_code_block() {
8148        // The info string becomes the block's label; a bare fence and an indented
8149        // block carry none.
8150        assert_eq!(
8151            map("```rust\nlet x = 1;\n```\n").code_blocks[0]
8152                .lang
8153                .as_deref(),
8154            Some("rust")
8155        );
8156        assert_eq!(map("```\nplain\n```\n").code_blocks[0].lang, None);
8157        assert_eq!(map("    indented\n").code_blocks[0].lang, None);
8158    }
8159
8160    /// The token every glyph spelling `ch` carries, in row order — how a test
8161    /// reads a block's highlighting off the map.
8162    fn tokens_of(m: &VisualMap, ch: char) -> Vec<Option<Token>> {
8163        m.rows
8164            .iter()
8165            .flat_map(|r| r.glyphs.iter())
8166            .filter(|g| g.ch == ch)
8167            .map(|g| g.style.token)
8168            .collect()
8169    }
8170
8171    #[cfg(feature = "syntax")]
8172    #[test]
8173    fn a_fenced_block_in_a_known_language_carries_tokens() {
8174        // `let` is a keyword, the string literal a string, and the plain
8175        // identifier `x` nothing at all — it draws in the code colour. Every
8176        // glyph is still `Role::Code`: a token is beside the role, not instead.
8177        let m = map("```rust\nlet x = \"s\";\n```\n");
8178        assert_eq!(tokens_of(&m, 'l'), vec![Some(Token::Keyword)]);
8179        assert_eq!(tokens_of(&m, 'x'), vec![None]);
8180        assert_eq!(tokens_of(&m, '"'), vec![Some(Token::String); 2]);
8181        assert!(
8182            m.rows
8183                .iter()
8184                .filter(|r| r.code)
8185                .flat_map(|r| r.glyphs.iter())
8186                .all(|g| g.style.role == Role::Code),
8187            "a token replaced the code role"
8188        );
8189    }
8190
8191    #[cfg(feature = "syntax")]
8192    #[test]
8193    fn a_token_changes_nothing_about_where_a_glyph_is() {
8194        // The same block with and without a language it can be highlighted in
8195        // lays out identically: same rows, same offsets, same stops. Only the
8196        // token differs, so the caret walks a highlighted block as it walked an
8197        // unhighlighted one.
8198        let hl = map("```rust\nlet x = 1; // c\nfn f() {}\n```\n");
8199        let plain = map("```text\nlet x = 1; // c\nfn f() {}\n```\n");
8200        assert_eq!(hl.rows.len(), plain.rows.len());
8201        for (a, b) in hl.rows.iter().zip(&plain.rows) {
8202            assert_eq!(a.end_src, b.end_src);
8203            assert_eq!(a.glyphs.len(), b.glyphs.len());
8204            for (ga, gb) in a.glyphs.iter().zip(&b.glyphs) {
8205                assert_eq!((ga.ch, ga.src, ga.stop), (gb.ch, gb.src, gb.stop));
8206                assert_eq!(ga.style.token(None), gb.style);
8207            }
8208        }
8209        assert!(tokens_of(&hl, 'l').iter().any(Option::is_some));
8210        assert!(tokens_of(&plain, 'l').iter().all(Option::is_none));
8211    }
8212
8213    #[test]
8214    fn a_block_with_no_language_to_highlight_in_carries_no_tokens() {
8215        // A bare fence, an indented block, a fence in a language no grammar
8216        // covers, and inline code all draw as plain code — and so does a
8217        // `rust` fence when the `syntax` feature is off.
8218        for src in [
8219            "```\nlet x = 1;\n```\n",
8220            "    let x = 1;\n",
8221            "```no-such-language\nlet x = 1;\n```\n",
8222            "a `let x` b\n",
8223        ] {
8224            assert!(
8225                tokens_of(&map(src), 'l').iter().all(Option::is_none),
8226                "{src:?} was highlighted"
8227            );
8228        }
8229        #[cfg(not(feature = "syntax"))]
8230        assert!(
8231            tokens_of(&map("```rust\nlet x = 1;\n```\n"), 'l')
8232                .iter()
8233                .all(Option::is_none)
8234        );
8235    }
8236
8237    #[test]
8238    fn inline_code_is_not_a_code_block() {
8239        // A `code` span inside prose is styled by role, not boxed: it's part of a
8240        // normal paragraph row, so it names no `code_blocks` entry.
8241        let m = map("a `snippet` b\n");
8242        assert!(m.code_blocks.is_empty(), "inline code wrongly boxed");
8243        assert!(
8244            m.rows.iter().all(|r| !r.code),
8245            "inline code flagged a code row"
8246        );
8247    }
8248
8249    #[test]
8250    fn caret_steps_over_hidden_delimiters() {
8251        // "a **bold** c": bytes 8,9 are the closing ** — no glyph. Moving right
8252        // from 'd' (src 7) lands on the space before 'c' (src 10), not inside **.
8253        let m = map("a **bold** c\n");
8254        let (r, c) = m.pos_of_offset(7);
8255        assert_eq!(m.offset_of_pos(r, c + 1), 10);
8256    }
8257
8258    // ── the structural view of a table ───────────────────────────────────────
8259
8260    #[test]
8261    fn a_table_is_published_structurally_beside_its_picture() {
8262        let m = map(TABLE);
8263        let t = &m.tables[0];
8264        let cell = |r: usize, c: usize| -> String {
8265            t.grid[r].cells[c].glyphs.iter().map(|g| g.ch).collect()
8266        };
8267        assert_eq!(t.grid.len(), 3, "head + two body rows");
8268        assert_eq!(
8269            (cell(0, 0), cell(0, 1), cell(1, 0), cell(2, 1)),
8270            ("Name".into(), "Qty".into(), "Pear".into(), "12".into())
8271        );
8272        assert_eq!(
8273            t.grid.iter().map(|r| r.head).collect::<Vec<_>>(),
8274            [true, false, false]
8275        );
8276        // The alignment the delimiter row spelled, carried per cell — the only
8277        // place it survives, since the parser consumes that row.
8278        assert!(matches!(t.grid[1].cells[0].align, Alignment::Left));
8279        assert!(matches!(t.grid[1].cells[1].align, Alignment::Right));
8280    }
8281
8282    #[test]
8283    fn a_block_media_is_published_structurally_beside_its_placeholder() {
8284        let m = map("intro\n\n![a cat](img/cat.png)\n\nend\n");
8285        assert_eq!(m.media.len(), 1, "one block image");
8286        let img = &m.media[0];
8287        assert_eq!(img.destination, "img/cat.png");
8288        assert_eq!(img.alt, "a cat");
8289        // The placeholder row named by `rows_span` carries the label a plain
8290        // surface paints and a capable frontend replaces.
8291        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
8292        assert_eq!(
8293            img.rows_span.end - img.rows_span.start,
8294            1,
8295            "one placeholder row"
8296        );
8297        assert_eq!(row_text(img.rows_span.start), "🖼 a cat");
8298        // The row carries the mark `media_spans` derives the side-table from.
8299        assert!(m.rows[img.rows_span.start].media.is_some());
8300    }
8301
8302    #[test]
8303    fn an_image_without_alt_labels_itself_with_its_filename() {
8304        let m = map("![](photos/beach.jpg)\n");
8305        let row = &m.rows[m.media[0].rows_span.start];
8306        assert_eq!(
8307            row.glyphs.iter().map(|g| g.ch).collect::<String>(),
8308            "🖼 beach.jpg"
8309        );
8310        assert_eq!(m.media[0].alt, "");
8311    }
8312
8313    #[test]
8314    fn an_empty_cells_home_is_read_from_either_shape_of_span() {
8315        // A whole-row span: the cell's pipes are the `col`-th and next.
8316        let row = "|  |  |";
8317        assert_eq!(empty_cell_offset(row, 10, 0), 12);
8318        assert_eq!(empty_cell_offset(row, 10, 1), 15);
8319        // A cell's own span, opening pipe to closing pipe exclusive: the same
8320        // homes, each read from its own span.
8321        assert_eq!(empty_cell_offset("|  ", 10, 0), 12);
8322        assert_eq!(empty_cell_offset("|  ", 13, 1), 15);
8323        // Nothing to stand in: just inside the pipe, never past the span.
8324        assert_eq!(empty_cell_offset("|", 10, 0), 11);
8325        assert_eq!(empty_cell_offset("", 10, 1), 10);
8326    }
8327
8328    #[test]
8329    fn a_hidden_marks_content_end_is_a_caret_home_but_not_a_glyph_stop() {
8330        // `a **bold** b`: the `d` is at 7, the content ends at 8, the closing
8331        // `**` draws nothing, and the space after it is at 10. Two homes at one
8332        // spot on screen: 8 (inside the bold) and 10 (past it).
8333        let m = map("a **bold** b\n");
8334        assert!(
8335            !m.stops.contains(&8),
8336            "8 has no glyph, so it is no glyph stop"
8337        );
8338        assert_eq!(m.mark_ends, vec![8]);
8339        assert!(m.is_stop(8), "but the caret may rest there");
8340        assert_eq!(m.snap_to_stop(8), 8, "and is left there when placed there");
8341        // Left/Right take both homes; the character-pairing walk takes one.
8342        assert_eq!(m.caret_stop_after(7), Some(8));
8343        assert_eq!(m.caret_stop_after(8), Some(10));
8344        assert_eq!(m.caret_stop_before(10), Some(8));
8345        assert_eq!(m.caret_stop_before(8), Some(7));
8346        assert_eq!(m.stop_after(7), Some(10));
8347        assert_eq!(m.stop_before(10), Some(7));
8348        // Drawn where the next glyph is: after the `d`, not on it.
8349        assert_eq!(m.pos_of_offset(8), m.pos_of_offset(10));
8350    }
8351
8352    #[test]
8353    fn every_hidden_inline_mark_gives_its_content_end_a_home() {
8354        // One end per mark, whatever it is spelled with; nested marks closing
8355        // together share the outer's end and the inner's alike.
8356        assert_eq!(
8357            map("*em* `code` [link](u) ~~del~~\n").mark_ends,
8358            vec![3, 10, 17, 27]
8359        );
8360        assert_eq!(map("***both***\n").mark_ends, vec![7]);
8361        // A mark that closes at its row's end coincides with the row's own end
8362        // stop — one offset, in both tables.
8363        let m = map("**bold**\n");
8364        assert_eq!(m.mark_ends, vec![6]);
8365        assert!(m.stops.contains(&6));
8366        // Revealed, the delimiter is glyphs of its own and the end is an
8367        // ordinary glyph stop: nothing to add.
8368        let mut ed = Editor::new_str("a **bold** b\n", Format::Markdown).unwrap();
8369        let src = "a **bold** b\n";
8370        let revealed = build(
8371            &ed.nodes().unwrap(),
8372            src,
8373            Some(80),
8374            false,
8375            &Surface::default(),
8376            Some(Reveal::full(0..src.len())),
8377        );
8378        assert!(revealed.mark_ends.is_empty());
8379        assert!(revealed.stops.contains(&8));
8380    }
8381
8382    #[test]
8383    fn a_marks_content_end_is_a_home_inside_a_table_cell() {
8384        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
8385        let m = map(src);
8386        let end = src.find("bold").unwrap() + 4; // 32, before the closing `**`
8387        assert_eq!(m.mark_ends, vec![end]);
8388        assert_eq!(m.snap_to_stop(end), end);
8389        // Drawn after the `d`, in this cell — where the cell's own end stop is.
8390        assert_eq!(m.pos_of_offset(end), m.pos_of_offset(end + 2));
8391    }
8392
8393    #[test]
8394    fn a_block_media_gives_the_caret_a_home_before_and_after_it() {
8395        // `![x](y)` on its own line: the caret can rest in front of the image
8396        // (its start) and just past it (the row end), and nowhere inside the
8397        // markup — the same coarse mapping a thematic break uses.
8398        let src = "![x](y.png)\n";
8399        let m = map(src);
8400        let img = &m.rows[m.media[0].rows_span.start];
8401        let start = 0; // the image opens the document
8402        let end = "![x](y.png)".len();
8403        // Every placeholder glyph maps to the image start and is a stop there.
8404        assert!(img.glyphs.iter().all(|g| g.src == start && g.stop));
8405        assert_eq!(img.end_src, end, "the row ends past the image");
8406        assert_eq!(m.stops.first(), Some(&start));
8407        assert!(m.stops.contains(&end), "a stop sits after the image");
8408        // Nothing inside the markup is a stop.
8409        assert!(!m.stops.iter().any(|&s| s > start && s < end));
8410    }
8411
8412    #[test]
8413    fn an_inline_image_amid_text_is_not_a_block_media() {
8414        // An image sharing its line with prose isn't block-level: it stays in the
8415        // inline path (rendered as its alt text), and publishes no MediaInfo.
8416        let m = map("see ![a cat](cat.png) here\n");
8417        assert!(m.media.is_empty(), "not a block image");
8418        assert!(
8419            rendered(&m).contains("a cat"),
8420            "alt text still renders inline"
8421        );
8422    }
8423
8424    /// The block images `Doc` publishes for `src`, driven through the real
8425    /// production build (`build_visual` → `build_cached`) with `html_elements`
8426    /// on — the path a `<picture>` actually travels. Not the raw `build` the
8427    /// other tests use: the editor's flat whole-arena snapshot tangles the links
8428    /// of inline-promoted HTML (phantom roots, dangling `parent`s), which only
8429    /// the per-block subtree walk `build_cached` does untangles.
8430    fn doc_media(src: &str) -> Vec<MediaInfo> {
8431        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
8432        doc.build_visual(80);
8433        doc.vmap.media.clone()
8434    }
8435
8436    #[test]
8437    fn a_video_block_is_media_with_its_src_poster_and_kind() {
8438        // The load-bearing assumption of video support: twig has no `video` node
8439        // kind, so `html_elements` promotion must land a `<video>` as a generic
8440        // `element` whose tag name and attributes survive onto `FlatNode` — the
8441        // same treatment `<picture>` gets. If that ever stops holding, this is
8442        // the test that says so.
8443        let m = doc_media("<video src=\"clip.mp4\" poster=\"still.png\" controls>\n</video>\n");
8444        assert_eq!(m.len(), 1, "the video is one block media");
8445        assert_eq!(m[0].kind, MediaKind::Video);
8446        assert_eq!(m[0].destination, "clip.mp4");
8447        assert_eq!(m[0].poster, "still.png");
8448    }
8449
8450    #[test]
8451    fn a_single_line_video_is_a_block_too() {
8452        // The spelling everyone actually writes. It used to parse as a paragraph
8453        // of raw inline HTML — CommonMark opens a block on a complete tag only
8454        // when the line ends there, and its fixed tag list predates `<video>` —
8455        // so the tags never reached core as an element at all. twig 2.5.1 widened
8456        // that list under `html_elements`; this is the test that would catch the
8457        // pin sliding back.
8458        let m = doc_media("<video src=\"clip.mp4\" controls></video>\n");
8459        assert_eq!(m.len(), 1, "single-line <video> is a block");
8460        assert_eq!(m[0].kind, MediaKind::Video);
8461        assert_eq!(m[0].destination, "clip.mp4");
8462    }
8463
8464    #[test]
8465    fn a_single_line_picture_is_a_block_with_its_alternatives() {
8466        // `<picture>` had the identical gap and it went unnoticed because the
8467        // conventional spelling breaks the lines. Same twig fix covers it.
8468        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\
8469                   <img src=\"l.svg\" alt=\"banner\"></picture>\n";
8470        let m = doc_media(src);
8471        assert_eq!(m.len(), 1);
8472        assert_eq!(m[0].kind, MediaKind::Image);
8473        assert_eq!(m[0].destination, "l.svg");
8474        assert_eq!(m[0].resolve(ColorScheme::Dark), "d.svg");
8475    }
8476
8477    #[test]
8478    fn an_audio_block_is_media_with_no_poster() {
8479        let m = doc_media("<audio src=\"take.mp3\" controls>\n</audio>\n");
8480        assert_eq!(m.len(), 1);
8481        assert_eq!(m[0].kind, MediaKind::Audio);
8482        assert_eq!(m[0].destination, "take.mp3");
8483        assert!(m[0].poster.is_empty(), "audio has no poster frame");
8484    }
8485
8486    #[test]
8487    fn a_videos_source_children_are_its_candidates_typed_by_mime() {
8488        // A `<video>` with no `src` of its own — the common shape, since it's how
8489        // you offer more than one codec. The candidates come from `<source src>`
8490        // (not `srcset`, which is `<picture>`'s spelling) and carry their MIME.
8491        let src = "<video controls>\n\
8492                   <source src=\"a.webm\" type=\"video/webm\">\n\
8493                   <source src=\"a.mp4\" type=\"video/mp4\">\n\
8494                   fallback\n\
8495                   </video>\n";
8496        let m = doc_media(src);
8497        assert_eq!(m.len(), 1);
8498        assert!(
8499            m[0].destination.is_empty(),
8500            "no src attribute on the element"
8501        );
8502        assert_eq!(m[0].sources.len(), 2);
8503        assert_eq!(m[0].sources[0].srcset, "a.webm");
8504        assert_eq!(m[0].sources[0].mime, "video/webm");
8505        assert_eq!(m[0].sources[1].srcset, "a.mp4");
8506        // With an empty destination, `resolve` falls through to the first
8507        // candidate rather than handing the frontend nothing to load.
8508        assert_eq!(m[0].resolve(ColorScheme::Light), "a.webm");
8509    }
8510
8511    #[test]
8512    fn a_video_placeholder_row_carries_its_own_sigil_and_mark() {
8513        // The placeholder contract images already hold, now for a video: the row
8514        // renders as a labelled stand-in a plain surface can paint as-is, and
8515        // carries the mark a capable frontend replaces it from.
8516        let src = "<video src=\"clip.mp4\" controls>\n</video>\n";
8517        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
8518        doc.build_visual(80);
8519        let row = &doc.vmap.rows[doc.vmap.media[0].rows_span.start];
8520        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
8521        assert!(
8522            text.starts_with('🎬'),
8523            "video sigil, not the image one: {text:?}"
8524        );
8525        assert!(row.media.is_some(), "the mark rides the placeholder row");
8526    }
8527
8528    #[test]
8529    fn a_picture_block_carries_its_source_alternatives() {
8530        // A `<picture>` with a dark-mode `<source>`: one block image, whose
8531        // fallback destination is the `<img>` and whose `sources` carry the
8532        // `<source>`'s media + srcset for a theme-aware frontend to pick.
8533        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"banner\"></picture>\n";
8534        let images = doc_media(src);
8535        assert_eq!(images.len(), 1, "the picture is one block image");
8536        let img = &images[0];
8537        assert_eq!(img.destination, "light.svg", "fallback is the <img>");
8538        assert_eq!(img.alt, "banner");
8539        assert_eq!(
8540            img.sources,
8541            vec![MediaSource {
8542                media: "(prefers-color-scheme: dark)".into(),
8543                srcset: "dark.svg".into(),
8544                mime: String::new(),
8545            }],
8546        );
8547    }
8548
8549    #[test]
8550    fn a_picture_inside_a_heading_is_still_a_block_media_with_sources() {
8551        // fig.md's shape: the banner is an `<h1>` wrapping the `<picture>`.
8552        let src = "<h1><picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\"><img src=\"l.svg\" alt=\"fig\"></picture></h1>\n";
8553        let images = doc_media(src);
8554        assert_eq!(images.len(), 1, "heading-wrapped picture is a block image");
8555        assert_eq!(images[0].destination, "l.svg");
8556        assert_eq!(images[0].sources.len(), 1);
8557        assert_eq!(images[0].sources[0].srcset, "d.svg");
8558    }
8559
8560    #[test]
8561    fn a_plain_image_has_no_media_sources() {
8562        // A bare Markdown image carries an empty `sources` — nothing to pick from.
8563        let images = doc_media("![alt](p.png)\n");
8564        assert_eq!(images.len(), 1);
8565        assert!(
8566            images[0].sources.is_empty(),
8567            "no <picture>, no alternatives"
8568        );
8569    }
8570
8571    #[test]
8572    fn resolve_picks_the_source_matching_the_scheme() {
8573        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"b\"></picture>\n";
8574        let images = doc_media(src);
8575        let img = &images[0];
8576        // Dark theme takes the dark source; light falls through to the <img>.
8577        assert_eq!(img.resolve(ColorScheme::Dark), "dark.svg");
8578        assert_eq!(img.resolve(ColorScheme::Light), "light.svg");
8579    }
8580
8581    #[test]
8582    fn resolve_falls_back_for_a_plain_image_and_unknown_media() {
8583        // A plain image ignores the scheme.
8584        let plain = doc_media("![a](p.png)\n");
8585        assert_eq!(plain[0].resolve(ColorScheme::Dark), "p.png");
8586
8587        // A <source> with an unrecognized media query is skipped; a light source
8588        // is taken under a light theme.
8589        let m = doc_media(
8590            "<picture><source media=\"print\" srcset=\"p.svg\"><source media=\"(prefers-color-scheme: light)\" srcset=\"l.svg\"><img src=\"f.svg\" alt=\"x\"></picture>\n",
8591        );
8592        assert_eq!(m[0].resolve(ColorScheme::Light), "l.svg");
8593        assert_eq!(
8594            m[0].resolve(ColorScheme::Dark),
8595            "f.svg",
8596            "no dark source → <img>"
8597        );
8598    }
8599
8600    #[test]
8601    fn resolve_reads_the_first_srcset_url_ignoring_descriptors() {
8602        // A comma/descriptor srcset resolves to its first URL.
8603        assert_eq!(first_srcset_url("a.png 1x, b.png 2x"), Some("a.png"));
8604        assert_eq!(first_srcset_url("  solo.svg  "), Some("solo.svg"));
8605        assert_eq!(first_srcset_url(""), None);
8606        // An empty (unconditional) media always matches.
8607        assert!(media_matches("", ColorScheme::Light));
8608        assert!(media_matches(
8609            "(prefers-color-scheme:dark)",
8610            ColorScheme::Dark
8611        ));
8612        assert!(!media_matches(
8613            "(prefers-color-scheme: dark)",
8614            ColorScheme::Light
8615        ));
8616    }
8617
8618    #[test]
8619    fn a_block_media_carries_its_list_prefix() {
8620        // An image that is a list item's body opens past the bullet, like every
8621        // other block does.
8622        let m = map("- ![alt](p.png)\n");
8623        let row = &m.rows[m.media[0].rows_span.start];
8624        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
8625        assert!(
8626            text.starts_with("• "),
8627            "the list marker prefixes the image row: {text:?}"
8628        );
8629        assert!(text.contains("🖼 alt"));
8630    }
8631
8632    #[test]
8633    fn the_structural_table_spans_exactly_its_drawn_rows() {
8634        // A frontend drawing its own grid skips `rows_span` and renders from
8635        // `grid`. If the span were short the leftover border rows would be
8636        // painted as text under the real table; if long it would eat a
8637        // neighbouring paragraph. Both are silent, so pin it to the picture.
8638        let m = map(&format!("before\n\n{TABLE}\nafter\n"));
8639        let t = &m.tables[0];
8640        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
8641        assert!(
8642            row_text(t.rows_span.start).starts_with('┌'),
8643            "opens on the top border"
8644        );
8645        assert!(
8646            row_text(t.rows_span.end - 1).starts_with('└'),
8647            "closes on the bottom border"
8648        );
8649        assert!(
8650            !row_text(t.rows_span.start - 1).contains('┌'),
8651            "the row before the span is not the table's"
8652        );
8653        assert_eq!(
8654            row_text(t.rows_span.end),
8655            "",
8656            "the span ends before the gap row"
8657        );
8658    }
8659
8660    #[test]
8661    fn a_nested_tables_structure_carries_the_block_prefix() {
8662        // The picture puts the quote's gutter on every row of the grid. A
8663        // frontend drawing its own table has to draw that too and start past it,
8664        // so the prefix has to travel with the structure — without it a quoted
8665        // table renders flush at the margin and leaves the quote it's in.
8666        let m = map("> | a | b |\n> |---|---|\n> | c | d |\n");
8667        let t = &m.tables[0];
8668        let prefix: String = t.prefix.iter().map(|g| g.ch).collect();
8669        assert_eq!(prefix, "│ ", "the quote's gutter should ride the structure");
8670        // And it matches what the picture actually drew.
8671        let drawn: String = m.rows[t.rows_span.start]
8672            .glyphs
8673            .iter()
8674            .map(|g| g.ch)
8675            .collect();
8676        assert!(
8677            drawn.starts_with(&prefix),
8678            "picture and structure disagree: {drawn:?}"
8679        );
8680    }
8681
8682    #[test]
8683    fn a_top_level_table_carries_no_prefix() {
8684        assert!(map(TABLE).tables[0].prefix.is_empty());
8685    }
8686
8687    #[test]
8688    fn structural_cells_are_unwrapped_even_when_the_picture_wraps_them() {
8689        // The picture wraps a cell to its column; a frontend laying the grid out
8690        // in pixels needs the text as the document spells it, before that
8691        // decision. Narrow enough that the drawn cell must break.
8692        let src = "| Name |\n|------|\n| alpha beta gamma |\n";
8693        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8694        let m = build_t(&ed.nodes().unwrap(), src, Some(12));
8695        let drawn = rendered(&m);
8696        let cell: String = m.tables[0].grid[1].cells[0]
8697            .glyphs
8698            .iter()
8699            .map(|g| g.ch)
8700            .collect();
8701        assert_eq!(
8702            cell, "alpha beta gamma",
8703            "structure must not carry the wrap"
8704        );
8705        assert!(
8706            drawn.lines().count() > 5,
8707            "the picture should have wrapped, else this proves nothing:\n{drawn}"
8708        );
8709    }
8710
8711    // ── display columns ──────────────────────────────────────────────────────
8712
8713    #[test]
8714    fn a_table_column_is_as_wide_as_its_cells_are_drawn() {
8715        // A column sized by counting characters is drawn narrower than the text
8716        // it has to hold — `你好` is two characters in four cells — and the cell
8717        // spills over the border it is supposed to sit inside, taking the whole
8718        // grid out of square with it. Squareness is the property: every row of a
8719        // grid is drawn to the same column, whatever its cells are spelled with.
8720        for src in [
8721            "| A | B |\n|---|---|\n| 你好 | y |\n",
8722            "| A | B |\n|---|---|\n| a👨‍👩‍👧b | y |\n",
8723            "| A | 漢字 |\n|---|---|\n| x | y |\n",
8724        ] {
8725            let m = map(src);
8726            let widths: Vec<usize> = m.rows.iter().map(|r| r.width()).collect();
8727            assert!(
8728                widths.windows(2).all(|w| w[0] == w[1]),
8729                "ragged grid {widths:?} for {src:?}:\n{}",
8730                rendered(&m)
8731            );
8732        }
8733    }
8734
8735    #[test]
8736    fn a_cell_wrapped_narrow_never_breaks_inside_a_character() {
8737        // A column too narrow for its cell hard-breaks the text, and every line
8738        // of it is given an end stop just past its last glyph. Broken into runs
8739        // of four glyphs, the first line of this cell ends between `👨‍👩` and the
8740        // joiner holding `👧` on — so its end stop lands inside a character,
8741        // where a click or Down can reach it and the next Backspace takes the
8742        // cluster apart from the middle.
8743        let src = "| A |\n|---|\n| 👨‍👩‍👧👨‍👩‍👧 |\n";
8744        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8745        let m = build_t(&ed.nodes().unwrap(), src, Some(8));
8746        let boundaries: Vec<usize> = src
8747            .grapheme_indices(true)
8748            .map(|(i, _)| i)
8749            .chain(std::iter::once(src.len()))
8750            .collect();
8751        for off in (0..=src.len()).filter(|&o| m.is_stop(o)) {
8752            assert!(
8753                boundaries.contains(&off),
8754                "stop at {off} is inside a character:\n{}",
8755                rendered(&m)
8756            );
8757        }
8758    }
8759
8760    #[test]
8761    fn a_wrapped_cell_keeps_every_line_inside_its_column() {
8762        // The width is a promise in a table, where a glyph past the column lands
8763        // on the border or in the next cell — and it is a promise about cells,
8764        // which is not what a count of glyphs measures.
8765        let src = "| A |\n|---|\n| 你好世界漢字 |\n";
8766        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8767        let m = build_t(&ed.nodes().unwrap(), src, Some(14));
8768        for r in &m.rows {
8769            assert_eq!(r.width(), 14, "{:?} is not drawn to the grid", rendered(&m));
8770        }
8771    }
8772
8773    #[test]
8774    fn a_hard_break_falls_between_clusters_and_measures_in_cells() {
8775        let glyphs = |s: &str| {
8776            let mut out = Vec::new();
8777            push_text(&mut out, s, 0, Style::default());
8778            out
8779        };
8780        let piece = |p: &[Glyph]| p.iter().map(|g| g.ch).collect::<String>();
8781
8782        // Six cells of CJK broken at four: two characters, then one — never
8783        // between the two cells of `好`.
8784        let w = glyphs("你好世");
8785        let pieces: Vec<String> = hard_break(&w, 4).iter().map(|p| piece(p)).collect();
8786        assert_eq!(pieces, ["你好", "世"]);
8787
8788        // A character wider than the column has nowhere legal to break, so it
8789        // keeps its cells rather than being cut in half.
8790        let w = glyphs("你好");
8791        let pieces: Vec<String> = hard_break(&w, 1).iter().map(|p| piece(p)).collect();
8792        assert_eq!(pieces, ["你", "好"]);
8793
8794        // An empty word yields no pieces at all — a double space stays a space.
8795        assert!(hard_break(&[], 4).is_empty());
8796    }
8797
8798    #[test]
8799    fn an_empty_list_item_still_gets_a_bulleted_row_with_a_caret_home() {
8800        // Pressing Enter at the end of a list item opens a new, empty item —
8801        // a childless `list_item`. Without a row of its own the new bullet
8802        // wouldn't appear until something was typed into it (the caret would be
8803        // stranded on an offset no row draws). It now renders as one prefixed
8804        // row whose end is a caret stop, so the bullet shows and the caret lands
8805        // just past the marker.
8806        let m = map("- item\n- \n");
8807        assert_eq!(m.num_rows(), 2, "the empty second item needs its own row");
8808        assert_eq!(
8809            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8810            "• ",
8811            "the empty item draws just its bullet",
8812        );
8813        // Its end is the caret home (past the `- ` marker), and it's a real stop.
8814        assert!(
8815            m.is_stop(m.rows[1].end_src),
8816            "the empty item's caret home is not a stop"
8817        );
8818        assert_eq!(
8819            m.pos_of_offset(m.rows[1].end_src),
8820            (1, 2),
8821            "caret sits after '• '"
8822        );
8823    }
8824
8825    #[test]
8826    fn a_notes_row_range_stops_at_the_note_even_when_it_ends_in_a_link() {
8827        // The peek bug: a note whose body ends in a link has its last byte
8828        // inside the hidden destination, so mapping `end - 1` through
8829        // `pos_of_offset` snapped *forward* — past its own row, past the drawn
8830        // gap, and onto the next note's row. The popover then drew both notes.
8831        let src = "A[^1] B[^2].\n\n[^1]: bare text\n\n[^2]: [title](https://example.com/x)\n\n[^3]: last\n";
8832        let m = map(src);
8833        let body = src.find("[title]").unwrap();
8834        let end = src.find("\n\n[^3]").unwrap();
8835
8836        let (first, last) = m.row_range_for(body..end);
8837        assert_eq!(
8838            first, last,
8839            "a one-block note is one row, not a span onto the next"
8840        );
8841
8842        // The old arithmetic, kept here as the thing that must stay wrong: it
8843        // is what this method exists instead of.
8844        assert_ne!(
8845            m.pos_of_offset(end - 1).0,
8846            last,
8847            "the forward snap still leaves the note's row — that is the whole point",
8848        );
8849
8850        // A note ending in *visible* text was never broken, and still isn't:
8851        // both readings agree there, which is why the original test missed it.
8852        let plain = src.find("bare text").unwrap();
8853        let plain_end = src.find("\n\n[^2]").unwrap();
8854        let (pf, pl) = m.row_range_for(plain..plain_end);
8855        assert_eq!(pf, pl);
8856        assert_eq!(m.pos_of_offset(plain_end - 1).0, pl);
8857    }
8858
8859    #[test]
8860    fn a_row_range_covers_every_row_of_a_block_that_spans_several() {
8861        // The range is a span, not a point: a quote of two paragraphs covers its
8862        // gap row and both of its text rows, so a peek draws the whole thing.
8863        let src = "> one\n>\n> two\n\nafter\n";
8864        let m = map(src);
8865        let (first, last) = m.row_range_for(0..src.find("\n\nafter").unwrap());
8866        assert_eq!((first, last), (0, 2));
8867
8868        // And a range with no visible byte at all still covers the row it opened
8869        // on, rather than collapsing to nothing.
8870        let (f, l) = m.row_range_for(0..1);
8871        assert_eq!((f, l), (0, 0));
8872    }
8873
8874    #[test]
8875    fn an_empty_block_quote_still_gets_a_gutter_row_with_a_caret_home() {
8876        // The peer of the empty list item, and the case that made an empty line
8877        // in a quote draw as plain body text: a childless `block_quote` — a bare
8878        // `> `, which is what the toolbar's Quote button leaves on a blank line —
8879        // has no inner block to carry the gutter, so the whole quote used to
8880        // render as *nothing*. It didn't merely lose its bar; the row went away
8881        // and the caret had no home on it.
8882        let m = map("a\n\n> \n\nb\n");
8883        assert_eq!(
8884            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
8885            "│ ",
8886            "the empty quote draws just its gutter",
8887        );
8888        assert!(
8889            m.rows[2]
8890                .glyphs
8891                .iter()
8892                .all(|g| g.style.role == Role::QuoteGutter)
8893        );
8894        assert!(
8895            !m.rows[2].decoration,
8896            "it is a line text can go on, not a drawn gap"
8897        );
8898        assert!(
8899            m.is_stop(m.rows[2].end_src),
8900            "the empty quote's caret home is not a stop"
8901        );
8902        assert_eq!(
8903            m.pos_of_offset(m.rows[2].end_src),
8904            (2, 2),
8905            "caret sits after '│ '"
8906        );
8907
8908        // And a document that is *only* an empty quote still renders a row — it
8909        // used to render none at all, leaving the caret nowhere to stand.
8910        let m = map("> \n");
8911        assert_eq!(m.num_rows(), 1);
8912        assert_eq!(
8913            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
8914            "│ "
8915        );
8916    }
8917
8918    #[test]
8919    fn a_quotes_own_trailing_marker_lines_stay_inside_the_quote() {
8920        // Enter at the end of `> a` writes `> a\n>\n> \n`. Those last two lines
8921        // hold no block — a quote's `content_span` stops at its last child — so
8922        // the children walk never reaches them, and they used to fall through to
8923        // the document-level trailing pass, which knows no prefix: the gutter
8924        // stopped and the writer's new line drew as plain prose. Fixable only
8925        // since twig 3.2.0, where the quote's *span* covers its own marker lines
8926        // (`0..3` before, `0..8` now) and there is finally a node saying they
8927        // are the quote's.
8928        let m = map("> a\n>\n> \n");
8929        assert_eq!(m.num_rows(), 3, "one row per line the quote spells");
8930        for (i, row) in m.rows.iter().enumerate() {
8931            let text = row.glyphs.iter().map(|g| g.ch).collect::<String>();
8932            assert!(text.starts_with("│ "), "row {i} lost the gutter: {text:?}");
8933            assert!(
8934                !row.decoration,
8935                "row {i} is a line to type on, not a drawn gap"
8936            );
8937            assert!(m.is_stop(row.end_src), "row {i} has no caret home");
8938        }
8939        assert_eq!(
8940            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
8941            "│ a"
8942        );
8943        // Distinct offsets, so ↑/↓ between them moves the caret rather than
8944        // landing twice on the same byte.
8945        assert!(m.rows[0].end_src < m.rows[1].end_src);
8946        assert!(m.rows[1].end_src < m.rows[2].end_src);
8947
8948        // A blank line *after* the quote is not the quote's: it is spelled with
8949        // no marker, so it stays an ordinary boundary and the gutter ends.
8950        let m = map("> a\n\nb\n");
8951        assert_eq!(m.num_rows(), 3);
8952        assert_eq!(
8953            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
8954            "b"
8955        );
8956        assert!(
8957            !m.rows[1]
8958                .glyphs
8959                .iter()
8960                .any(|g| g.style.role == Role::QuoteGutter)
8961        );
8962
8963        // Nesting is the case this could get wrong, and the depth has to come
8964        // from which quote's span the line falls in rather than from the row
8965        // above it. A trailing `>` under `> > a` matches only the OUTER quote,
8966        // so it wears one gutter; spell it `> >` and it wears two.
8967        let m = map("> > a\n>\n");
8968        assert_eq!(
8969            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
8970            "│ │ a"
8971        );
8972        assert_eq!(
8973            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8974            "│ "
8975        );
8976        let m = map("> > a\n> >\n");
8977        assert_eq!(
8978            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8979            "│ │ "
8980        );
8981
8982        // And a marker line BETWEEN two quoted paragraphs is untouched: that is
8983        // the boundary `emit_separators_before` spells, and it stays a drawn gap
8984        // rather than becoming a line to type on.
8985        let m = map("> a\n>\n> b\n");
8986        assert_eq!(m.num_rows(), 3);
8987        assert!(
8988            m.rows[1].decoration,
8989            "the gap between two quoted blocks is still a gap"
8990        );
8991    }
8992
8993    #[test]
8994    fn an_empty_ordered_item_gets_its_number_and_a_caret_home() {
8995        let m = map("1. item\n2. \n");
8996        assert_eq!(m.num_rows(), 2);
8997        assert_eq!(
8998            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8999            "2. "
9000        );
9001        assert!(m.is_stop(m.rows[1].end_src));
9002        assert_eq!(
9003            m.pos_of_offset(m.rows[1].end_src),
9004            (1, 3),
9005            "caret sits after '2. '"
9006        );
9007    }
9008
9009    #[test]
9010    fn an_empty_headings_caret_home_is_past_its_hidden_marker() {
9011        // The toolbar's H1 on a blank line writes `# ` and nothing else. The row
9012        // it renders is empty (the marker is hidden), so its end *is* its only
9013        // caret stop — and it has to be the offset past the `# `, where typing
9014        // continues the heading. Anchored at the block's start instead, the caret
9015        // drew in front of the hashes and the first character typed there landed
9016        // before them (`x# `), which isn't a heading at all.
9017        let m = map("# \n");
9018        assert_eq!(m.num_rows(), 1);
9019        assert!(m.rows[0].glyphs.is_empty(), "the `# ` marker is hidden");
9020        assert_eq!(m.rows[0].end_src, 2, "the caret home is past the marker");
9021        assert!(m.is_stop(2), "the empty heading's caret home is not a stop");
9022    }
9023
9024    #[test]
9025    fn a_headings_rows_carry_its_level_even_with_nothing_typed_in_it() {
9026        // The row-level fact a proportional frontend sizes a whole line by. An
9027        // empty heading has no glyph to read a `Role::Heading` off, so a renderer
9028        // scanning glyphs drew `# ` (and its caret) at body height until the
9029        // first character landed.
9030        let m = map("# \n");
9031        assert_eq!(
9032            m.rows[0].heading,
9033            Some(1),
9034            "the empty heading knows its level"
9035        );
9036
9037        // Every row of one that wraps, not just the first — and nothing else.
9038        let m = map_at(
9039            "## a heading long enough to wrap over two rows\n\nbody\n",
9040            Some(20),
9041        );
9042        let heads: Vec<Option<u8>> = m.rows.iter().map(|r| r.heading).collect();
9043        assert!(
9044            heads.iter().filter(|h| **h == Some(2)).count() >= 2,
9045            "got {heads:?}"
9046        );
9047        assert_eq!(
9048            m.rows.last().and_then(|r| r.heading),
9049            None,
9050            "the paragraph under it is not a heading",
9051        );
9052    }
9053
9054    #[test]
9055    fn an_empty_heading_leaves_the_rows_under_it_at_their_own_offsets() {
9056        // The row's end is also what the *next* row's separator is measured from,
9057        // so an empty heading that under-reported it shifted every offset below —
9058        // and the blank line under the heading then claimed the same offset as the
9059        // heading's own end. `pos_of_offset` resolves such a tie downstream (a
9060        // soft wrap belongs to the row below), so the caret at the end of the
9061        // heading was drawn two rows lower, on the blank line.
9062        // `text\n\n# \n\n`: the heading's content opens at 8, and the two rows
9063        // under it end at 9 and 10 — the blank line and the document's end.
9064        let m = map("text\n\n# \n\n");
9065        let end = m.rows.last().expect("a trailing blank row").end_src;
9066        assert_eq!(end, 10, "the trailing rows must end at their real offsets");
9067        // The heading's caret home is its own row's, not one shared with a row
9068        // below — the tie that drew the caret two rows down.
9069        assert_eq!(m.pos_of_offset(8), (2, 0), "the empty heading's own row");
9070        assert!(
9071            m.rows[3..].iter().all(|r| r.end_src > 8),
9072            "rows below own later offsets"
9073        );
9074    }
9075
9076    // ── block boundaries ─────────────────────────────────────────────────────
9077
9078    /// Every drawn boundary in `src`, in order, as `(above, below)`.
9079    fn boundaries(m: &VisualMap) -> Vec<(BlockClass, BlockClass)> {
9080        m.rows
9081            .iter()
9082            .filter_map(|r| r.boundary)
9083            .map(|b| (b.above, b.below))
9084            .collect()
9085    }
9086
9087    #[test]
9088    fn a_boundary_says_which_blocks_it_divides() {
9089        use BlockClass::*;
9090        let m = map("one\n\ntwo\n\n# Head\n\ntail\n\n> quoted\n\n```\ncode\n```\n");
9091        assert_eq!(
9092            boundaries(&m),
9093            vec![
9094                (Paragraph, Paragraph),
9095                (Paragraph, Heading),
9096                (Heading, Paragraph),
9097                (Paragraph, Quote),
9098                (Quote, Code),
9099                // The blank the document trails off with is a boundary too — it
9100                // closes the last block above the empty paragraph the caret rests
9101                // on. See `emit_trailing_blank_lines`.
9102                (Code, Paragraph),
9103            ],
9104            "each gap names the pair it falls between, in document order"
9105        );
9106    }
9107
9108    // ── hidden blocks ────────────────────────────────────────────────────────
9109
9110    /// The row texts of `m`, one string per row.
9111    fn row_texts(m: &VisualMap) -> Vec<String> {
9112        m.rows
9113            .iter()
9114            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9115            .collect()
9116    }
9117
9118    #[test]
9119    fn a_div_s_closing_tag_is_not_a_blank_row() {
9120        // The `</div>` sits on a line of its own under the div's last child and
9121        // draws nothing. Counting the separator from the child's end read that
9122        // line as a blank line between the div and the block below — a
9123        // navigable empty row the author never opened — and at the end of the
9124        // file, as an empty trailing paragraph.
9125        let m = map("above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n");
9126        assert_eq!(row_texts(&m), ["above", "", "hello", "", "below"]);
9127        assert!(!m.is_stop(36), "the `</div>` line is not a caret home");
9128        assert_eq!(
9129            m.stop_after(34),
9130            Some(44),
9131            "from `hello` the next stop is `below`"
9132        );
9133
9134        let m = map("above\n\n<div class=\"center\">\n\nhello\n\n</div>\n");
9135        assert_eq!(row_texts(&m), ["above", "", "hello"], "no trailing rows");
9136    }
9137
9138    #[test]
9139    fn a_comment_between_two_blocks_is_stepped_over_not_drawn_as_a_gap() {
9140        // `<!-- exec -->` is a top-level block that draws no rows. The blocks
9141        // either side of it meet across the one boundary a paragraph and a code
9142        // block always meet across — not that boundary *plus* one blank row per
9143        // line of the comment, which is what counting the separator from the
9144        // paragraph's end used to spell.
9145        let m = map("para one\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n");
9146        assert_eq!(row_texts(&m), ["para one", "", "code", "", "after"]);
9147        assert_eq!(
9148            boundaries(&m),
9149            vec![
9150                (BlockClass::Paragraph, BlockClass::Code),
9151                (BlockClass::Code, BlockClass::Paragraph),
9152            ],
9153            "the boundary names the drawn blocks either side, not the comment"
9154        );
9155        // The gap stands past the comment, so the caret's row lookup never
9156        // resolves inside it.
9157        assert_eq!(
9158            m.rows[1].end_src, 23,
9159            "the gap row ends at the comment's end"
9160        );
9161    }
9162
9163    #[test]
9164    fn a_comment_opening_the_document_draws_no_leading_gap() {
9165        let m = map("<!-- lead -->\n\npara\n");
9166        assert_eq!(row_texts(&m), ["para"]);
9167        assert_eq!(m.content_start, 0, "the comment is still the first block");
9168    }
9169
9170    #[test]
9171    fn a_comment_closing_the_document_is_not_trailing_blank_lines() {
9172        // Its lines are not blank lines the author opened with Enter, so no
9173        // gap-plus-empty-paragraph is fabricated under the last drawn block.
9174        let m = map("para\n\n<!-- trail -->\n");
9175        assert_eq!(row_texts(&m), ["para"]);
9176        // Enter at the end of the document still opens the empty paragraph the
9177        // caret rests on: the newlines *after* the comment count as they would
9178        // after any block.
9179        let m = map("para\n\n<!-- trail -->\n\n");
9180        assert_eq!(row_texts(&m), ["para", "", ""]);
9181    }
9182
9183    #[test]
9184    fn a_comment_in_a_list_item_leaves_the_bullet_to_what_follows_it() {
9185        // The first *drawn* child wears the item's marker; a hidden first child
9186        // would otherwise take it and leave the text without one.
9187        let m = map("- <!-- note -->\n\n  text\n- two\n");
9188        let texts = row_texts(&m);
9189        assert!(
9190            texts.iter().any(|t| t == "• text"),
9191            "the text wears the bullet: {texts:?}"
9192        );
9193        assert!(
9194            !texts.iter().any(|t| t == "• "),
9195            "no empty bullet row for the comment: {texts:?}"
9196        );
9197    }
9198
9199    #[test]
9200    fn the_cached_build_does_not_spell_the_document_out_as_blank_rows_after_a_comment() {
9201        // The bug as seen: a 200-line document with one comment in it rendered
9202        // ~200 blank rows after the comment, one per source line, because the
9203        // comment's per-block builder handed back a `last_off` of 0. Parity with
9204        // `build` alone would not catch a *shared* wrong answer, so the count is
9205        // pinned outright.
9206        let body = (0..200)
9207            .map(|i| format!("line {i}"))
9208            .collect::<Vec<_>>()
9209            .join("\n\n");
9210        let src = format!("intro\n\n<!-- exec -->\n{body}\n");
9211        let mut ed = Editor::new_str(&src, Format::Markdown).unwrap();
9212        let mut cache = BlockCache::default();
9213        let (plain, cached) = render_both(&mut ed, &src, Some(80), &mut cache);
9214        assert_maps_eq(&plain, &cached, "comment then 200 paragraphs");
9215        // intro, then 200 × (gap, paragraph): 401 rows and not a row more.
9216        assert_eq!(cached.rows.len(), 401);
9217    }
9218
9219    #[test]
9220    fn a_link_reference_definition_is_stepped_over_like_a_comment() {
9221        // `[a]: /a` is a root beside `doc` with no rows of its own. Merged into
9222        // the walk it is a hidden block: the blocks either side meet across one
9223        // boundary, and its line is not a blank row.
9224        let m = map("see [a]\n\n[a]: /a\n\nafter\n");
9225        assert_eq!(row_texts(&m), ["see a", "", "after"]);
9226        assert_eq!(
9227            boundaries(&m),
9228            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
9229        );
9230    }
9231
9232    #[test]
9233    fn link_reference_definitions_closing_the_document_are_not_trailing_blank_lines() {
9234        // The README shape: prose, then a `[links]` block nobody reads. Its
9235        // lines used to be counted as blank ones, an empty paragraph per
9236        // definition under the last real block.
9237        let m = map("see [a] and [b]\n\n<!-- links -->\n[a]: /a\n[b]: /b \"bee\"\n");
9238        assert_eq!(row_texts(&m), ["see a and b"]);
9239    }
9240
9241    #[test]
9242    fn a_definition_glued_under_a_paragraph_stays_inside_it() {
9243        // `[a]: /a` at the front of a paragraph's lines is stripped from the
9244        // paragraph's text, but the paragraph's span still starts on its line.
9245        // Both blocks start at the same offset; the definition, sorted first,
9246        // is stepped over, and the paragraph draws as it always did — one gap
9247        // above it, none inside.
9248        let m = map("intro\n\n[a]: /a\ntext [a]\n");
9249        assert_eq!(row_texts(&m), ["intro", "", "text a"]);
9250    }
9251
9252    #[test]
9253    fn a_definition_with_no_span_is_left_out_of_the_walk() {
9254        // twig before 3.3.3 reported `0..0` for every link reference
9255        // definition. One of those has nowhere to be merged: sorted first by
9256        // its zero start it would open the document with a phantom block, and
9257        // the walk would step back to offset 0. It is simply not a block. A
9258        // footnote definition is always placed; it has a body to draw.
9259        assert!(!is_placed_definition(&Kind::Reference, &(0..0)));
9260        assert!(is_placed_definition(&Kind::Reference, &(7..14)));
9261        assert!(is_placed_definition(&Kind::Footnote, &(0..0)));
9262        assert!(!is_placed_definition(&Kind::Str, &(7..14)));
9263    }
9264
9265    #[test]
9266    fn the_trailing_gap_closes_the_last_block() {
9267        // Two Enters at the end of a document: a drawn gap, then the navigable
9268        // empty paragraph. Only the gap is labelled, so a frontend that shrinks
9269        // boundaries shrinks the spacer and leaves the row being typed on alone.
9270        let m = map("# Head\n\n\n");
9271        assert_eq!(
9272            boundaries(&m),
9273            vec![(BlockClass::Heading, BlockClass::Paragraph)]
9274        );
9275    }
9276
9277    #[test]
9278    fn only_the_drawn_gap_rows_carry_a_boundary() {
9279        let m = map("one\n\ntwo\n");
9280        for row in &m.rows {
9281            assert_eq!(
9282                row.boundary.is_some(),
9283                row.decoration,
9284                "a boundary is exactly a drawn gap row: {:?}",
9285                row.glyphs.iter().map(|g| g.ch).collect::<String>()
9286            );
9287        }
9288    }
9289
9290    #[test]
9291    fn preserve_flow_labels_no_boundary() {
9292        // Every blank line is a caret home there — somewhere text can go, not a
9293        // gap between blocks — so nothing is drawn-only and nothing is labelled.
9294        // A frontend keying its spacing off `boundary` can't shrink a row the
9295        // author is about to type on.
9296        let m = map_preserve("one\n\ntwo\n\n# Head\n", Some(80));
9297        assert!(boundaries(&m).is_empty());
9298    }
9299
9300    #[test]
9301    fn a_list_draws_no_boundary_between_its_items() {
9302        // Tight or loose, core puts no gap row between two items of one list —
9303        // so an item↔item boundary is a shape no frontend will ever be handed,
9304        // and spacing one is spacing something that isn't there.
9305        for src in ["- one\n- two\n", "- one\n\n- two\n"] {
9306            let m = map(src);
9307            assert!(
9308                boundaries(&m).is_empty(),
9309                "no gap row inside the list of {src:?}"
9310            );
9311        }
9312        // Leaving the list is an ordinary boundary, and the list is named as
9313        // what sits above it.
9314        let m = map("- one\n- two\n\npara\n");
9315        assert_eq!(
9316            boundaries(&m),
9317            vec![(BlockClass::List, BlockClass::Paragraph)]
9318        );
9319    }
9320
9321    #[test]
9322    fn a_nested_boundary_names_the_blocks_inside_the_container() {
9323        // Two paragraphs inside a blockquote are divided by a Paragraph↔Paragraph
9324        // boundary — the quote is the container they're both in, not what the gap
9325        // separates.
9326        let m = map("> one\n>\n> two\n");
9327        assert_eq!(
9328            boundaries(&m),
9329            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
9330        );
9331    }
9332
9333    #[test]
9334    fn a_directive_container_draws_one_boundary_like_every_other_block() {
9335        // A container's rows stop at its last *child*, so without anchoring
9336        // `last_off` past the closing `:::` the separator logic counted the fence
9337        // line as a blank row of its own and drew the gap twice — one authored
9338        // blank line, two boundaries, and a frontend spacing each of them put
9339        // double margin under every fenced div. The code-block arm anchors past
9340        // its ``` for exactly this reason; compare the two here.
9341        let fenced = map_directives(":::note\nin\n:::\n\ntwo\n");
9342        assert_eq!(
9343            boundaries(&fenced),
9344            vec![(BlockClass::Directive, BlockClass::Paragraph)],
9345            "one authored gap, one boundary row"
9346        );
9347        let code = map("```\nc\n```\n\ntwo\n");
9348        assert_eq!(
9349            boundaries(&code).len(),
9350            boundaries(&fenced).len(),
9351            "a fenced div spaces like a fenced code block"
9352        );
9353        // Nesting closes several fences at once; still one gap.
9354        let nested = map_directives(":::a\n:::b\nin\n:::\n:::\n\ntwo\n");
9355        assert_eq!(
9356            boundaries(&nested),
9357            vec![(BlockClass::Directive, BlockClass::Paragraph)]
9358        );
9359    }
9360
9361    #[test]
9362    fn a_block_media_names_itself_in_the_boundaries_either_side() {
9363        use BlockClass::*;
9364        // A block image is never a node of its own — `media_only` promotes the
9365        // *paragraph* wrapping it — so classifying the node the walk stands on
9366        // called the picture `Paragraph` and left `BlockClass::Media` unreachable:
9367        // a frontend could not give a photo more air than a line of prose.
9368        // `label_media_boundaries` reads it back off the finished rows instead.
9369        let m = map("one\n\n![alt](p.png)\n\ntwo\n");
9370        assert_eq!(boundaries(&m), vec![(Paragraph, Media), (Media, Paragraph)]);
9371        // At the edges of the document too: the leading gap has no boundary of
9372        // its own, and the trailing one is `emit_trailing_blank_lines`'.
9373        let edges = map("![a](p.png)\n\nmid\n\n![b](q.png)\n");
9374        assert_eq!(
9375            boundaries(&edges),
9376            vec![(Media, Paragraph), (Paragraph, Media)]
9377        );
9378        // One gap spelled with several rows — the row closing the block above and
9379        // the row opening the one below, with the author's spare blank line
9380        // navigable between them — carries the same pair on every drawn row.
9381        let roomy = map("one\n\n\n\n![alt](p.png)\n");
9382        assert_eq!(
9383            boundaries(&roomy),
9384            vec![(Paragraph, Media), (Paragraph, Media)]
9385        );
9386    }
9387
9388    #[test]
9389    fn a_block_video_is_media_at_its_boundaries_not_a_directive_panel() {
9390        // Worse than the image case before `label_media_boundaries`: a `<video>`
9391        // arrives as twig's generic `container`, which classifies `Directive` —
9392        // the one class a frontend reads as "draw a tinted panel here". A movie
9393        // got the chrome of a fenced div.
9394        let mut doc = crate::Doc::from_source(
9395            "one\n\n<video src=\"v.mp4\"></video>\n\ntwo\n".to_string(),
9396            Format::Markdown,
9397        )
9398        .unwrap();
9399        doc.build_visual(80);
9400        assert_eq!(
9401            boundaries(&doc.vmap),
9402            vec![
9403                (BlockClass::Paragraph, BlockClass::Media),
9404                (BlockClass::Media, BlockClass::Paragraph),
9405            ]
9406        );
9407    }
9408
9409    #[test]
9410    fn the_incremental_walk_labels_boundaries_like_the_full_one() {
9411        // `assert_maps_eq` compares boundaries too, so this pins the two doors
9412        // into `BlockClass::from_node_kind` — a `FlatNode`'s kind on the full
9413        // build, a query match's on the cached one — against a document with one
9414        // of every boundary in it.
9415        let src = "one\n\n# Head\n\ntwo\n\n- a\n- b\n\n> q\n\n```\nc\n```\n\npara\n";
9416        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
9417        let mut cache = BlockCache::default();
9418        let (full, cached) = render_both(&mut ed, src, Some(80), &mut cache);
9419        assert_maps_eq(&full, &cached, "boundary labelling");
9420        assert!(
9421            !boundaries(&full).is_empty(),
9422            "the fixture has boundaries to compare"
9423        );
9424    }
9425
9426    #[test]
9427    fn every_caret_stop_opens_a_cluster_of_its_row() {
9428        // The two ways of finding a cluster have to agree. `push_text` marks the
9429        // stops by segmenting one run of text; the column mapping segments the
9430        // whole row, decoration and all. A stop that came out as the *middle* of
9431        // some row-level cluster would be a caret with no column of its own —
9432        // drawn at the column of whatever swallowed it.
9433        let src = "# 標題\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` 你好\n\n\
9434                   - 項目 one\n- e\u{0301}dge\n\n> 引用 text\n\n\
9435                   | A | 值 |\n|---|---|\n| 你好 | 👩‍🚀 |\n";
9436        let m = map(src);
9437        for (r, row) in m.rows.iter().enumerate() {
9438            let openers: Vec<usize> = clusters(&row.glyphs).iter().map(|c| c.glyph).collect();
9439            for (i, g) in row.glyphs.iter().enumerate() {
9440                assert!(
9441                    !g.stop || openers.contains(&i),
9442                    "row {r}: the stop at glyph {i} ({:?}) is inside a cluster, \
9443                     so it is drawn at another glyph's column",
9444                    g.ch
9445                );
9446            }
9447        }
9448    }
9449
9450    // ── the presentation vocabulary ─────────────────────────────────────────
9451
9452    /// A block's own attributes, in the three formats that spell one on the
9453    /// block itself: HTML's tag, djot's `{…}` line, and — the odd one — a
9454    /// Markdown `<div>` around it, which is where twig has to put a Markdown
9455    /// block's attributes because the format has nowhere else.
9456    #[test]
9457    fn a_block_carries_its_alignment_on_every_row_it_draws() {
9458        // HTML, on the paragraph. `lead` is somebody else's class and is
9459        // neither read nor in the way.
9460        let html = map_leaf("<p class=\"lead center\">hi</p>\n", Format::Html);
9461        assert_eq!(line_facts(&html), vec![(Some(Align::Center), None)]);
9462
9463        // djot's attribute line, on the block.
9464        let dj = map_leaf("{.right}\nhi\n", Format::Djot);
9465        assert_eq!(line_facts(&dj), vec![(Some(Align::Right), None)]);
9466
9467        // A heading carries it too, and on every row a wrapped one draws.
9468        let h = map_leaf("{.center}\n# a heading\n", Format::Djot);
9469        assert_eq!(line_facts(&h), vec![(Some(Align::Center), None)]);
9470        assert_eq!(h.rows[0].heading, Some(1));
9471
9472        // Both keys at once, and the line spacing is read the same way.
9473        let both = map_leaf("{.justify data-line-height=\"1.5\"}\nhi\n", Format::Djot);
9474        assert_eq!(
9475            line_facts(&both),
9476            vec![(
9477                Some(Align::Justify),
9478                Some(LineHeight::Step(LineSpacing::OneHalf))
9479            )]
9480        );
9481
9482        // An unknown token is somebody else's and the block draws at the
9483        // theme's alignment; a ratio outside the menu's three is the author's
9484        // own and draws at exactly what they wrote.
9485        let other = map_leaf("{.lead data-line-height=\"1.3\"}\nhi\n", Format::Djot);
9486        assert_eq!(line_facts(&other), vec![(None, LineHeight::ratio(1.3))]);
9487
9488        // A value the grammar does not cover is neither: carried by the
9489        // document, drawn at the theme's spacing, and read as nothing at all.
9490        let em = map_leaf("{data-line-height=\"1.3em\"}\nhi\n", Format::Djot);
9491        assert_eq!(line_facts(&em), vec![(None, None)]);
9492    }
9493
9494    /// `<div class="center">` around three paragraphs centres all three, which
9495    /// is what the author of that HTML meant — and around one is the sole-child
9496    /// shape twig's `set_block_attrs` writes in Markdown.
9497    #[test]
9498    fn a_div_lends_its_alignment_to_every_block_inside_it() {
9499        let m = map_leaf(
9500            "<div class=\"center\" data-line-height=\"2\">\n\none\n\ntwo\n\n</div>\n",
9501            Format::Markdown,
9502        );
9503        assert_eq!(
9504            line_facts(&m),
9505            vec![
9506                (
9507                    Some(Align::Center),
9508                    Some(LineHeight::Step(LineSpacing::Double))
9509                ),
9510                (
9511                    Some(Align::Center),
9512                    Some(LineHeight::Step(LineSpacing::Double))
9513                ),
9514            ]
9515        );
9516
9517        // The nearer node wins, and the block after the div is untouched — the
9518        // context is restored, not left running.
9519        let nested = map_leaf(
9520            "<div class=\"center\">\n\n<div class=\"right\">\n\ninner\n\n</div>\n\nouter\n\n</div>\n\nafter\n",
9521            Format::Markdown,
9522        );
9523        assert_eq!(
9524            line_facts(&nested),
9525            vec![
9526                (Some(Align::Right), None),
9527                (Some(Align::Center), None),
9528                (None, None),
9529            ]
9530        );
9531    }
9532
9533    /// Size, face and colour are the run's, and the block's when the whole
9534    /// block is meant — read at both levels with the nearer winning.
9535    #[test]
9536    fn a_span_s_size_beats_its_block_s_and_its_face_falls_through() {
9537        // `<div data-font>` over `<p data-size>` over `<span data-size>`: the
9538        // span wins on size, the block is still what says the face.
9539        // The span is not first on its line: a `<span …>` opening one is an
9540        // HTML *block* to CommonMark, which is a fact about Markdown and not
9541        // about this.
9542        let m = map_leaf(
9543            "<div data-font=\"serif\">\n\nc <span data-size=\"small\">a</span> b\n\n</div>\n",
9544            Format::Markdown,
9545        );
9546        let a = style_of(&m, 'a');
9547        assert_eq!(a.size, Some(FontSize::Step(SizeStep::Small)));
9548        assert_eq!(a.font, Some(FaceRef::Generic(FontFamily::Serif)));
9549        // The text outside the span keeps the div's face and no size at all.
9550        let b = style_of(&m, 'b');
9551        assert_eq!(b.size, None);
9552        assert_eq!(b.font, Some(FaceRef::Generic(FontFamily::Serif)));
9553
9554        // djot spells the same span anonymously and it reads identically.
9555        let dj = map_leaf(
9556            "{data-size=\"large\"}\nx [y]{data-size=\"xx-large\" data-color=\"blue\"} z\n",
9557            Format::Djot,
9558        );
9559        assert_eq!(
9560            style_of(&dj, 'x').size,
9561            Some(FontSize::Step(SizeStep::Large))
9562        );
9563        assert_eq!(
9564            style_of(&dj, 'y').size,
9565            Some(FontSize::Step(SizeStep::XxLarge))
9566        );
9567        assert_eq!(
9568            style_of(&dj, 'y').color,
9569            Some(TextColor::Named(MarkColor::Blue))
9570        );
9571        // The block's size is still the block's outside the span.
9572        assert_eq!(
9573            style_of(&dj, 'z').size,
9574            Some(FontSize::Step(SizeStep::Large))
9575        );
9576        assert_eq!(style_of(&dj, 'z').color, None);
9577    }
9578
9579    /// The exact half of the vocabulary reaches a glyph and a row by the same
9580    /// doors the names do — the fold has one rule, not one per form. A named
9581    /// family is the one that cannot ride the glyph as itself: the walker
9582    /// interns it and the glyph carries the id.
9583    #[test]
9584    fn an_exact_size_face_and_colour_reach_the_glyph_and_the_row() {
9585        let m = map_leaf(
9586            "<div data-line-height=\"1.3\">\n\nc <span data-size=\"14pt\" \
9587             data-color=\"#c03030\" data-font=\"Garamond\">a</span> b\n\n</div>\n",
9588            Format::Markdown,
9589        );
9590        let a = style_of(&m, 'a');
9591        assert_eq!(a.size, FontSize::points(14.0));
9592        assert_eq!(
9593            a.color,
9594            Some(TextColor::Rgb {
9595                r: 0xc0,
9596                g: 0x30,
9597                b: 0x30
9598            })
9599        );
9600        assert_eq!(a.font, Some(FaceRef::Named(FaceId::of("Garamond"))));
9601        assert_eq!(m.face_name(FaceId::of("Garamond")), Some("Garamond"));
9602        // The div's ratio is the row's, on every row the block draws.
9603        assert_eq!(line_facts(&m), vec![(None, LineHeight::ratio(1.3))]);
9604        // And the text outside the span has none of the span's three.
9605        let b = style_of(&m, 'b');
9606        assert_eq!((b.size, b.font, b.color), (None, None, None));
9607
9608        // One name, one entry, however many spans wear it — the table is what
9609        // keeps a `Style` `Copy` and it should not grow per run.
9610        let twice = map_leaf(
9611            "x <span data-font=\"Garamond\">a</span> y <span data-font=\"Garamond\">b</span>\n",
9612            Format::Markdown,
9613        );
9614        assert_eq!(twice.faces().len(), 1);
9615        assert_eq!(
9616            style_of(&twice, 'a').font,
9617            style_of(&twice, 'b').font,
9618            "one family, one id"
9619        );
9620
9621        // A generic needs no entry at all: it names itself.
9622        let generic = map_leaf(
9623            "<div data-font=\"serif\">\n\nhi\n\n</div>\n",
9624            Format::Markdown,
9625        );
9626        assert_eq!(
9627            style_of(&generic, 'h').font,
9628            Some(FaceRef::Generic(FontFamily::Serif))
9629        );
9630        assert!(generic.faces().is_empty());
9631    }
9632
9633    /// The one key two nodes share. `data-color` on a `mark` is the highlight's
9634    /// *background* and reaches a glyph through [`Role::Mark`]; the same key on
9635    /// an attributed span is the text's foreground. Same vocabulary, same enum,
9636    /// no collision — and a mark inside a coloured span wears both.
9637    #[test]
9638    fn a_mark_keeps_its_highlight_colour_and_a_span_colours_the_text() {
9639        let m = map_leaf("a ==\u{1f534} red== b\n", Format::Markdown);
9640        let r = style_of(&m, 'r');
9641        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)));
9642        assert_eq!(r.color, None, "a highlight is not a text colour");
9643
9644        let both = map_leaf(
9645            "<span data-color=\"blue\">a ==\u{1f534} red== b</span>\n",
9646            Format::Markdown,
9647        );
9648        let r = style_of(&both, 'r');
9649        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)), "the highlight");
9650        assert_eq!(
9651            r.color,
9652            Some(TextColor::Named(MarkColor::Blue)),
9653            "the letters"
9654        );
9655    }
9656
9657    /// A page break is the `::page-break` leaf directive, and djot spells the
9658    /// same document as an empty `::: page-break` fence whose name comes back
9659    /// as a class. Both draw the placeholder row every leaf directive gets and
9660    /// both carry the same [`DirectiveMark`], because a frontend that opens a
9661    /// page at one must not be able to tell which format the file is in.
9662    #[test]
9663    fn a_page_break_reads_the_same_in_markdown_and_in_djot() {
9664        for (fmt, src) in [
9665            (Format::Markdown, "a\n\n::page-break\n\nb\n"),
9666            (Format::Djot, "a\n\n::: page-break\n:::\n\nb\n"),
9667        ] {
9668            let m = map_leaf(src, fmt);
9669            let marks: Vec<&DirectiveMark> = m
9670                .rows
9671                .iter()
9672                .filter_map(|r| r.leaf_directive.as_ref())
9673                .collect();
9674            assert_eq!(marks.len(), 1, "{fmt:?} draws one placeholder");
9675            assert_eq!(marks[0].name, "page-break", "{fmt:?}");
9676            assert!(marks[0].attrs.is_empty(), "{fmt:?}: {:?}", marks[0].attrs);
9677            assert!(
9678                m.rows
9679                    .iter()
9680                    .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>()
9681                        == "\u{29c9} page-break"),
9682                "{fmt:?} draws the label, got {:?}",
9683                m.rows
9684                    .iter()
9685                    .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
9686                    .collect::<Vec<_>>()
9687            );
9688        }
9689
9690        // A Markdown `:::note` with nothing in it is *not* this: its name is
9691        // its own, and nothing about it says "a block with no body" the way
9692        // djot's spelling of a leaf directive does.
9693        let empty_fence = map_leaf("::: note\n:::\n", Format::Markdown);
9694        assert!(
9695            empty_fence.rows.iter().all(|r| r.leaf_directive.is_none()),
9696            "a named empty fence keeps the reading it has"
9697        );
9698    }
9699
9700    /// A djot fence carrying more than its name keeps the rest as an attribute
9701    /// rather than folding it into the name: the *first* class token is the
9702    /// name, because that is where `insert_directive` puts it.
9703    #[test]
9704    fn a_djot_fence_s_first_class_is_the_directive_s_name_and_the_rest_is_attributes() {
9705        let m = map_leaf("{.page-break .wide}\n:::\n:::\n", Format::Djot);
9706        let mark = m
9707            .rows
9708            .iter()
9709            .find_map(|r| r.leaf_directive.as_ref())
9710            .expect("a placeholder");
9711        assert_eq!(mark.name, "page-break");
9712        assert_eq!(
9713            mark.attrs,
9714            vec![("class".to_string(), Some("wide".to_string()))]
9715        );
9716    }
9717
9718    // ── math ─────────────────────────────────────────────────────────────────
9719
9720    /// [`map_leaf`] on a chosen surface and reveal — the whole of what a math
9721    /// rendering turns on.
9722    fn map_math(src: &str, format: Format, surface: &Surface, reveal: Option<Reveal>) -> VisualMap {
9723        let mut ed =
9724            Editor::new_ext(src.as_bytes(), format, crate::doc::parse_extensions()).unwrap();
9725        build(&ed.nodes().unwrap(), src, Some(80), false, surface, reveal)
9726    }
9727
9728    fn pictures() -> Surface {
9729        Surface {
9730            inline_pictures: true,
9731            ..Default::default()
9732        }
9733    }
9734
9735    #[test]
9736    fn markdown_reads_math_and_a_dollar_before_whitespace_stays_prose() {
9737        // The `math` extension is on for every leaf document; twig's own rule
9738        // keeps a price out of it.
9739        let m = map_leaf("Say $E = mc^2$ for $5 and $6.\n", Format::Markdown);
9740        assert_eq!(row_texts(&m), vec!["Say E = mc^2 for $5 and $6."]);
9741        let e = m.rows[0].glyphs.iter().find(|g| g.ch == 'E').unwrap();
9742        assert_eq!(
9743            e.style.role,
9744            Role::Code,
9745            "the formula's TeX, in the code style"
9746        );
9747        assert_eq!(e.src, 5, "at its own byte, past the `$`");
9748        let five = m.rows[0].glyphs.iter().find(|g| g.ch == '5').unwrap();
9749        assert_eq!(five.style.role, Role::Body);
9750        assert!(m.math.is_empty(), "no picture stands in on a plain surface");
9751    }
9752
9753    #[test]
9754    fn a_plain_surface_draws_inline_math_as_code_with_the_delimiters_hidden() {
9755        // The verbatim treatment, in both languages — what `inline_math` always
9756        // rendered as — with the caret's home at the content's end.
9757        for (src, fmt) in [
9758            ("a $x+y$ b\n", Format::Markdown),
9759            ("a $`x+y` b\n", Format::Djot),
9760        ] {
9761            let m = map_leaf(src, fmt);
9762            assert_eq!(row_texts(&m), vec!["a x+y b"], "{src:?}");
9763            let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
9764            assert_eq!(x.style.role, Role::Code);
9765            assert!(!m.mark_ends.is_empty(), "the content end is a caret home");
9766        }
9767    }
9768
9769    #[test]
9770    fn display_math_in_a_line_of_prose_puts_its_text_at_the_text_s_own_offset() {
9771        // `display_math` had no arm and fell to the default one, which pushed
9772        // the text at the *node's* start: three bytes short in djot, past `$$`
9773        // and the backtick.
9774        let m = map_leaf("Before $$`x`$$ after\n", Format::Djot);
9775        let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
9776        assert_eq!(x.src, "Before $$`".len());
9777        assert_eq!(x.style.role, Role::Code);
9778        let m = map_leaf("Before $$x$$ after\n", Format::Markdown);
9779        let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
9780        assert_eq!(x.src, "Before $$".len());
9781    }
9782
9783    #[test]
9784    fn a_surface_that_paints_in_a_line_gets_one_atom_per_inline_formula() {
9785        let src = "Say $E = mc^2$ and $a$.\n";
9786        let m = map_math(src, Format::Markdown, &pictures(), None);
9787        assert_eq!(row_texts(&m), vec!["Say ∑ and ∑."]);
9788        assert_eq!(m.math.len(), 2);
9789        let first = &m.math[0];
9790        assert_eq!(first.tex, "E = mc^2");
9791        assert!(!first.display);
9792        assert_eq!(first.row, 0);
9793        assert_eq!(first.rows_span, 0..1);
9794        assert_eq!(first.glyph, Some(4));
9795        assert_eq!(first.src, 4, "the formula's start, where a click lands");
9796        let atom = &m.rows[0].glyphs[4];
9797        assert_eq!(atom.ch, MATH_ATOM);
9798        assert_eq!(atom.style.role, Role::Math);
9799        assert!(atom.stop);
9800        assert_eq!(atom.src, 4);
9801        // The caret has a stop on the atom and the next glyph's past it, and
9802        // nothing inside the markup.
9803        assert_eq!(m.stop_after(4), Some("Say $E = mc^2$".len()));
9804        assert!(m.mark_ends.is_empty(), "no home inside the hidden markup");
9805        // The row carries the marks the side-table is derived from.
9806        assert_eq!(m.rows[0].math.len(), 2);
9807        assert_eq!(m.rows[0].math[1].glyph, Some(m.math[1].glyph.unwrap()));
9808        assert_eq!(m.math[1].tex, "a");
9809    }
9810
9811    #[test]
9812    fn a_display_formula_written_inline_is_an_atom_in_display_style() {
9813        let m = map_math("Before $$x$$ after\n", Format::Markdown, &pictures(), None);
9814        assert_eq!(row_texts(&m), vec!["Before ∑ after"]);
9815        assert_eq!(m.math.len(), 1);
9816        assert!(m.math[0].display);
9817        assert_eq!(m.math[0].tex, "x");
9818    }
9819
9820    #[test]
9821    fn an_atom_follows_its_glyph_across_a_wrap() {
9822        // Fifteen words, then a formula that wraps onto the second row: the
9823        // mark is drained onto the row the glyph landed on, at its index there.
9824        let src = format!("{}$x$ end\n", "word ".repeat(15));
9825        let mut ed = Editor::new_ext(
9826            src.as_bytes(),
9827            Format::Markdown,
9828            crate::doc::parse_extensions(),
9829        )
9830        .unwrap();
9831        let m = build(
9832            &ed.nodes().unwrap(),
9833            &src,
9834            Some(40),
9835            false,
9836            &pictures(),
9837            None,
9838        );
9839        assert!(m.rows.len() >= 2);
9840        assert_eq!(m.math.len(), 1);
9841        let info = &m.math[0];
9842        let g = &m.rows[info.row].glyphs[info.glyph.unwrap()];
9843        assert_eq!(g.ch, MATH_ATOM);
9844        assert_eq!(g.src, src.find("$x$").unwrap());
9845        assert!(m.rows[..info.row].iter().all(|r| r.math.is_empty()));
9846    }
9847
9848    #[test]
9849    fn an_atom_in_a_table_cell_rides_the_cell_s_row() {
9850        let m = map_math(
9851            "| a | b |\n|---|---|\n| $x$ | c |\n",
9852            Format::Markdown,
9853            &pictures(),
9854            None,
9855        );
9856        assert_eq!(m.math.len(), 1);
9857        let info = &m.math[0];
9858        assert_eq!(m.rows[info.row].glyphs[info.glyph.unwrap()].ch, MATH_ATOM);
9859    }
9860
9861    #[test]
9862    fn a_display_formula_on_its_own_lines_is_a_block_placeholder_on_every_surface() {
9863        for (src, fmt) in [
9864            (
9865                "intro\n\n$$\n\\int_0^1 x\\,dx\n$$\n\nend\n",
9866                Format::Markdown,
9867            ),
9868            ("intro\n\n$$`\\int_0^1 x\\,dx`\n\nend\n", Format::Djot),
9869        ] {
9870            for surface in [Surface::default(), pictures()] {
9871                let m = map_math(src, fmt, &surface, None);
9872                assert_eq!(
9873                    row_texts(&m),
9874                    vec!["intro", "", "∑ \\int_0^1 x\\,dx", "", "end"],
9875                    "{src:?}"
9876                );
9877                assert_eq!(m.math.len(), 1);
9878                let info = &m.math[0];
9879                assert!(info.display);
9880                assert_eq!(info.glyph, None, "a block, not an atom");
9881                assert_eq!(info.rows_span, 2..3);
9882                assert_eq!(info.tex.trim(), "\\int_0^1 x\\,dx");
9883                let start = src.find("$$").unwrap();
9884                let end = start + src[start..].find("\n\nend").unwrap();
9885                assert_eq!(info.src, start);
9886                // Every label glyph at the formula's start, a stop there and
9887                // one past the block, nothing inside — a picture's two homes.
9888                let row = &m.rows[2];
9889                assert!(
9890                    row.glyphs
9891                        .iter()
9892                        .all(|g| g.src == start && g.style.role == Role::Math)
9893                );
9894                assert_eq!(row.end_src, end);
9895                assert_eq!(m.stop_after(start), Some(end));
9896                assert_eq!(m.stop_before(end), Some(start));
9897                // The gaps either side are labelled as a formula's.
9898                assert_eq!(m.rows[1].boundary.map(|b| b.below), Some(BlockClass::Math));
9899                assert_eq!(m.rows[3].boundary.map(|b| b.above), Some(BlockClass::Math));
9900            }
9901        }
9902    }
9903
9904    #[test]
9905    fn a_display_block_reserves_the_rows_the_frontend_measured() {
9906        let src = "$$\nx\n$$\n\nend\n";
9907        let surface = Surface {
9908            math_rows: HashMap::from([("\nx\n".to_string(), 4)]),
9909            ..Default::default()
9910        };
9911        let m = map_math(src, Format::Markdown, &surface, None);
9912        assert_eq!(m.math[0].rows_span, 0..4);
9913        assert_eq!(row_texts(&m)[..5], ["∑ x", "", "", "", ""]);
9914        // The fillers are decoration: drawn, no caret, anchored past the block.
9915        for r in &m.rows[1..4] {
9916            assert!(r.decoration);
9917            assert_eq!(r.end_src, 7);
9918        }
9919        assert_eq!(m.stop_after(0), Some(7));
9920        // A height keyed by TeX that does not match reserves nothing.
9921        let surface = Surface {
9922            math_rows: HashMap::from([("x".to_string(), 4)]),
9923            ..Default::default()
9924        };
9925        let m = map_math(src, Format::Markdown, &surface, None);
9926        assert_eq!(m.math[0].rows_span, 0..1);
9927    }
9928
9929    #[test]
9930    fn a_paragraph_with_prose_beside_a_display_formula_is_not_a_block() {
9931        let m = map_math("see\n$$\nx\n$$\n", Format::Markdown, &pictures(), None);
9932        assert!(
9933            m.math.iter().all(|i| i.glyph.is_some()),
9934            "an atom, not a placeholder"
9935        );
9936        let m = map_math(
9937            "$$\nx\n$$\n$$\ny\n$$\n",
9938            Format::Markdown,
9939            &pictures(),
9940            None,
9941        );
9942        assert_eq!(m.math.len(), 2);
9943        assert!(
9944            m.math.iter().all(|i| i.glyph.is_some()),
9945            "two formulas is prose with math in it"
9946        );
9947    }
9948
9949    #[test]
9950    fn a_formula_on_the_reveal_line_is_its_tex_in_every_mode() {
9951        let src = "Say $E = mc^2$ here.\n";
9952        // The hidden modes' reveal: only the formula shows its markup.
9953        let m = map_math(
9954            src,
9955            Format::Markdown,
9956            &pictures(),
9957            Some(Reveal::math(0..src.len() - 1)),
9958        );
9959        assert_eq!(row_texts(&m), vec!["Say $E = mc^2$ here."]);
9960        assert!(
9961            m.math.is_empty(),
9962            "nothing stands in for a revealed formula"
9963        );
9964        let dollar = m.rows[0].glyphs.iter().find(|g| g.ch == '$').unwrap();
9965        assert_eq!(dollar.style.role, Role::Delimiter);
9966        let e = m.rows[0].glyphs.iter().find(|g| g.ch == 'E').unwrap();
9967        assert_eq!(e.style.role, Role::Code);
9968        // Full's reveal draws the same, and an emphasis beside it reveals too
9969        // where the hidden modes' does not.
9970        let src = "*a* $x$\n";
9971        let hidden = map_math(
9972            src,
9973            Format::Markdown,
9974            &pictures(),
9975            Some(Reveal::math(0..src.len() - 1)),
9976        );
9977        assert_eq!(row_texts(&hidden), vec!["a $x$"]);
9978        let full = map_math(
9979            src,
9980            Format::Markdown,
9981            &pictures(),
9982            Some(Reveal::full(0..src.len() - 1)),
9983        );
9984        assert_eq!(row_texts(&full), vec!["*a* $x$"]);
9985        // A reveal line that does not meet the formula leaves the atom.
9986        let other = map_math(
9987            "$x$\n\ntext\n",
9988            Format::Markdown,
9989            &pictures(),
9990            Some(Reveal::math(5..9)),
9991        );
9992        assert_eq!(row_texts(&other)[0], "∑");
9993    }
9994
9995    #[test]
9996    fn a_display_block_on_the_reveal_line_is_its_source_lines_in_the_code_style() {
9997        let src = "intro\n\n$$\n\\int_0^1 x\n$$\n\nend\n";
9998        // Any line of the block reveals the whole of it: here the middle one.
9999        let mid = src.find("\\int").unwrap();
10000        let line = mid..mid + "\\int_0^1 x".len();
10001        let m = map_math(src, Format::Markdown, &pictures(), Some(Reveal::math(line)));
10002        assert_eq!(
10003            row_texts(&m),
10004            vec!["intro", "", "$$", "\\int_0^1 x", "$$", "", "end"]
10005        );
10006        assert!(m.math.is_empty());
10007        let fence = m.rows[2].glyphs.iter().find(|g| g.ch == '$').unwrap();
10008        assert_eq!(fence.style.role, Role::Delimiter);
10009        assert_eq!(fence.src, 7);
10010        let x = m.rows[3].glyphs.iter().find(|g| g.ch == 'x').unwrap();
10011        assert_eq!(x.style.role, Role::Code);
10012        assert_eq!(x.src, src.find("x\n$$").unwrap());
10013        // Every byte of the source is reachable: a stop on each fence and each
10014        // character between.
10015        assert!(m.is_stop(7));
10016        assert!(m.is_stop(mid));
10017        // The closing fence's line too, and the same for djot.
10018        let close = src.rfind("$$").unwrap();
10019        let m = map_math(
10020            src,
10021            Format::Markdown,
10022            &pictures(),
10023            Some(Reveal::math(close..close + 2)),
10024        );
10025        assert_eq!(row_texts(&m)[2], "$$");
10026        let src = "$$`\n\\int\n`\n";
10027        let m = map_math(src, Format::Djot, &pictures(), Some(Reveal::math(4..8)));
10028        assert_eq!(row_texts(&m), vec!["$$`", "\\int", "`"]);
10029    }
10030
10031    #[test]
10032    fn a_block_that_holds_a_formula_says_so_to_the_cache() {
10033        let src = "plain\n\nwith $x$ in it\n\n$$\ny\n$$\n";
10034        let mut ed = Editor::new_ext(
10035            src.as_bytes(),
10036            Format::Markdown,
10037            crate::doc::parse_extensions(),
10038        )
10039        .unwrap();
10040        let mut cache = BlockCache::default();
10041        let top = top_blocks(&mut ed);
10042        let _ = build_cached(
10043            &top,
10044            src,
10045            None,
10046            false,
10047            &pictures(),
10048            None,
10049            &mut cache,
10050            |id| ed.subtree(NodeId(id)).unwrap_or_default(),
10051        );
10052        assert!(!cache.math_meets(&(0..5)), "the plain paragraph");
10053        assert!(cache.math_meets(&(7..21)), "the one with an atom");
10054        assert!(
10055            cache.math_meets(&(26..27)),
10056            "the middle line of the display block"
10057        );
10058        // A hit carries the answer without a walk: build again from the cache.
10059        let _ = build_cached(
10060            &top,
10061            src,
10062            None,
10063            false,
10064            &pictures(),
10065            None,
10066            &mut cache,
10067            |_| Vec::new(),
10068        );
10069        assert!(cache.math_meets(&(7..21)));
10070        assert!(!cache.math_meets(&(0..5)));
10071    }
10072
10073    #[test]
10074    fn incremental_builds_agree_with_the_reference_on_math() {
10075        for src in [
10076            "a $x$ b\n\n$$\ny\n$$\n\nc\n",
10077            "one\n\ntwo $\\frac{a}{b}$ three\n",
10078            "$$\n\\int\n$$\n",
10079        ] {
10080            for surface in [Surface::default(), pictures()] {
10081                let mut ed = Editor::new_ext(
10082                    src.as_bytes(),
10083                    Format::Markdown,
10084                    crate::doc::parse_extensions(),
10085                )
10086                .unwrap();
10087                let all = ed.nodes().unwrap();
10088                let plain = build(&all, src, Some(80), false, &surface, None);
10089                let mut cache = BlockCache::default();
10090                let top = top_blocks(&mut ed);
10091                let cached = build_cached(
10092                    &top,
10093                    src,
10094                    Some(80),
10095                    false,
10096                    &surface,
10097                    None,
10098                    &mut cache,
10099                    |id| ed.subtree(NodeId(id)).unwrap_or_default(),
10100                );
10101                assert_eq!(row_texts(&plain), row_texts(&cached), "{src:?}");
10102                assert_eq!(plain.math, cached.math, "{src:?}");
10103                assert_eq!(plain.stops, cached.stops, "{src:?}");
10104            }
10105        }
10106    }
10107}