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        //
5092        // Or past the last byte of content, if *that* is later: a fenced code
5093        // block's last row ends at its last line of code, and the closing
5094        // fence under it is markup with no row of its own — so counted from
5095        // the row, the fence's own line and terminator read as two blank lines
5096        // and opened a phantom empty paragraph whose offset was *inside* the
5097        // fence. Typing on it broke the fence. (A setext heading's underline
5098        // was the same shape.) Trailing whitespace is not content, so a line
5099        // of spaces still counts as the blank line it looks like.
5100        let last_end = self
5101            .rows
5102            .last()
5103            .map_or(hidden_end, |r| r.end_src)
5104            .max(self.stepped_over)
5105            .max(self.source.trim_end().len());
5106        if last_end >= self.source.len() {
5107            return;
5108        }
5109        // The first newline after the last content just terminates that line, so
5110        // a lone trailing `\n` (an ordinary file ending) opens no blank row. A
5111        // *second* newline opens an empty paragraph: render it the way a block
5112        // boundary is rendered — a blank spacer row, then the empty paragraph row
5113        // the caret rests on — so the just-pressed-Enter view already shows the
5114        // gap it will keep once text is typed, and typing doesn't shift the line
5115        // down. One row per trailing newline (each its own caret offset), the
5116        // last landing at the document end where the caret sits.
5117        let extra = self.source[last_end..].matches('\n').count();
5118        if extra < 2 {
5119            return;
5120        }
5121        for k in 1..=extra {
5122            self.rows.push(VRow {
5123                glyphs: Vec::new(),
5124                end_src: last_end + k,
5125                // As between two blocks: the first blank row is the gap that
5126                // closes the block above, not somewhere to type. Nothing follows
5127                // to need a gap of its own, though, so every row after it is a
5128                // real empty paragraph — the end of the document bounds the last
5129                // one the way a following block would. Preserve flow makes even
5130                // that first row navigable, as it does every blank line.
5131                decoration: !self.preserve_soft && k == 1,
5132                code: false,
5133                code_lang: None,
5134                directive: false,
5135                directive_label: None,
5136                media: None,
5137                task: None,
5138                leaf_directive: None,
5139                heading: None,
5140                align: None,
5141                line_height: None,
5142                // The one drawn row here is a block boundary like any other —
5143                // "rendered the way a block boundary is rendered" is the whole
5144                // point of it — so it says so, and a frontend spacing boundaries
5145                // spaces this one the same. The rows below it are navigable empty
5146                // paragraphs, not gaps.
5147                boundary: (!self.preserve_soft && k == 1).then_some(Boundary {
5148                    above,
5149                    below: BlockClass::Paragraph,
5150                }),
5151                mark_ends: Vec::new(),
5152                math: Vec::new(),
5153            });
5154        }
5155    }
5156}
5157
5158// ── display width ────────────────────────────────────────────────────────────
5159//
5160// Two things a row can be counted in, and they are not the same number:
5161//
5162//   *glyphs*, one per codepoint — how the text is stored here, and what an
5163//   index into `VRow::glyphs` means; and
5164//   *columns*, one per terminal cell — where the text is drawn, and what every
5165//   `col` in this crate means.
5166//
5167// `你` is one glyph in two columns. Counting columns with `glyphs.len()` (or,
5168// in the source view, `chars().count()`) is the same number only for the ASCII
5169// that most fixtures are written in, and drifts one cell per wide character
5170// everywhere else — the caret drawn a column short of the text it types into.
5171// Everything below converts between the two; nothing else should have to.
5172
5173/// The display width of `s` in terminal cells.
5174///
5175/// Measured per grapheme cluster, because that is the unit a surface advances
5176/// by: `👨‍👩‍👧` is five codepoints measuring 2 + 0 + 2 + 0 + 2 cells one at a
5177/// time, but the character they spell is drawn in 2. Both frontends already
5178/// measure it that way — ratatui asks `unicode-width` per cluster, and the GUI
5179/// asks its own text system — so the caret only lands where the text is if this
5180/// agrees with them.
5181pub fn text_width(s: &str) -> usize {
5182    UnicodeWidthStr::width(s)
5183}
5184
5185/// One grapheme cluster of a laid-out row: the glyphs that spell it, and the
5186/// cells it is drawn in.
5187///
5188/// The cluster, not the glyph, is what has a width. A row's glyphs are one per
5189/// codepoint, so an accented letter or an emoji is several of them drawn in one
5190/// character's worth of cells — the glyph that opens the cluster claims those
5191/// cells, and the ones continuing it are drawn *inside* them rather than beside
5192/// them. It's the same cluster the stop table is built on: the opening glyph is
5193/// the one a caret can rest on, and so the only one whose column it can be
5194/// drawn at.
5195struct Cluster {
5196    /// Index of the glyph that opens it.
5197    glyph: usize,
5198    /// The display column it starts at.
5199    col: usize,
5200    /// How many cells it is drawn in. Zero for a cluster with no width of its
5201    /// own (a lone joiner), which therefore sits at no column at all.
5202    cells: usize,
5203}
5204
5205/// Walk a row's glyphs as the clusters they spell, in column order.
5206fn clusters(glyphs: &[Glyph]) -> Vec<Cluster> {
5207    let text: String = glyphs.iter().map(|g| g.ch).collect();
5208    let mut out = Vec::new();
5209    let (mut glyph, mut col) = (0, 0);
5210    for cluster in text.graphemes(true) {
5211        let cells = text_width(cluster);
5212        out.push(Cluster { glyph, col, cells });
5213        // One glyph per codepoint, so a cluster spans exactly its own.
5214        glyph += cluster.chars().count();
5215        col += cells;
5216    }
5217    out
5218}
5219
5220/// The display width of a run of glyphs.
5221fn glyphs_width(glyphs: &[Glyph]) -> usize {
5222    clusters(glyphs).last().map_or(0, |c| c.col + c.cells)
5223}
5224
5225/// A cell's display width — the widest of its lines, since an in-cell `\n` break
5226/// splits it into several. Sizes the column that must hold every line.
5227fn cell_width(glyphs: &[Glyph]) -> usize {
5228    glyphs
5229        .split(|g| g.ch == '\n')
5230        .map(glyphs_width)
5231        .max()
5232        .unwrap_or(0)
5233}
5234
5235/// Whether a raw inline HTML tag is a line break (`<br>`, `<br/>`, `<br />`,
5236/// case-insensitively) — the one tag a table cell reads as an in-cell break.
5237fn is_br(text: Option<&str>) -> bool {
5238    let Some(t) = text else { return false };
5239    matches!(
5240        t.trim().to_ascii_lowercase().replace(' ', "").as_str(),
5241        "<br>" | "<br/>"
5242    )
5243}
5244
5245impl VRow {
5246    /// The row's width in display columns — and so the column of the caret
5247    /// placed past its last glyph, which is the rightmost column it can occupy.
5248    fn width(&self) -> usize {
5249        glyphs_width(&self.glyphs)
5250    }
5251
5252    /// The display column glyph `i` is drawn at. Glyphs continuing a cluster
5253    /// report the column of the glyph that opened it, since that is where they
5254    /// are drawn; none of them is ever a stop, so no caret is placed by it.
5255    fn col_of_glyph(&self, i: usize) -> usize {
5256        clusters(&self.glyphs)
5257            .iter()
5258            .rev()
5259            .find(|c| c.glyph <= i)
5260            .map_or(0, |c| c.col)
5261    }
5262
5263    /// The glyph drawn at display column `col`, or `None` past the row's last
5264    /// cell.
5265    ///
5266    /// A column landing on the *second* cell of a wide glyph resolves to that
5267    /// glyph: half a character is not a place to be, so clicking either cell of
5268    /// `你` means `你`, and the caret comes to rest at its start — the column it
5269    /// would be drawn at anyway. That rule is what makes the mapping invertible:
5270    /// every offset has one column, and every column has one offset.
5271    fn glyph_at_col(&self, col: usize) -> Option<usize> {
5272        clusters(&self.glyphs)
5273            .into_iter()
5274            .find(|c| col < c.col + c.cells)
5275            .map(|c| c.glyph)
5276    }
5277}
5278
5279// ── helpers ──────────────────────────────────────────────────────────────────
5280
5281/// The caret home inside an *empty* table cell (`col`, 0-based) whose node
5282/// `span` is `src` starting at byte `start`. twig gives an empty cell no
5283/// `content_span`, so its interior is read from the pipes: the home is one
5284/// space past the pipe that opens the cell — mimicking the `| ` padding a
5285/// filled cell has — and never at or past the pipe that closes it. So
5286/// `|  |  |` gives the two cells distinct, editable homes instead of both
5287/// collapsing onto the row's start.
5288///
5289/// Two shapes of span are read. A twig from 3.3.3 gave every cell of a row
5290/// the *row's* span, so the cell's own pipes are the `col`-th and
5291/// `col+1`-th unescaped `|` in it; a later twig spans a cell from the pipe
5292/// that opens it to the one that closes it, exclusive, so the span holds at
5293/// most that one pipe, at its start, and the closing one is the byte past
5294/// its end. The two are told apart by the pipes the span holds — a row's
5295/// span has several, or one that is not at its start.
5296fn empty_cell_offset(src: &str, start: usize, col: usize) -> usize {
5297    let bytes = src.as_bytes();
5298    let mut pipes = Vec::new();
5299    for (i, &b) in bytes.iter().enumerate() {
5300        if b == b'|' && (i == 0 || bytes[i - 1] != b'\\') {
5301            pipes.push(i);
5302        }
5303    }
5304    let whole_row = pipes.len() > 1 || pipes.first().is_some_and(|&i| i != 0);
5305    let (open, close) = if whole_row {
5306        (pipes.get(col).copied(), pipes.get(col + 1).copied())
5307    } else {
5308        (pipes.first().copied(), Some(src.len()))
5309    };
5310    match (open, close) {
5311        (Some(open), Some(close)) => {
5312            let lo = open + 1; // just inside the opening pipe
5313            let hi = close.saturating_sub(1); // just inside the closing pipe
5314            let inside = if hi < lo {
5315                lo
5316            } else {
5317                (open + 2).clamp(lo, hi)
5318            };
5319            start + inside
5320        }
5321        (Some(open), None) => start + open + 1,
5322        _ => start,
5323    }
5324}
5325
5326/// One laid-out table cell: its rendered text, the source range that text
5327/// occupies (`start`/`end` are the caret anchors decoration points at), and the
5328/// column alignment its padding honours.
5329///
5330/// `glyphs` is the cell's inline content *unwrapped* — the box-drawn rows wrap
5331/// it to a column width, but a frontend laying the grid out itself needs the
5332/// text before that decision was made.
5333#[derive(Clone)]
5334pub struct TableCell {
5335    pub glyphs: Vec<Glyph>,
5336    pub start: usize,
5337    pub end: usize,
5338    pub align: Alignment,
5339}
5340
5341/// One row of a table's grid, as the document spells it — not as it's drawn.
5342#[derive(Clone)]
5343pub struct TableRow {
5344    /// A header row: drawn bold, and ruled off from the body below it.
5345    pub head: bool,
5346    pub cells: Vec<TableCell>,
5347}
5348
5349/// A table's structure, published alongside the box-drawn rows that spell it.
5350///
5351/// The rows in [`VisualMap::rows`] are the *default monospace* picture of a
5352/// table: every border a `│`, every column a whole number of character cells.
5353/// That picture is exactly right on any monospace surface, and unfixable off one
5354/// — in a proportional font the `│`s of two rows land at different x and the grid
5355/// shears. So a frontend that draws its own geometry reads this instead: the
5356/// cells, their alignment, and which rows are the head, with no opinion about
5357/// how wide a column is or what a border looks like.
5358///
5359/// Both are always built. The TUI paints `rows` and ignores this; the GUI skips
5360/// `rows` for the span in `rows_span` and draws from here. They describe the
5361/// same cells, so the caret lands on the same offsets either way.
5362#[derive(Clone)]
5363pub struct TableInfo {
5364    /// The `VisualMap::rows` this table's picture occupies, borders included —
5365    /// what a frontend drawing its own table skips over.
5366    pub rows_span: Range<usize>,
5367    /// The end of the table node's source span, and the offset its trailing
5368    /// caret stop sits at — the one caret home past the last cell, held by the
5369    /// bottom border row's end. Typing there opens a paragraph under the table
5370    /// rather than joining the block; see `Doc::open_paragraph_at_block_edge`.
5371    pub end_src: usize,
5372    /// The block prefix every row of this table carries — a blockquote's `│ `
5373    /// gutter, a list item's indent. Empty for a table at the top level.
5374    ///
5375    /// A frontend drawing its own grid has to render this and start the table
5376    /// past it, exactly as the picture does; a table nested in a quote that
5377    /// draws flush at the left margin has left the quote.
5378    pub prefix: Vec<Glyph>,
5379    pub grid: Vec<TableRow>,
5380}
5381
5382/// A fenced or indented code block, named by the [`VisualMap::rows`] it occupies.
5383///
5384/// Unlike a table, the rows *are* the block's content — a frontend still paints
5385/// them, it just draws a border and a tinted background around the whole span
5386/// and lets the code inside scroll horizontally instead of wrapping. So this
5387/// carries only the row range; there's no structural alternative to the picture
5388/// the way [`TableInfo`] is one. Derived from [`VRow::code`] — see
5389/// [`code_block_spans`].
5390#[derive(Clone, Debug, PartialEq, Eq)]
5391pub struct CodeBlockInfo {
5392    /// The contiguous run of [`VisualMap::rows`] this code block spans, blank
5393    /// code lines included.
5394    pub rows_span: Range<usize>,
5395    /// The block's language, from a fenced block's info string — what a frontend
5396    /// paints as a small label on the box (`` ```rust `` → `Some("rust")`).
5397    /// `None` for a fence written without one, or an indented block. Editing it
5398    /// goes through [`crate::Doc::set_code_language`], which re-finds the fence
5399    /// in the AST, so this stays a display string.
5400    pub lang: Option<String>,
5401}
5402
5403/// A block-level image (`![alt](url)` on its own line), named by the single
5404/// [`VisualMap::rows`] row it occupies.
5405///
5406/// Like [`CodeBlockInfo`], the row *is* the block's default rendering — a plain
5407/// surface paints the `🖼 alt` placeholder glyphs as-is. An image-capable
5408/// frontend instead **skips the row in `rows_span`** and paints the resolved
5409/// picture there, exactly as it skips a [`TableInfo`]'s box-drawn rows. Derived
5410/// from [`VRow::media`] by [`media_spans`], so it survives the row reuse of
5411/// [`BlockCache`] and [`build_spliced`].
5412#[derive(Clone, Debug, PartialEq, Eq)]
5413pub struct MediaInfo {
5414    /// The [`VisualMap::rows`] rows this media's placeholder occupies — what a
5415    /// capable frontend replaces with the picture or player.
5416    pub rows_span: Range<usize>,
5417    /// Whether this is a picture, a movie, or a sound — which widget the
5418    /// frontend builds over [`rows_span`](MediaInfo::rows_span). A frontend that
5419    /// handles only some kinds leaves the rest as core's placeholder rows, which
5420    /// already read sensibly on their own.
5421    pub kind: MediaKind,
5422    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
5423    /// the AST. A frontend resolves a relative path against the document's own
5424    /// directory; core does no I/O. For a `<picture>` this is the `<img>`
5425    /// fallback — the source used when no [`sources`](MediaInfo::sources) media
5426    /// query matches (or the frontend has no theme). Empty when a `<video>`/
5427    /// `<audio>` carries no `src` and names its candidates in `<source>`s
5428    /// instead; [`resolve`](MediaInfo::resolve) already accounts for that.
5429    pub destination: String,
5430    /// The `<source>` alternatives in document order, or empty for a plain
5431    /// image. See [`MediaSource`]; a theme- or codec-aware frontend picks one and
5432    /// otherwise loads [`destination`](MediaInfo::destination).
5433    pub sources: Vec<MediaSource>,
5434    /// The media's alt text, flattened from its inline children (empty when it
5435    /// has none).
5436    pub alt: String,
5437    /// A `<video poster="…">`'s still frame, or empty when there is none — an
5438    /// image destination, resolved exactly as [`destination`] is.
5439    ///
5440    /// [`destination`]: MediaInfo::destination
5441    pub poster: String,
5442}
5443
5444/// One leaf directive (`::name{…}`) as a frontend sees it: which rows its
5445/// placeholder occupies, its type, and its attributes. A plain surface paints
5446/// the `⧉ name` placeholder glyphs as-is; a frontend that knows the host app's
5447/// vocabulary **skips the rows in `rows_span`** and paints the real thing there,
5448/// exactly as an image-capable one does with [`MediaInfo`]. Derived from
5449/// [`VRow::leaf_directive`] by [`directive_spans`].
5450///
5451/// Core resolves nothing here — it has no idea what an `embed` or a `toc` is,
5452/// and deliberately so: the directive vocabulary belongs to the app on top.
5453#[derive(Clone, Debug, PartialEq, Eq)]
5454pub struct DirectiveInfo {
5455    /// The [`VisualMap::rows`] rows this directive's placeholder occupies — the
5456    /// label row plus any blank fillers under it.
5457    pub rows_span: Range<usize>,
5458    /// The directive's type (`embed`, `toc`, `vis`), no leading colons.
5459    pub name: String,
5460    /// Its `{…}` attributes in source order; a bare one has a `None` value.
5461    pub attrs: Vec<(String, Option<String>)>,
5462    /// Its `[label]` text, flattened from its inline children (empty when it has
5463    /// none) — what the placeholder row shows.
5464    pub label: String,
5465}
5466
5467/// One formula as a frontend sees it: where its picture goes, and the TeX to
5468/// typeset for it. Two shapes, told apart by [`glyph`](MathInfo::glyph):
5469///
5470/// - An **inline atom** — `$E = mc^2$` in a line of prose — is one
5471///   [`Role::Math`] glyph on `row` at index `glyph`, standing for the whole
5472///   formula. A frontend that paints pictures in a line typesets the TeX at
5473///   the run's font size and draws the picture in the glyph's place, as wide
5474///   as the picture is and with the text baseline through it at its height —
5475///   a run delegate on Apple, an inline element on the web. The glyph is a
5476///   caret stop at the formula's start; the stop after it is the next glyph's.
5477/// - A **display block** — a paragraph holding nothing but `$$…$$` — is the
5478///   placeholder row (`∑ tex`, every glyph at the formula's start) plus the
5479///   blank fillers `rows_span` reserves under it, exactly a [`MediaInfo`]'s
5480///   shape. A frontend skips those rows and paints the picture there, centred
5481///   on the measure.
5482///
5483/// Either way the frontend supplies the *width*: core lays out in glyphs and
5484/// cannot know how wide a typeset formula is, which is why an inline atom is
5485/// one glyph and not a run of them. Only in a **column-wrapped** build does
5486/// that matter to the wrap: a terminal never asks for atoms (see
5487/// [`Surface::inline_pictures`]), and the web re-fits a row the picture
5488/// overflows.
5489///
5490/// A plain surface paints the glyphs as they are — `∑` for an atom, the
5491/// labelled row for a block — and needs none of this. Derived from
5492/// [`VRow::math`] by [`math_spans`], so it survives the row reuse of
5493/// [`BlockCache`] and [`build_spliced`].
5494#[derive(Clone, Debug, PartialEq, Eq)]
5495pub struct MathInfo {
5496    /// The [`VisualMap::rows`] rows this formula occupies: `row..row + 1` for
5497    /// an atom, the placeholder row and its fillers for a block.
5498    pub rows_span: Range<usize>,
5499    /// The row the atom glyph, or the block's placeholder label, is on.
5500    pub row: usize,
5501    /// The atom's index into that row's glyphs, or `None` for a block.
5502    pub glyph: Option<usize>,
5503    /// The TeX between the delimiters, verbatim.
5504    pub tex: String,
5505    /// Display style rather than text style — see [`MathMark::display`].
5506    pub display: bool,
5507    /// The formula's source start: where a click on its picture lands the
5508    /// caret, and the same offset every placeholder glyph carries.
5509    pub src: usize,
5510}
5511
5512impl DirectiveInfo {
5513    /// The value of attribute `key`, if it has one with a value. The convenience
5514    /// a frontend reaches for first (`info.attr("src")`), since almost every
5515    /// directive that draws as something real is pointed at by one attribute.
5516    pub fn attr(&self, key: &str) -> Option<&str> {
5517        self.attrs
5518            .iter()
5519            .find(|(k, _)| k == key)
5520            .and_then(|(_, v)| v.as_deref())
5521    }
5522}
5523
5524impl MediaInfo {
5525    /// The image URL to load under `scheme`: the first [`sources`] `<source>`
5526    /// whose media query matches, else the [`destination`] `<img>` fallback. The
5527    /// pick is a `<source>`'s first `srcset` URL or the destination — a frontend
5528    /// resolves whichever it gets against the document directory exactly as it
5529    /// resolves `destination`, and reserves/keys the picture under `destination`
5530    /// regardless, so a theme switch just re-picks without disturbing the layout.
5531    ///
5532    /// Only `prefers-color-scheme` is understood (that's what a light/dark banner
5533    /// uses); a `<source>` with any other media query is skipped, and one with no
5534    /// media at all always matches (an unconditional override). With no matching
5535    /// source — including every frontend that can't/doesn't theme and passes
5536    /// [`ColorScheme::Light`] to a dark-only picture — it's the plain `<img>`.
5537    ///
5538    /// [`sources`]: MediaInfo::sources
5539    /// [`destination`]: MediaInfo::destination
5540    pub fn resolve(&self, scheme: ColorScheme) -> &str {
5541        if let Some(url) = self
5542            .sources
5543            .iter()
5544            .find(|s| media_matches(&s.media, scheme))
5545            .and_then(|s| first_srcset_url(&s.srcset))
5546        {
5547            return url;
5548        }
5549        // A `<video>`/`<audio>` may carry no `src` of its own, naming its
5550        // candidates only in child `<source>`s — none of which matched above,
5551        // because a codec-typed `<source>` has no media query and core judges no
5552        // MIME types. Falling through to an empty destination would hand the
5553        // frontend nothing to load, so take the first candidate URL instead and
5554        // let the frontend reject it if it can't decode it. An `<img>` never
5555        // reaches this: its `src` is the picture.
5556        if self.destination.is_empty()
5557            && let Some(url) = self
5558                .sources
5559                .iter()
5560                .find_map(|s| first_srcset_url(&s.srcset))
5561        {
5562            return url;
5563        }
5564        &self.destination
5565    }
5566
5567    /// The **still picture** that stands for this media under `scheme`, for a
5568    /// frontend that can rasterize an image but not play a movie — a terminal, or
5569    /// a GUI still growing its player. `None` when there is no picture to draw,
5570    /// which is the honest answer for audio and for a poster-less video: the
5571    /// caller leaves core's labelled placeholder row, which already reads as
5572    /// *a thing that isn't text*.
5573    ///
5574    /// This exists so those frontends never hand a `.mp4` to an image decoder.
5575    /// That fails harmlessly today (a failed decode falls back to the same
5576    /// placeholder), but it spends a file read and a decode attempt per frame to
5577    /// arrive where this gets in one match.
5578    pub fn still(&self, scheme: ColorScheme) -> Option<&str> {
5579        match self.kind {
5580            MediaKind::Image => Some(self.resolve(scheme)),
5581            // A `poster` is an image destination, so it resolves the same way —
5582            // but it is named directly and has no `<source>` alternatives of its
5583            // own, so it needs no theme matching.
5584            MediaKind::Video if !self.poster.is_empty() => Some(&self.poster),
5585            MediaKind::Video | MediaKind::Audio => None,
5586        }
5587    }
5588}
5589
5590/// A frontend's active color scheme — what a `<picture>`'s `prefers-color-scheme`
5591/// `<source>`s are matched against by [`MediaInfo::resolve`]. A frontend with no
5592/// notion of theme passes [`Light`](ColorScheme::Light), the web's own default.
5593#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5594pub enum ColorScheme {
5595    Light,
5596    Dark,
5597}
5598
5599/// Whether a `<source media="…">` query applies under `scheme`. Empty media is
5600/// an unconditional `<source>` (always matches); otherwise only a
5601/// `prefers-color-scheme: dark|light` feature is understood — anything else
5602/// (a width query, `print`, …) doesn't match, so resolution falls through to the
5603/// next source or the `<img>`. Deliberately lax about the surrounding syntax
5604/// (`(prefers-color-scheme: dark)`, `screen and (prefers-color-scheme:dark)`):
5605/// it keys off the feature and its value, which is all the theme case needs.
5606fn media_matches(media: &str, scheme: ColorScheme) -> bool {
5607    let media = media.trim();
5608    if media.is_empty() {
5609        return true;
5610    }
5611    let lower = media.to_ascii_lowercase();
5612    let Some(after) = lower
5613        .split_once("prefers-color-scheme")
5614        .map(|(_, rest)| rest)
5615    else {
5616        return false;
5617    };
5618    // Skip the `:` and any spaces to reach the value word.
5619    let value = after.trim_start_matches([':', ' ', '\t']);
5620    let wanted = match scheme {
5621        ColorScheme::Light => "light",
5622        ColorScheme::Dark => "dark",
5623    };
5624    value.starts_with(wanted)
5625}
5626
5627/// The first URL in a `srcset`: its first comma-separated candidate, before any
5628/// `1x`/`2x`/width descriptor. The theme case only ever puts one URL per
5629/// `<source>`, so the first candidate is the picture.
5630fn first_srcset_url(srcset: &str) -> Option<&str> {
5631    let first = srcset.split(',').next()?.trim();
5632    first.split_whitespace().next().filter(|u| !u.is_empty())
5633}
5634
5635/// The narrowest a column may be squeezed. Below a few characters a column
5636/// stops carrying text and just shreds it one letter per line, which is worse
5637/// than letting the grid run wide.
5638const MIN_COL_WIDTH: usize = 3;
5639
5640/// Shrink `widths` until the grid fits `avail` screen columns, taking from the
5641/// widest column each time so the loss is shared out rather than falling on
5642/// whichever column happens to be last. No column goes below
5643/// [`MIN_COL_WIDTH`]; a table with more columns than the surface has room for
5644/// still overflows, which is the honest outcome — there's nothing left to give.
5645fn fit_widths(widths: &mut [usize], avail: usize) {
5646    // Chrome: each column is its content plus a gutter either side, and every
5647    // column is closed by a `│` — with one more opening the row.
5648    let budget = avail.saturating_sub(3 * widths.len() + 1);
5649    while widths.iter().sum::<usize>() > budget {
5650        let Some(w) = widths.iter_mut().filter(|w| **w > MIN_COL_WIDTH).max() else {
5651            return;
5652        };
5653        *w -= 1;
5654    }
5655}
5656
5657/// Word-wrap `glyphs` into lines of at most `width` columns, hard-breaking any
5658/// single word too long to fit.
5659///
5660/// Unlike a paragraph — where an overlong word just trails off the end of the
5661/// line — a table column is a hard boundary: a glyph past it lands on top of
5662/// the border, or on the next cell. So the width here is a promise, and a word
5663/// that won't keep it is broken.
5664///
5665/// The space at a break is dropped rather than hung past the edge. Its offset
5666/// isn't lost: the caller gives every line an end stop just past its last
5667/// glyph, which is exactly where that space was.
5668///
5669/// `width` is in display columns, and a break only ever falls between grapheme
5670/// clusters. Both matter to more than the picture: the caller anchors each
5671/// line's end stop just past its last glyph, so a line cut mid-cluster would
5672/// put a caret stop inside a character — reachable by Down or a click, and the
5673/// next Backspace would take the cluster apart from the middle.
5674///
5675/// An explicit in-cell break (a `\n` glyph, from a `<br>`) is a hard boundary:
5676/// each run between the breaks wraps on its own and the results stack. The break
5677/// glyphs are dropped — the caller's per-line end stop already sits exactly where
5678/// each break was, so no offset is lost.
5679fn wrap_glyphs(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
5680    if glyphs.iter().any(|g| g.ch == '\n') {
5681        return glyphs
5682            .split(|g| g.ch == '\n')
5683            .flat_map(|seg| wrap_segment(seg, width))
5684            .collect();
5685    }
5686    wrap_segment(glyphs, width)
5687}
5688
5689/// [`wrap_glyphs`] for a run with no explicit breaks — the word-wrap proper.
5690fn wrap_segment(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
5691    let width = width.max(1);
5692    // Words are maximal non-space runs, each carrying the space that followed it
5693    // — which survives only if the next word joins it on this line.
5694    let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
5695    let mut word: Vec<Glyph> = Vec::new();
5696    for g in glyphs {
5697        if g.ch == ' ' {
5698            words.push((std::mem::take(&mut word), Some(g.clone())));
5699        } else {
5700            word.push(g.clone());
5701        }
5702    }
5703    if !word.is_empty() {
5704        words.push((word, None));
5705    }
5706
5707    let mut lines: Vec<Vec<Glyph>> = Vec::new();
5708    let mut line: Vec<Glyph> = Vec::new();
5709    let mut used = 0usize;
5710    let mut gap: Option<Glyph> = None;
5711    for (word, space) in words {
5712        for chunk in hard_break(&word, width) {
5713            let sep = gap.is_some() as usize;
5714            let cells = glyphs_width(chunk);
5715            if !line.is_empty() && used + sep + cells > width {
5716                lines.push(std::mem::take(&mut line));
5717                used = 0;
5718                gap = None; // the break swallows the space
5719            }
5720            if let Some(sp) = gap.take() {
5721                line.push(sp);
5722                used += 1;
5723            }
5724            line.extend_from_slice(chunk);
5725            used += cells;
5726        }
5727        gap = space;
5728    }
5729    // An empty cell is still one (empty) line — it has an end the caret can
5730    // sit at, which is how you type into it.
5731    if !line.is_empty() || lines.is_empty() {
5732        lines.push(line);
5733    }
5734    lines
5735}
5736
5737/// Break a single word into pieces of at most `width` columns, cutting only
5738/// between grapheme clusters — the replacement for slicing it into fixed runs
5739/// of glyphs, which measures a wide character as one column and can cut an
5740/// emoji in half.
5741///
5742/// A cluster wider than the whole column still gets a piece to itself: there is
5743/// nowhere legal to cut it, and overflowing by a cell is better than splitting a
5744/// character. An empty word yields no pieces at all, which is what keeps a
5745/// double space from opening a line of its own.
5746fn hard_break(word: &[Glyph], width: usize) -> Vec<&[Glyph]> {
5747    let mut out = Vec::new();
5748    if word.is_empty() {
5749        return out;
5750    }
5751    let (mut start, mut used) = (0usize, 0usize);
5752    for c in clusters(word) {
5753        if used > 0 && used + c.cells > width {
5754            out.push(&word[start..c.glyph]);
5755            start = c.glyph;
5756            used = 0;
5757        }
5758        used += c.cells;
5759    }
5760    out.push(&word[start..]);
5761    out
5762}
5763
5764/// A table rule spanning `widths`, e.g. `┌──────┬─────┐`. Each column is its
5765/// content width plus the one-space gutter on either side.
5766fn rule_text(widths: &[usize], left: char, mid: char, right: char) -> String {
5767    let mut s = String::new();
5768    s.push(left);
5769    for (i, w) in widths.iter().enumerate() {
5770        if i > 0 {
5771            s.push(mid);
5772        }
5773        for _ in 0..w + 2 {
5774            s.push('─');
5775        }
5776    }
5777    s.push(right);
5778    s
5779}
5780
5781/// Push real document text: each glyph maps to its own source byte, and the one
5782/// that opens a grapheme cluster is the caret stop for the whole cluster.
5783///
5784/// Per cluster rather than per codepoint because a cluster is the character the
5785/// user sees, and it's the unit backspace and delete already step by. A stop
5786/// inside 👨‍👩‍👧 — five codepoints strung together with joiners — is a caret
5787/// parked in the middle of a character: one press of Right lands there, and the
5788/// next Backspace severs a joiner from what it joined, leaving a dangling ZWJ in
5789/// the source. The rest of the cluster still gets its glyph (it has to be
5790/// drawn); it just isn't somewhere to stand.
5791fn push_text(out: &mut Vec<Glyph>, text: &str, base_src: usize, style: Style) {
5792    for (gi, cluster) in text.grapheme_indices(true) {
5793        for (ci, ch) in cluster.char_indices() {
5794            out.push(Glyph {
5795                ch,
5796                style,
5797                src: base_src + gi + ci,
5798                stop: ci == 0,
5799            });
5800        }
5801    }
5802}
5803
5804/// [`push_text`] for one line of a highlighted code block: the same glyphs at
5805/// the same offsets, each additionally carrying the [`Token`] of the span it
5806/// falls in — `spans` being the line's entry from [`code_tokens`], ascending
5807/// byte ranges *into `text`*. A byte between spans keeps `style` as it is.
5808///
5809/// Offsets are what matters here: a token changes how a glyph is painted and
5810/// nothing about where it is or which source byte it stands on, so a caret
5811/// walks a highlighted block exactly as it walks an unhighlighted one.
5812fn push_code_text(
5813    out: &mut Vec<Glyph>,
5814    text: &str,
5815    base_src: usize,
5816    style: Style,
5817    spans: &[(Range<usize>, Token)],
5818) {
5819    let mut spans = spans.iter().peekable();
5820    for (gi, cluster) in text.grapheme_indices(true) {
5821        // Spans are ascending, so the one covering this cluster's first byte
5822        // is at or after the one that covered the last; step past those ended.
5823        while spans.peek().is_some_and(|(r, _)| r.end <= gi) {
5824            spans.next();
5825        }
5826        let token = spans
5827            .peek()
5828            .filter(|(r, _)| r.contains(&gi))
5829            .map(|(_, t)| *t);
5830        // A cluster is classed whole, by its first byte: a grammar that split
5831        // an emoji's scalars between two tokens would otherwise split the
5832        // glyph, and no grammar means to.
5833        let style = style.token(token);
5834        for (ci, ch) in cluster.char_indices() {
5835            out.push(Glyph {
5836                ch,
5837                style,
5838                src: base_src + gi + ci,
5839                stop: ci == 0,
5840            });
5841        }
5842    }
5843}
5844
5845/// One line's highlighting — `crate::syntax::LineTokens`, spelled here so the
5846/// shape exists whether or not the feature that fills it does.
5847type LineTokens = Vec<(Range<usize>, Token)>;
5848
5849/// The syntax highlighting for a code block's lines, or `None` when the fence's
5850/// language is not one the grammars know. Without the `syntax` feature nothing
5851/// is known, and every code glyph draws in the plain code colour.
5852#[cfg(feature = "syntax")]
5853fn code_tokens(lang: &str, lines: &[&str]) -> Option<Vec<LineTokens>> {
5854    crate::syntax::highlight(lang, lines)
5855}
5856
5857#[cfg(not(feature = "syntax"))]
5858fn code_tokens(_lang: &str, _lines: &[&str]) -> Option<Vec<LineTokens>> {
5859    None
5860}
5861
5862/// Emit an inline `str`/`smart_punctuation` run, mapping every visible char back
5863/// to its *true* source byte even when the source carries backslash escapes the
5864/// parsed `text` dropped (`\*` → `*`). The naive `span.start + text_offset`
5865/// mapping [`push_text`] uses drifts by one byte after each escape, so a caret or
5866/// click past an escaped `*` would land on the wrong character; walking the text
5867/// against its source keeps them aligned, and the hidden escape backslash gets no
5868/// glyph of its own (it is a spelling artefact, not something the caret lands on).
5869fn push_escaped_text(
5870    out: &mut Vec<Glyph>,
5871    text: &str,
5872    span: Range<usize>,
5873    source: &str,
5874    style: Style,
5875) {
5876    let end = span.end.min(source.len());
5877    let src = source.get(span.start..end).unwrap_or("");
5878    // Fast path — no dropped bytes, so text and source align 1:1 (the common
5879    // case: prose with no escapes). Byte lengths equal ⇒ no backslash was eaten.
5880    if src.len() == text.len() {
5881        push_text(out, text, span.start, style);
5882        return;
5883    }
5884    // Slow path: some `\` was consumed. Walk char-by-char, skipping a backslash
5885    // in the source exactly when it escapes the next visible char (a real escape),
5886    // never when it is a literal backslash the parse kept (that case has equal
5887    // lengths and takes the fast path above).
5888    let sb = src.as_bytes();
5889    let mut si = 0usize;
5890    'text: for (_, cluster) in text.grapheme_indices(true) {
5891        for (ci, ch) in cluster.char_indices() {
5892            // The text outlasted the source it is being mapped onto. In a
5893            // consistent document that cannot happen on this path: the slow path
5894            // is only entered when the two lengths differ, and everything that
5895            // makes them differ makes the *source* the longer one — an escape
5896            // backslash the parse ate, or source folded into a neighbouring node.
5897            // A `smart_punctuation` node reports its canonical ASCII spelling
5898            // (`--`, `...`, `"`), which is never longer than what was written.
5899            //
5900            // So reaching here means `span` was measured against a document that
5901            // `source` is no longer, and there is no honest offset left to give
5902            // the remaining characters. Stop: the row comes out short, which is
5903            // a wrong picture of a document that is already inconsistent. The
5904            // alternative was `si` stepping past the end and the slice below
5905            // panicking — which is what it did, in a paint loop.
5906            if si >= sb.len() {
5907                break 'text;
5908            }
5909            // Advance to the source character this one came from, stepping over
5910            // whatever the parse dropped on the way. An escape backslash is the
5911            // common case, but not the only one: a span can cover source that
5912            // was folded into a neighbouring node (smart punctuation next to a
5913            // bracket gives `text: "]"` over a source span of `"…]"`). Advancing
5914            // by the *text* character's length assumed escapes were the only
5915            // divergence, so one dropped multi-byte character desynchronized
5916            // every glyph after it — placing `]` inside the `…` before it.
5917            while si < sb.len() && !src[si..].starts_with(ch) {
5918                si += src[si..].chars().next().map_or(1, char::len_utf8);
5919            }
5920            out.push(Glyph {
5921                ch,
5922                style,
5923                src: span.start + si.min(src.len()),
5924                stop: ci == 0,
5925            });
5926            si += src[si..]
5927                .chars()
5928                .next()
5929                .map_or(ch.len_utf8(), char::len_utf8);
5930        }
5931    }
5932}
5933
5934/// Build synthetic decoration glyphs (a bullet, a gutter) all pointing at `src`,
5935/// each carrying `role` so the frontend can style it (`Role::Body` for plain
5936/// padding). Synthetic glyphs are never caret stops — they share one offset, so
5937/// the caret steps over them (a click still lands at `src`).
5938fn synth(text: &str, role: Role, src: usize) -> Vec<Glyph> {
5939    let style = Style::default().role(role);
5940    text.chars()
5941        .map(|ch| Glyph {
5942            ch,
5943            style,
5944            src,
5945            stop: false,
5946        })
5947        .collect()
5948}
5949
5950fn concat(a: &[Glyph], b: &[Glyph]) -> Vec<Glyph> {
5951    let mut v = a.to_vec();
5952    v.extend_from_slice(b);
5953    v
5954}
5955
5956/// The columns a row's prefix (a bullet, a quote gutter, an indent) takes up
5957/// before the text it introduces — what the wrap budget has left to spend.
5958fn prefix_width(prefix: &[Glyph]) -> usize {
5959    glyphs_width(prefix)
5960}
5961
5962/// The label shown for an image with no alt text: the final path segment of its
5963/// destination (`img/cat.png` → `cat.png`), the whole destination when it has no
5964/// separator, and `"image"` when it's empty. A `data:` URI (which has no useful
5965/// tail) shows its scheme so the placeholder isn't a wall of base64.
5966fn media_label(dest: &str) -> String {
5967    if dest.is_empty() {
5968        return "image".to_string();
5969    }
5970    if dest.starts_with("data:") {
5971        return "data:…".to_string();
5972    }
5973    // Trim a query/fragment so a URL's `?v=2#frag` doesn't ride along.
5974    let clean = dest.split(['?', '#']).next().unwrap_or(dest);
5975    let tail = clean
5976        .trim_end_matches('/')
5977        .rsplit(['/', '\\'])
5978        .next()
5979        .unwrap_or(clean);
5980    if tail.is_empty() {
5981        dest.to_string()
5982    } else {
5983        tail.to_string()
5984    }
5985}
5986
5987/// A directive's attributes read as a human label — what a frontend puts on a
5988/// container's tinted panel, and what an attribute-bearing inline directive
5989/// shows in its chip.
5990///
5991/// Reads BOTH conventions diaryx content actually uses: twig's own dot-prefixed
5992/// classes (`{.public .family}`, arriving as one combined `class` attr) and bare
5993/// pandoc-style words with no leading dot (`{public family}` — what
5994/// `diaryx_core::visibility`'s publish-time filter and apps/web's directive
5995/// serializer both write, and which twig parses as one valueless attribute
5996/// each). Reading only `.class` would leave every *existing* diaryx `:::vis{…}`
5997/// block unlabeled. A `key=value` attr is configuration rather than a name, so
5998/// it contributes nothing. `None` when nothing readable is left.
5999fn directive_attr_label(attrs: &[(String, Option<String>)]) -> Option<String> {
6000    let mut parts: Vec<String> = Vec::new();
6001    for (k, v) in attrs {
6002        if k == "class" {
6003            if let Some(v) = v
6004                && !v.is_empty()
6005            {
6006                parts.push(v.clone());
6007            }
6008        } else if v.as_deref().unwrap_or("").is_empty() {
6009            parts.push(k.clone());
6010        }
6011    }
6012    (!parts.is_empty()).then(|| parts.join(" "))
6013}
6014
6015fn heading_style(level: u32) -> Style {
6016    // Just the role — a frontend decides how a heading of this level *looks*
6017    // (the terminal cycles a color and bolds it, the GUI scales the font). The
6018    // author wrote no emphasis here, so core records none. `level as u8` is safe:
6019    // Markdown/Djot cap headings at 6.
6020    Style::default().role(Role::Heading(level.min(255) as u8))
6021}
6022
6023/// Is this `container` node a *directive* (`:::note{…}`, `::embed{…}`,
6024/// `:vis[…]`) rather than an HTML element (`<video>`, `<picture>`, `<div>`)?
6025///
6026/// twig 2.8 folded `div`/`span`/`directive`/`element` into one `container` kind,
6027/// and left nothing that separated them: `kind`, `name` and `directive_form` all
6028/// agree, field for field, on an HTML `<div>` and a Markdown `:::div`. Leaf
6029/// answered it by sniffing the span for whichever of `:` or `<` came first.
6030/// twig 3.0 records the answer at parse time as [`ContainerOrigin`], so this is
6031/// now the parser's own knowledge rather than a guess rebuilt from the bytes it
6032/// consumed.
6033pub(crate) fn container_is_directive(node: &FlatNode) -> bool {
6034    node.origin == Some(ContainerOrigin::Directive)
6035}
6036
6037/// The tag a `container` node carries when it is an HTML element rather than a
6038/// directive — `Some("video")` for a promoted `<video>`, `None` for a `:::note`
6039/// or for any node that is not a container at all.
6040pub(crate) fn element_tag(node: &FlatNode) -> Option<&str> {
6041    (node.origin == Some(ContainerOrigin::Element))
6042        .then_some(node.name.as_deref())
6043        .flatten()
6044}
6045
6046/// A leaf directive's name and whatever attributes are not part of spelling
6047/// it — the two things a [`DirectiveMark`] carries, which twig hands back
6048/// differently per format and which a frontend must not be able to tell apart.
6049///
6050/// Markdown's `::page-break` is a `Leaf`-form directive *named* `page-break`
6051/// with no attributes, and this returns it verbatim. Djot has no leaf form:
6052/// `insert_directive` writes the same document as an empty `::: page-break`
6053/// fence, whose container is anonymous (a djot div carries no name) and whose
6054/// name arrives as the fence's one class. So where the node has no name of its
6055/// own the first `class` token *is* the name, and whatever else the class said
6056/// — an author's `::: page-break {.wide}` — stays an attribute.
6057fn leaf_directive_identity(node: &FlatNode) -> (String, Vec<(String, Option<String>)>) {
6058    let named = node.name.clone().unwrap_or_default();
6059    if !named.is_empty() {
6060        return (named, node.attrs.clone());
6061    }
6062    let class = node
6063        .attrs
6064        .iter()
6065        .find(|(k, _)| k == "class")
6066        .and_then(|(_, v)| v.as_deref())
6067        .unwrap_or_default();
6068    let mut tokens = class.split_whitespace();
6069    let Some(name) = tokens.next().map(str::to_string) else {
6070        return (named, node.attrs.clone());
6071    };
6072    let rest = tokens.collect::<Vec<_>>().join(" ");
6073    let attrs = node
6074        .attrs
6075        .iter()
6076        .filter_map(|(k, v)| {
6077            if k != "class" {
6078                return Some((k.clone(), v.clone()));
6079            }
6080            (!rest.is_empty()).then(|| (k.clone(), Some(rest.clone())))
6081        })
6082        .collect();
6083    (name, attrs)
6084}
6085
6086/// Is this inline `container` an **attributed span** — the node leaf's run-level
6087/// vocabulary rides — rather than a named directive?
6088///
6089/// The four formats spell one span four ways and twig hands the name back for
6090/// two of them: HTML's and Markdown's `<span …>` arrive named `span` with
6091/// `Element` origin, while djot's `[text]{…}` and AsciiDoc's `[.a]#text#`
6092/// arrive anonymous (an empty name) with `Directive` origin. All four are the
6093/// same node to `wrap_range_attrs`, which is what writes them, so they are the
6094/// same node here.
6095///
6096/// A *named* directive is not one, whatever its name: a Markdown `:span[…]{…}`
6097/// is a directive the parser read as a directive, twig's own
6098/// `wrap_range_attrs` says so, and it keeps the handling it has.
6099///
6100/// **Anonymous is not enough**, and the form is what finishes the question:
6101/// a djot fenced div (`{.center}` / `:::` / … / `:::`) is anonymous too, with
6102/// the same `Directive` origin, and is a *block* — `Container` form against the
6103/// span's `Text`. Reading one as a span made every gesture and every query lie
6104/// about it: `set_text_color` over a word inside such a div copied the whole
6105/// div's attribute set — its `id` along with the rest — onto the new span, and
6106/// `alignment_at_caret` reported the div's `.center` as a *run's* answer while
6107/// the walker drew none. So the anonymous arm asks the form [`is_inline`] asks.
6108pub(crate) fn is_run_span(node: &FlatNode) -> bool {
6109    if node.kind != Kind::Container {
6110        return false;
6111    }
6112    match node.name.as_deref() {
6113        None | Some("") => node.directive_form == Some(DirectiveForm::Text),
6114        Some("span") => node.origin == Some(ContainerOrigin::Element),
6115        Some(_) => false,
6116    }
6117}
6118
6119/// `base` with an attributed span's three run-level keys written over it — the
6120/// nearest-wins fold [`is_run_span`] describes, for one span. `faces` is the
6121/// build's intern table, as it is for [`Presentation::under`].
6122fn run_style(node: &FlatNode, base: Style, faces: &RefCell<FaceTable>) -> Style {
6123    Style {
6124        size: FontSize::from_attrs(&node.attrs).or(base.size),
6125        font: faces
6126            .borrow_mut()
6127            .face_from_attrs(&node.attrs)
6128            .or(base.font),
6129        color: TextColor::from_attrs(&node.attrs).or(base.color),
6130        ..base
6131    }
6132}
6133
6134pub(crate) fn is_inline(node: &FlatNode) -> bool {
6135    // A directive is inline only in its `text` form (`:name[label]{…}`); the
6136    // `leaf` and `container` forms are blocks. All three report the same `kind`,
6137    // so the form is the only thing telling them apart — and getting it wrong
6138    // costs a whole paragraph: a text directive misread as a block makes its
6139    // paragraph fail the "all children inline" test in `block`, and the line is
6140    // then walked as a container of blocks, rendering as empty rows with no
6141    // caret home at all.
6142    //
6143    // An HTML element shares the `container` kind, and twig sets the same form
6144    // on the two tags the lightweight formats have a generic spelling for: a
6145    // `<span>` is `Text` and a `<div>` is `Container`, while a `<video>` or a
6146    // `<picture>` has no form at all. So the form answers for an element as it
6147    // answers for a directive, and the origin is not consulted — which is what
6148    // makes a `<span …>` inside a paragraph an inline node.
6149    //
6150    // It has to. `wrap_range_attrs` spells an attributed run as exactly that
6151    // span in Markdown and HTML, and a paragraph holding one whose kids were
6152    // not all inline failed the test below and was walked as a container of
6153    // blocks: the text either side of the span rendered as nothing at all.
6154    if node.kind == Kind::Container {
6155        return node.directive_form == Some(DirectiveForm::Text);
6156    }
6157    is_inline_kind(&node.kind)
6158}
6159
6160/// [`is_inline`] by kind alone — for the ancestor walks, whose `QueryMatch`es
6161/// carry no `directive_form`. It answers `false` for every directive, which its
6162/// callers must (and do) reconcile: they pair it with `is_block_container`,
6163/// which claims every directive, so the pair's verdict is the same one a form
6164/// would have given. Anything looking at a *directive itself* wants [`is_inline`]
6165/// and a real node.
6166pub(crate) fn is_inline_kind(kind: &Kind) -> bool {
6167    matches!(
6168        kind,
6169        Kind::Str
6170            | Kind::SoftBreak
6171            | Kind::HardBreak
6172            | Kind::NonBreakingSpace
6173            | Kind::Emph
6174            | Kind::Strong
6175            | Kind::Mark
6176            | Kind::Insert
6177            | Kind::Delete
6178            | Kind::Verbatim
6179            | Kind::InlineMath
6180            | Kind::DisplayMath
6181            | Kind::Url
6182            | Kind::Email
6183            | Kind::Link
6184            | Kind::Image
6185            | Kind::SmartPunctuation
6186            | Kind::Superscript
6187            | Kind::Subscript
6188            | Kind::FootnoteReference
6189    )
6190}
6191
6192/// Assert two maps are identical down to every glyph, stop, and table span — the
6193/// contract `build_cached` and `build_spliced` must hold against `build`. Lives
6194/// at module scope (not in `mod tests`) so the Doc-driven differential test in
6195/// `doc.rs` can reach it and the private `stops` field it compares.
6196#[cfg(test)]
6197pub(crate) fn assert_maps_eq(a: &VisualMap, b: &VisualMap, ctx: &str) {
6198    assert_eq!(a.rows.len(), b.rows.len(), "row count ({ctx})");
6199    for (i, (ra, rb)) in a.rows.iter().zip(&b.rows).enumerate() {
6200        assert_eq!(ra.end_src, rb.end_src, "row {i} end_src ({ctx})");
6201        assert_eq!(ra.decoration, rb.decoration, "row {i} decoration ({ctx})");
6202        // The incremental walk labels a boundary from a query match's kind
6203        // string and the whole-arena walk from a `FlatNode`'s; this is what says
6204        // the two doors reach the same answer.
6205        assert_eq!(ra.boundary, rb.boundary, "row {i} boundary ({ctx})");
6206        assert_eq!(ra.code, rb.code, "row {i} code ({ctx})");
6207        assert_eq!(ra.code_lang, rb.code_lang, "row {i} code_lang ({ctx})");
6208        assert_eq!(ra.align, rb.align, "row {i} align ({ctx})");
6209        assert_eq!(
6210            ra.line_height, rb.line_height,
6211            "row {i} line_height ({ctx})"
6212        );
6213        assert_eq!(
6214            ra.glyphs.len(),
6215            rb.glyphs.len(),
6216            "row {i} glyph count ({ctx})"
6217        );
6218        for (j, (ga, gb)) in ra.glyphs.iter().zip(&rb.glyphs).enumerate() {
6219            assert_eq!(
6220                (ga.ch, ga.src, ga.stop, ga.style),
6221                (gb.ch, gb.src, gb.stop, gb.style),
6222                "row {i} glyph {j} ({ctx})"
6223            );
6224        }
6225    }
6226    assert_eq!(a.content_start, b.content_start, "content_start ({ctx})");
6227    assert_eq!(a.stops, b.stops, "stops ({ctx})");
6228    assert_eq!(a.mark_ends, b.mark_ends, "mark_ends ({ctx})");
6229    assert_eq!(a.tables.len(), b.tables.len(), "table count ({ctx})");
6230    for (i, (ta, tb)) in a.tables.iter().zip(&b.tables).enumerate() {
6231        assert_eq!(ta.rows_span, tb.rows_span, "table {i} rows_span ({ctx})");
6232        assert_eq!(ta.end_src, tb.end_src, "table {i} end_src ({ctx})");
6233    }
6234    assert_eq!(a.code_blocks, b.code_blocks, "code_blocks ({ctx})");
6235    assert_eq!(a.media, b.media, "images ({ctx})");
6236}
6237
6238#[cfg(test)]
6239mod tests {
6240    use super::*;
6241    use crate::style::{FontFamily, LineSpacing, SizeStep};
6242    use twig::{Editor, Format, NodeId};
6243
6244    fn map(src: &str) -> VisualMap {
6245        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6246        build_t(&ed.nodes().unwrap(), src, Some(80))
6247    }
6248
6249    /// [`map`] over a Djot source. Djot is the format that spells superscript
6250    /// and subscript at all — Markdown has no syntax for either.
6251    fn map_djot(src: &str) -> VisualMap {
6252        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
6253        build_t(&ed.nodes().unwrap(), src, Some(80))
6254    }
6255
6256    /// The baseline every glyph spelling `ch` was built with, in row order —
6257    /// how a test reads a raised or lowered run off the map without caring
6258    /// which row it landed on.
6259    fn baselines_of(m: &VisualMap, ch: char) -> Vec<Baseline> {
6260        m.rows
6261            .iter()
6262            .flat_map(|r| r.glyphs.iter())
6263            .filter(|g| g.ch == ch)
6264            .map(|g| g.style.baseline)
6265            .collect()
6266    }
6267
6268    /// [`map`] at a chosen wrap width.
6269    fn map_at(src: &str, wrap: Option<usize>) -> VisualMap {
6270        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6271        build_t(&ed.nodes().unwrap(), src, wrap)
6272    }
6273
6274    /// [`map`], but with twig's `directives` extension on (off by twig's own
6275    /// default) — the `:::name{.class}` fenced-div containers leaf-core's
6276    /// `"directive"` wysiwyg arm renders.
6277    fn map_directives(src: &str) -> VisualMap {
6278        let mut ed = Editor::new_ext(
6279            src.as_bytes(),
6280            Format::Markdown,
6281            twig::MarkdownExtensions {
6282                directives: true,
6283                ..Default::default()
6284            },
6285        )
6286        .unwrap();
6287        build_t(&ed.nodes().unwrap(), src, Some(80))
6288    }
6289
6290    /// [`map`] in `format`, parsed the way every leaf document is — the
6291    /// extensions [`crate::doc::parse_extensions`] turns on, which is what
6292    /// pairs a Markdown `<div …>` with its `</div>` into a container and makes
6293    /// `::page-break` a directive rather than a paragraph of colons.
6294    fn map_leaf(src: &str, format: Format) -> VisualMap {
6295        let mut ed =
6296            Editor::new_ext(src.as_bytes(), format, crate::doc::parse_extensions()).unwrap();
6297        build_t(&ed.nodes().unwrap(), src, Some(80))
6298    }
6299
6300    /// The alignment and line spacing of every row that draws text, in order —
6301    /// how a test reads a block property off the map.
6302    fn line_facts(m: &VisualMap) -> Vec<(Option<Align>, Option<LineHeight>)> {
6303        m.rows
6304            .iter()
6305            .filter(|r| r.glyphs.iter().any(|g| !g.ch.is_whitespace()))
6306            .map(|r| (r.align, r.line_height))
6307            .collect()
6308    }
6309
6310    /// The style of the glyph spelling `ch`, first occurrence — how a test reads
6311    /// a run property off the map.
6312    fn style_of(m: &VisualMap, ch: char) -> Style {
6313        m.rows
6314            .iter()
6315            .flat_map(|r| r.glyphs.iter())
6316            .find(|g| g.ch == ch)
6317            .unwrap_or_else(|| panic!("no glyph {ch:?} in the map"))
6318            .style
6319    }
6320
6321    /// [`map`] with soft breaks preserved (`LineFlow::Preserve`).
6322    fn map_preserve(src: &str, wrap: Option<usize>) -> VisualMap {
6323        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6324        build(
6325            &ed.nodes().unwrap(),
6326            src,
6327            wrap,
6328            true,
6329            &Surface::default(),
6330            None,
6331        )
6332    }
6333
6334    /// The cache-free reference [`build`], with no per-image height overrides —
6335    /// every block image stays its default one-row placeholder. The tests that
6336    /// need a taller image drive it through [`crate::Doc::set_media_rows`] instead.
6337    fn build_t(nodes: &[FlatNode], src: &str, wrap: Option<usize>) -> VisualMap {
6338        build(nodes, src, wrap, false, &Surface::default(), None)
6339    }
6340
6341    /// An arena and a string that disagree — spans reaching past the source they
6342    /// are built against.
6343    ///
6344    /// [`crate::Doc`] keeps the two in step, so this is a "cannot happen" that
6345    /// nonetheless *did*: `examples/bench` timed a loop of `edit_range` and then
6346    /// went on handing the grown editor's spans to a builder holding the string
6347    /// from before it, and every run ended in a slice panic rather than a
6348    /// number. `push_escaped_text` was already written to survive the mismatch —
6349    /// it clamps the span's end and falls back to an empty slice — and this is
6350    /// the half of that intent it did not carry through.
6351    ///
6352    /// Rendering the wrong thing is the acceptable answer here; panicking in a
6353    /// paint loop is not.
6354    #[test]
6355    fn a_source_shorter_than_the_arena_built_over_it_renders_rather_than_panicking() {
6356        // An escape puts the run on `push_escaped_text`'s slow path — the fast
6357        // path is a length comparison that a truncated source fails anyway.
6358        let src = "alpha \\*beta\\* gamma delta epsilon\n";
6359        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6360        let nodes = ed.nodes().unwrap();
6361
6362        // Every truncation of it, so the cut lands before, inside and after the
6363        // escaped run rather than only where one hand-picked index put it.
6364        for cut in 0..=src.len() {
6365            if !src.is_char_boundary(cut) {
6366                continue;
6367            }
6368            let map = build_t(&nodes, &src[..cut], Some(80));
6369            for row in &map.rows {
6370                for g in &row.glyphs {
6371                    assert!(
6372                        g.src <= src.len(),
6373                        "cut {cut}: glyph {:?} points past the source at {}",
6374                        g.ch,
6375                        g.src
6376                    );
6377                }
6378            }
6379        }
6380    }
6381
6382    fn rendered(m: &VisualMap) -> String {
6383        m.rows
6384            .iter()
6385            .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
6386            .collect::<Vec<_>>()
6387            .join("\n")
6388    }
6389
6390    /// Render a source both ways: `build` over the whole marshalled arena (the
6391    /// reference), and `build_cached` driven the way [`crate::Doc`] drives it —
6392    /// top-level blocks from `child_spans`, per-block subtrees on a miss.
6393    fn render_both(
6394        ed: &mut Editor,
6395        src: &str,
6396        wrap: Option<usize>,
6397        cache: &mut BlockCache,
6398    ) -> (VisualMap, VisualMap) {
6399        let all = ed.nodes().unwrap();
6400        let surface = Surface::default();
6401        let plain = build(&all, src, wrap, false, &surface, None);
6402        let top = top_blocks(ed);
6403        let cached = build_cached(&top, src, wrap, false, &surface, None, cache, |id| {
6404            ed.subtree(NodeId(id)).unwrap_or_default()
6405        });
6406        (plain, cached)
6407    }
6408
6409    /// The whole correctness claim of the block cache: `build_cached` produces a
6410    /// byte-identical map to `build`, on a fresh cache *and* — the case that
6411    /// actually exercises reuse-and-shift plus per-block subtree marshalling — on
6412    /// a warm cache after the source has been edited underneath it.
6413    /// **Every glyph must stand on the character it claims.** A row's source
6414    /// extent is computed from its last glyph's offset, so a glyph carrying an
6415    /// offset that is not its own character's start yields a row end inside a
6416    /// multi-byte character — and every later slice of the source panics on it.
6417    ///
6418    /// Reproduces a real crash from a journal entry: a bracketed elision inside
6419    /// a blockquote (`[…]`) gave the closing bracket a `text` of `"]"` over a
6420    /// source span covering `"…]"`, because the parse folded the ellipsis into a
6421    /// neighbouring node. `push_escaped_text` walked that span assuming a
6422    /// dropped backslash was the only way text and source could diverge, so the
6423    /// `]` landed on the `…`'s first byte:
6424    /// `byte index 1236 is not a char boundary; it is inside '…'`.
6425    #[test]
6426    fn a_glyph_never_lands_inside_the_character_before_it() {
6427        let src = "> engage with it rather than look away. […]\n>\n> The through-line\n";
6428        let vmap = map(src);
6429        for (r, row) in vmap.rows.iter().enumerate() {
6430            assert!(
6431                src.is_char_boundary(row.end_src.min(src.len())),
6432                "row {r} ends at {} — inside a character",
6433                row.end_src
6434            );
6435            for g in &row.glyphs {
6436                assert!(
6437                    src.is_char_boundary(g.src.min(src.len())),
6438                    "row {r} has {:?} at {}, which is inside a character",
6439                    g.ch,
6440                    g.src
6441                );
6442            }
6443        }
6444        // The elision survives, and its bracket sits on the real `]`.
6445        let text: String = vmap
6446            .rows
6447            .iter()
6448            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
6449            .collect();
6450        assert!(text.contains("[…]"), "the elision should render: {text:?}");
6451        let close = vmap
6452            .rows
6453            .iter()
6454            .flat_map(|r| r.glyphs.iter())
6455            .find(|g| g.ch == ']')
6456            .expect("a closing bracket");
6457        assert_eq!(
6458            src[close.src..].chars().next(),
6459            Some(']'),
6460            "the bracket glyph should stand on the source's own `]`"
6461        );
6462    }
6463
6464    #[test]
6465    fn build_cached_matches_build() {
6466        let docs = [
6467            "# Title\n\nThe quick brown fox.\n\nAnother paragraph here.\n",
6468            "## H\n\n- one\n- two\n- three\n\n> a quote\n> continued\n",
6469            "para one\n\n```\ncode\nlines\n```\n\nafter code\n",
6470            "| a | b |\n|---|---|\n| 1 | 2 |\n\ntext after a table\n",
6471            "line\n- \nsetext?\n\nreal para\n\n\n\ntrailing blanks\n",
6472            "> quote with **bold** and a [link](https://x.dev)\n>\n> - item\n> - item2\n\ntail\n",
6473            "intro\n\n![a cat](img/cat.png)\n\nbetween\n\n![](https://x.dev/logo.svg)\n\nend\n",
6474            "- text item\n- ![alt](pic.png)\n- more text\n",
6475            // Footnotes: twig parses each definition as a root beside `doc`, so
6476            // these are the docs where the reference build and the incremental
6477            // one could disagree about what the top-level blocks even are.
6478            "A claim[^1] and another[^src].\n\n[^1]: First note.\n\n[^src]: Second.\n\ntail\n",
6479            "note[^a]\n\n[^a]: body **bold**\n    wrapped on\n    three lines\n\nafter\n",
6480            // No trailing newline. twig closes the document's last block on the
6481            // virtual newline it supplies at EOF, so that block's `span.end` is
6482            // `source.len() + 1` — a range that slices no bytes at all. Keying
6483            // the block cache off such a slice made every last block hash alike;
6484            // see [`block_bytes`].
6485            "# Title\n\nThe quick brown fox.\n\nA tail with no newline",
6486            "A claim[^1] and another[^src].\n\n[^1]: First note.\n[^src]: Second, ending the file.",
6487            // Comments draw nothing. The per-block builder the cached path
6488            // renders one with starts at offset 0 and, drawing nothing, never
6489            // moved — so the walk went on from 0 and spelled every line of the
6490            // document as a blank row. One at the start, one between blocks,
6491            // one at the end, so each position is covered.
6492            "<!-- lead -->\n\npara\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n\n<!-- trail -->\n",
6493            // A Markdown `<div>` ends with a hidden `</div>` line the walk
6494            // steps over — between blocks and closing the file, so both the
6495            // separator after it and the trailing count are covered.
6496            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
6497            "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n",
6498            // Link reference definitions: roots beside `doc` like footnotes,
6499            // but drawing nothing. Alone between blocks, glued under a
6500            // paragraph, and closing the file under a comment — the README
6501            // shape.
6502            "see [a] and [b]\n\n[a]: /a\n\nmid\n[b]: /b \"bee\"\n\nend [c]\n\n<!-- links -->\n[c]: /c\n",
6503        ];
6504        for wrap in [None, Some(80usize), Some(20)] {
6505            for src in docs {
6506                let ctx = format!("wrap={wrap:?} src={src:?}");
6507                let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6508                let mut cache = BlockCache::default();
6509
6510                // 1) Fresh cache equals the cache-free build.
6511                let (plain, cached) = render_both(&mut ed, src, wrap, &mut cache);
6512                assert_maps_eq(&plain, &cached, &format!("fresh {ctx}"));
6513
6514                // 2) Type a char mid-document, reparse, rebuild with the now-warm
6515                //    cache: the edited block is re-marshalled and re-rendered,
6516                //    every block below it is reused shifted, and the result must
6517                //    still match a from-scratch build.
6518                let at = (src.len() / 2..=src.len())
6519                    .find(|&i| src.is_char_boundary(i))
6520                    .unwrap();
6521                ed.edit_range(at, at, "Z").unwrap();
6522                let src2 = ed.source_str().unwrap();
6523                let (plain2, cached2) = render_both(&mut ed, &src2, wrap, &mut cache);
6524                assert_maps_eq(&plain2, &cached2, &format!("after insert {ctx}"));
6525
6526                // 3) Delete it again: offsets shift back the other way, and the
6527                //    warm cache must not hand back stale shifted rows.
6528                ed.edit_range(at, at + 1, "").unwrap();
6529                let src3 = ed.source_str().unwrap();
6530                let (plain3, cached3) = render_both(&mut ed, &src3, wrap, &mut cache);
6531                assert_maps_eq(&plain3, &cached3, &format!("after delete {ctx}"));
6532            }
6533        }
6534    }
6535
6536    /// A document that does not end in a newline is the one place twig hands
6537    /// leaf a top-level span that addresses no source: the last block is closed
6538    /// on the virtual newline the parser supplies at EOF, so its `span.end` is
6539    /// `source.len() + 1`. The block cache keys on the bytes under that span, and
6540    /// reading the out-of-range slice as *no bytes* broke it two ways at once —
6541    /// [`block_bytes`] has the full account. Both ways are checked here, because
6542    /// they fail independently.
6543    #[test]
6544    fn a_block_running_past_the_last_byte_still_keys_the_cache_by_its_own_bytes() {
6545        // One: two overrunning blocks collide. A footnote definition is a root
6546        // beside `doc` that [`top_blocks`] merges into the top level, while the
6547        // `section` above it spans the definition's bytes too — so when the
6548        // definition ends the file, both blocks end past it. The second was
6549        // served the first's rows, and the definition rendered as a copy of the
6550        // heading.
6551        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.";
6552        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
6553        let (plain, cached) = render_both(&mut ed, src, Some(80), &mut BlockCache::default());
6554        assert_maps_eq(&plain, &cached, "a definition ending the file");
6555        let text = rendered(&cached);
6556        assert!(
6557            text.ends_with("[note] A note with a word for a label."),
6558            "the last definition should render itself: {text:?}"
6559        );
6560        assert_eq!(
6561            text.matches("A heading with a reference").count(),
6562            1,
6563            "the heading should render exactly once: {text:?}"
6564        );
6565
6566        // Two: one overrunning block goes stale. Its bytes are its cache key, so
6567        // a block that keeps hashing the same however it is edited is served the
6568        // rows built before the edit — the whole last line frozen as the user
6569        // types in it.
6570        let mut cache = BlockCache::default();
6571        let first = "first para\n\n# A heading\n\nlast para with no newline";
6572        let mut ed = Editor::new_str(first, Format::Djot).unwrap();
6573        let (_, warm) = render_both(&mut ed, first, Some(80), &mut cache);
6574        assert!(rendered(&warm).ends_with("last para with no newline"));
6575
6576        let second = "first para\n\n# A heading\n\nDIFFERENT text without a newline";
6577        let mut ed = Editor::new_str(second, Format::Djot).unwrap();
6578        let (plain, cached) = render_both(&mut ed, second, Some(80), &mut cache);
6579        assert_maps_eq(&plain, &cached, "edited last block, warm cache");
6580        let text = rendered(&cached);
6581        assert!(
6582            text.ends_with("DIFFERENT text without a newline"),
6583            "the warm cache served the pre-edit rows: {text:?}"
6584        );
6585    }
6586
6587    #[test]
6588    fn resolves_markup_to_plain_text() {
6589        let text = rendered(&map("# Title\n\na **bold** word\n"));
6590        assert!(!text.contains('#'), "heading marker shown: {text:?}");
6591        assert!(!text.contains("**"), "strong delimiters shown: {text:?}");
6592        assert!(text.contains("Title") && text.contains("bold word"));
6593    }
6594
6595    #[test]
6596    fn every_glyph_points_at_its_source_byte() {
6597        let src = "a **bold** c\n";
6598        let m = map(src);
6599        for row in &m.rows {
6600            for g in &row.glyphs {
6601                // A real (non-synthetic) glyph's source byte is the glyph's char.
6602                if g.src < src.len()
6603                    && src.is_char_boundary(g.src)
6604                    && let Some(sc) = src[g.src..].chars().next()
6605                    && sc == g.ch
6606                {
6607                    continue;
6608                }
6609                // Synthetic prefixes (none here) would be the only exceptions.
6610                panic!("glyph {:?} at src {} doesn't match source", g.ch, g.src);
6611            }
6612        }
6613    }
6614
6615    #[test]
6616    fn offset_and_position_round_trip_on_visible_text() {
6617        let m = map("hello world\n");
6618        let (r, c) = m.pos_of_offset(6); // the 'w'
6619        assert_eq!(m.offset_of_pos(r, c), 6);
6620    }
6621
6622    #[test]
6623    fn visible_utf16_indices_count_the_text_the_system_sees() {
6624        // Hidden delimiters, a two-unit emoji, and a block gap — every way the
6625        // visible text's UTF-16 length parts company with a source byte count.
6626        let src = "a **b\u{1F600}** c\n\nd\n";
6627        let m = map(src);
6628        let end = m.snap_to_stop(src.len());
6629        let text = m.visible_text(0, end);
6630        assert_eq!(text, "a b\u{1F600} c\nd");
6631
6632        // Forward: the index of each offset is where that character sits in
6633        // the visible string, in UTF-16 units.
6634        for (i, (src_off, _)) in m.visible_items(0, end).iter().enumerate() {
6635            let expect: usize = text.chars().take(i).map(char::len_utf16).sum();
6636            assert_eq!(
6637                m.visible_utf16_len(0, *src_off),
6638                expect,
6639                "utf16 index of source offset {src_off}"
6640            );
6641            // And back: the index resolves to the offset it came from.
6642            assert_eq!(m.offset_at_visible_utf16(end, expect), Some(*src_off));
6643        }
6644        // Inside the emoji's surrogate pair resolves to the emoji.
6645        let emoji_src = src.find('\u{1F600}').unwrap();
6646        let emoji_idx = m.visible_utf16_len(0, emoji_src);
6647        assert_eq!(
6648            m.offset_at_visible_utf16(end, emoji_idx + 1),
6649            Some(emoji_src)
6650        );
6651        // At or past the end is nobody's character.
6652        let total = m.visible_utf16_len(0, end);
6653        assert_eq!(total, text.encode_utf16().count());
6654        assert_eq!(m.offset_at_visible_utf16(end, total), None);
6655    }
6656
6657    /// The documents the lookups are checked against their reference scans
6658    /// on: every shape that puts rows out of source order or a stop out of
6659    /// step with a glyph. A wrapped table, whose cells' second lines sit
6660    /// below the next column's first; a wide grapheme and an emoji outside
6661    /// the BMP; hidden delimiters and a link's hidden destination; a list
6662    /// with synthetic markers; a code block; an image row whose label glyphs
6663    /// all share one offset; an empty paragraph, a heading, and a wrapped
6664    /// paragraph — at a narrow width so the table and the prose both wrap,
6665    /// and unwrapped, which is how a GUI builds it.
6666    fn lookup_maps() -> Vec<(String, VisualMap)> {
6667        let table = "| left cell that wraps | right |\n|---|---|\n| a longer cell than the column can hold | b |\n| `k` | 你好 |\n\n";
6668        let srcs = [
6669            "hello world\n",
6670            "a **b\u{1F600}** c\n\nd\n",
6671            "- one *two*\n- three\n\n\n# Title\n\nend [link](https://e.org/x) tail\n",
6672            &format!("{table}```\nx\ny\n```\n\n![alt](a.png)\n\ntail 你好 **bold** here\n"),
6673            "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",
6674        ];
6675        let mut out = Vec::new();
6676        for src in srcs {
6677            for wrap in [Some(14), None] {
6678                out.push((format!("{src:?} at {wrap:?}"), map_at(src, wrap)));
6679            }
6680        }
6681        out
6682    }
6683
6684    /// `pos_of_offset` as it was written before the walk learnt to dismiss a
6685    /// row from its ends: every row read through, the nearest stop kept.
6686    fn pos_of_offset_by_scan(m: &VisualMap, off: usize) -> (usize, usize) {
6687        let mut best: Option<(usize, usize, usize)> = None;
6688        for (r, row) in m.rows.iter().enumerate() {
6689            if row.decoration {
6690                continue;
6691            }
6692            let cand = row
6693                .glyphs
6694                .iter()
6695                .enumerate()
6696                .find(|(_, g)| g.stop && g.src >= off)
6697                .map(|(i, g)| (g.src, r, row.col_of_glyph(i)))
6698                .or_else(|| (row.end_src >= off).then_some((row.end_src, r, row.width())));
6699            if let Some(c) = cand
6700                && best.is_none_or(|b| c.0 <= b.0)
6701            {
6702                best = Some(c);
6703            }
6704        }
6705        match best {
6706            Some((_, r, c)) => (r, c),
6707            None => {
6708                let r = m.last_stop_row();
6709                (r, m.row_width(r))
6710            }
6711        }
6712    }
6713
6714    /// `visible_items` as it was written before the spelling was tabulated:
6715    /// every stop glyph in the range gathered, sorted, and paired up.
6716    fn visible_items_by_scan(m: &VisualMap, from: usize, to: usize) -> Vec<(usize, Option<char>)> {
6717        let (lo, hi) = m.visible_span(from, to);
6718        let from = m.snap_to_glyph_stop(from);
6719        let mut glyphs: Vec<(usize, char)> = m
6720            .rows
6721            .iter()
6722            .filter(|r| !r.decoration)
6723            .flat_map(|r| r.glyphs.iter())
6724            .filter(|g| g.stop && g.src >= from && g.src < to)
6725            .map(|g| (g.src, g.ch))
6726            .collect();
6727        glyphs.sort_by_key(|&(src, _)| src);
6728        glyphs.dedup_by_key(|&mut (src, _)| src);
6729        let cell_ends: Vec<usize> = m
6730            .tables
6731            .iter()
6732            .flat_map(|t| t.grid.iter())
6733            .flat_map(|r| r.cells.iter())
6734            .map(|c| c.end)
6735            .collect();
6736        m.stops[lo..hi]
6737            .iter()
6738            .map(|&s| {
6739                let ch = glyphs
6740                    .iter()
6741                    .find(|&&(src, _)| src == s)
6742                    .filter(|_| !cell_ends.contains(&s))
6743                    .map(|&(_, ch)| ch);
6744                (s, ch)
6745            })
6746            .collect()
6747    }
6748
6749    #[test]
6750    fn pos_of_offset_agrees_with_reading_every_row_through() {
6751        for (name, m) in lookup_maps() {
6752            let len = m.rows.iter().map(|r| r.end_src).max().unwrap_or(0) + 2;
6753            for off in 0..=len {
6754                assert_eq!(
6755                    m.pos_of_offset(off),
6756                    pos_of_offset_by_scan(&m, off),
6757                    "offset {off} of {name}"
6758                );
6759            }
6760        }
6761    }
6762
6763    #[test]
6764    fn the_tabulated_spelling_agrees_with_gathering_the_glyphs() {
6765        for (name, m) in lookup_maps() {
6766            let end = m.stops.last().copied().unwrap_or(0);
6767            // Whole text, and every window a frontend might ask for.
6768            let mut spans = vec![(0, end)];
6769            for &a in m.stops.iter().step_by(3) {
6770                spans.push((a, end));
6771                spans.push((0, a));
6772                spans.push((a, (a + 5).min(end)));
6773            }
6774            for (from, to) in spans {
6775                let items = visible_items_by_scan(&m, from, to);
6776                assert_eq!(
6777                    m.visible_items(from, to),
6778                    items,
6779                    "items {from}..{to} of {name}"
6780                );
6781                let utf16: usize = items
6782                    .iter()
6783                    .map(|(_, ch)| ch.map_or(1, char::len_utf16))
6784                    .sum();
6785                assert_eq!(
6786                    m.visible_utf16_len(from, to),
6787                    utf16,
6788                    "utf16 {from}..{to} of {name}"
6789                );
6790            }
6791            // And back: every UTF-16 index in the text resolves to the stop
6792            // that spells it, as the scan would have found it.
6793            let items = visible_items_by_scan(&m, 0, end);
6794            let mut seen = 0;
6795            for (src, ch) in &items {
6796                for u in seen..seen + ch.map_or(1, char::len_utf16) {
6797                    assert_eq!(
6798                        m.offset_at_visible_utf16(end, u),
6799                        Some(*src),
6800                        "index {u} of {name}"
6801                    );
6802                }
6803                seen += ch.map_or(1, char::len_utf16);
6804            }
6805            assert_eq!(
6806                m.offset_at_visible_utf16(end, seen),
6807                None,
6808                "past the end of {name}"
6809            );
6810        }
6811    }
6812
6813    #[test]
6814    fn visible_text_spends_exactly_one_character_on_every_stop() {
6815        // A list (whose items' ends no gap row follows), a table (whose cells'
6816        // ends draw a gutter space), and a code block (one row per line):
6817        // every place the text used to part company with the stop count, in
6818        // both directions. `UITextInput`'s tokenizer indexes this text by
6819        // that count, so the two must agree exactly between any two stops.
6820        let src = "- one\n- two\n\n| a | b |\n| - | - |\n| c | d |\n\n```\nx\ny\n```\n\nend\n";
6821        let m = map(src);
6822        let end = m.snap_to_stop(src.len());
6823        // The table's trailing stop draws no glyph, so it is spelled as a line
6824        // end too: to the system the table ends on a blank line, which is
6825        // where the caret past it stands.
6826        assert_eq!(m.visible_text(0, end), "one\ntwo\na\nb\nc\nd\n\nx\ny\nend");
6827        // Between any two stops, one character per hop.
6828        let first = m.snap_to_glyph_stop(0);
6829        let stops: Vec<usize> = std::iter::successors(Some(first), |&o| m.stop_after(o)).collect();
6830        for (i, &a) in stops.iter().enumerate() {
6831            for (j, &b) in stops.iter().enumerate().skip(i) {
6832                assert_eq!(
6833                    m.visible_text(a, b).chars().count(),
6834                    j - i,
6835                    "text between stops {a} and {b}"
6836                );
6837            }
6838        }
6839        // A cell's end is spelled as a line end, not the space it draws, so a
6840        // tap landing past `a`'s last letter has nothing to step over into `b`.
6841        let a_end = src.find("a |").unwrap() + 1;
6842        assert_eq!(m.visible_text(a_end, a_end + 1), "\n");
6843    }
6844
6845    #[test]
6846    fn unwrapped_mode_emits_one_row_per_paragraph() {
6847        // A long paragraph that would wrap under a column budget stays a single
6848        // row when wrap is None (the GUI wraps it at pixel width instead).
6849        let long = "one two three four five six seven eight nine ten eleven twelve\n";
6850        let mut ed = Editor::new_str(long, Format::Markdown).unwrap();
6851        let wrapped = build_t(&ed.nodes().unwrap(), long, Some(12));
6852        let unwrapped = build_t(&ed.nodes().unwrap(), long, None);
6853        assert!(wrapped.num_rows() > 1, "narrow column should wrap");
6854        assert_eq!(unwrapped.num_rows(), 1, "no budget should keep it one row");
6855        // Every glyph's source byte is preserved in the single row.
6856        let text: String = unwrapped.rows[0].glyphs.iter().map(|g| g.ch).collect();
6857        assert_eq!(text.trim_end(), long.trim_end());
6858    }
6859
6860    fn line_texts(m: &VisualMap) -> Vec<String> {
6861        m.rows
6862            .iter()
6863            .map(|r| {
6864                // Trim the trailing whitespace a row may carry — the zero-width
6865                // '\n' that closes a preserved line, and any space glyph left at
6866                // a wrap boundary (both real caret stops, neither visible text).
6867                r.glyphs
6868                    .iter()
6869                    .map(|g| g.ch)
6870                    .collect::<String>()
6871                    .trim_end()
6872                    .to_string()
6873            })
6874            .collect()
6875    }
6876
6877    #[test]
6878    fn preserve_lays_each_soft_break_on_its_own_row() {
6879        // A soft break (a bare newline inside a paragraph) folds into a space by
6880        // default — the whole paragraph is one reflowed row...
6881        let src = "one two\nthree four\n";
6882        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6883        let folded = build_t(&ed.nodes().unwrap(), src, None);
6884        assert_eq!(folded.num_rows(), 1, "fold: one reflowed row");
6885        assert_eq!(
6886            line_texts(&folded),
6887            vec!["one two three four"],
6888            "break folded to a space"
6889        );
6890
6891        // ...and under Preserve it renders where it was written, a row per line.
6892        let kept = map_preserve(src, None);
6893        assert_eq!(
6894            line_texts(&kept),
6895            vec!["one two", "three four"],
6896            "preserve: a row per line"
6897        );
6898    }
6899
6900    #[test]
6901    fn a_preserved_break_keeps_the_newline_offset_as_a_caret_stop() {
6902        // The break must leave a caret stop at the newline byte, or the caret
6903        // could not rest at the end of the first line. The '\n' glyph is dropped
6904        // from the row (so nothing stray renders); its offset (7 here) becomes the
6905        // row's end stop instead — the same offset the folded space would carry.
6906        let src = "one two\nthree four\n";
6907        let m = map_preserve(src, None);
6908        assert!(
6909            !m.rows[0].glyphs.iter().any(|g| g.ch == '\n'),
6910            "the break glyph is dropped"
6911        );
6912        assert_eq!(
6913            m.rows[0].end_src, 7,
6914            "the first row ends at the newline byte"
6915        );
6916        assert!(m.is_stop(7), "the newline offset is a caret stop");
6917        // Row end offsets stay strictly ascending — no two rows pin one offset.
6918        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
6919        assert!(
6920            offs.windows(2).all(|w| w[0] < w[1]),
6921            "offsets not unique: {offs:?}"
6922        );
6923    }
6924
6925    #[test]
6926    fn preserved_lines_wrap_independently() {
6927        // Each preserved line wraps to the column on its own; the break between
6928        // them is hard, so a word never crosses it — "gamma" and "delta" could
6929        // share a row on width alone but the soft break keeps them apart.
6930        let src = "alpha beta gamma\ndelta epsilon\n";
6931        let m = map_preserve(src, Some(12));
6932        assert_eq!(
6933            line_texts(&m),
6934            vec!["alpha beta", "gamma", "delta", "epsilon"],
6935            "each source line wraps on its own"
6936        );
6937    }
6938
6939    #[test]
6940    fn an_empty_paragraph_between_blocks_renders_its_own_rows() {
6941        // "A", then two blank lines (an empty paragraph opened with Enter), then
6942        // "B": the empty paragraph must be navigable rows, not collapsed onto B.
6943        // Rows: "A", spacer, empty-paragraph, spacer, "B" — each blank row a
6944        // distinct source offset.
6945        let m = map("A\n\n\n\nB\n");
6946        let text: Vec<String> = m
6947            .rows
6948            .iter()
6949            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6950            .collect();
6951        assert_eq!(text, vec!["A", "", "", "", "B"], "got {text:?}");
6952        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
6953        // Strictly ascending — no two rows share an offset (else the caret pins).
6954        assert!(
6955            offs.windows(2).all(|w| w[0] < w[1]),
6956            "offsets not unique: {offs:?}"
6957        );
6958    }
6959
6960    #[test]
6961    fn a_tight_block_boundary_still_gets_one_separator() {
6962        // A heading directly above text (no blank line between) keeps the single
6963        // conventional separator row, as before.
6964        let m = map("# H\ntext\n");
6965        let text: Vec<String> = m
6966            .rows
6967            .iter()
6968            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6969            .collect();
6970        assert_eq!(text, vec!["H", "", "text"], "got {text:?}");
6971    }
6972
6973    #[test]
6974    fn an_escaped_delimiter_renders_without_its_backslash_and_maps_true_offsets() {
6975        // `a\*b` renders the three visible chars `a * b` — the escape backslash
6976        // is hidden — and every glyph points at its real source byte, so a caret
6977        // past the escape lands right (the `*` at source 2, `b` at source 3, not
6978        // the drifted 1/2 the naive text-offset mapping gave).
6979        let m = map("a\\*b\n");
6980        let row: Vec<(char, usize)> = m.rows[0].glyphs.iter().map(|g| (g.ch, g.src)).collect();
6981        assert_eq!(row, vec![('a', 0), ('*', 2), ('b', 3)], "got {row:?}");
6982    }
6983
6984    #[test]
6985    fn an_escaped_hash_stays_a_paragraph_and_shows_the_hash() {
6986        // `\# hi` is a paragraph beginning with a literal `#`, not a heading —
6987        // the backslash is hidden, the `#` shown at its true offset.
6988        let m = map("\\# hi\n");
6989        let text: String = m.rows[0].glyphs.iter().map(|g| g.ch).collect();
6990        assert_eq!(text, "# hi");
6991        assert_eq!(
6992            m.rows[0].glyphs[0].src, 1,
6993            "the # is at source byte 1, past the \\"
6994        );
6995    }
6996
6997    #[test]
6998    fn a_tight_nested_list_hangs_its_sublist_directly_under_the_item() {
6999        // A list item's own text and the sub-list nested under it are written on
7000        // adjacent source lines, so the rich view butts them together — no
7001        // fabricated blank row. Regression: the synthetic "breathe" separator
7002        // used to open a gap between `• a` and its `  • b`.
7003        assert_eq!(rendered(&map("- a\n  - b\n")), "• a\n  • b");
7004    }
7005
7006    #[test]
7007    fn a_loose_nested_list_keeps_its_real_blank_line() {
7008        // A genuine blank source line (a loose list) still parts the item from
7009        // its sub-list — only the *fabricated* separator is suppressed, never a
7010        // real one the author typed. The gap row wears the item's continuation
7011        // prefix (the two-space indent), so it renders as "  ", not empty.
7012        assert_eq!(rendered(&map("- a\n\n  - b\n")), "• a\n  \n  • b");
7013    }
7014
7015    #[test]
7016    fn frontmatter_is_hidden_and_the_document_opens_into_its_content() {
7017        // Leading YAML frontmatter renders nothing — no phantom blank rows for
7018        // its lines, no leading gap — and `content_start` points at the first
7019        // real block so the caret floor can keep out of the hidden metadata.
7020        let fm = "---\nconfig: prov.yaml\ncontents:\n- '[Sample](sample.md)'\n---\n";
7021        let src = format!("{fm}# leaf\n\nA line.\n");
7022        let m = map(&src);
7023        let text = rendered(&m);
7024        assert!(
7025            !text.contains("config"),
7026            "frontmatter body leaked: {text:?}"
7027        );
7028        assert!(!text.contains("prov"), "frontmatter body leaked: {text:?}");
7029        assert_eq!(
7030            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7031            "leaf"
7032        );
7033        assert_eq!(
7034            m.content_start,
7035            fm.len(),
7036            "floor should be the first real block"
7037        );
7038    }
7039
7040    #[test]
7041    fn a_frontmatter_only_document_puts_the_floor_after_the_frontmatter() {
7042        // Nothing to render, so the caret floor is the end of the hidden
7043        // frontmatter — not 0, which is *before* the opening `---` and made the
7044        // first keystroke in a fresh metadata-only note land ahead of it. And
7045        // the frontmatter's own newlines are not trailing blank lines: they used
7046        // to open phantom rows at offsets 1..4, inside the metadata.
7047        let src = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
7048        let m = map(src);
7049        assert_eq!(m.content_start, src.len(), "floor must clear the metadata");
7050        assert!(
7051            m.rows.is_empty(),
7052            "frontmatter must render no rows: {:?}",
7053            rendered(&m)
7054        );
7055        assert!(
7056            m.stops.is_empty(),
7057            "no stop may sit inside the metadata: {:?}",
7058            m.stops
7059        );
7060    }
7061
7062    #[test]
7063    fn a_frontmatter_only_document_still_counts_its_real_blank_lines() {
7064        // Two blank lines after the frontmatter are the author's empty paragraph
7065        // and still render, counted from the metadata's end rather than from 0.
7066        let fm = "---\ntitle: n\n---\n";
7067        let m = map(&format!("{fm}\n\n"));
7068        assert_eq!(m.content_start, fm.len());
7069        assert_eq!(m.rows.len(), 2, "the two trailing newlines each open a row");
7070        assert!(
7071            m.rows.iter().all(|r| r.end_src > fm.len()),
7072            "rows must sit past the frontmatter"
7073        );
7074    }
7075
7076    #[test]
7077    fn a_document_without_frontmatter_has_a_zero_floor() {
7078        let m = map("# leaf\n\nbody\n");
7079        assert_eq!(m.content_start, 0);
7080    }
7081
7082    #[test]
7083    fn trailing_spaces_become_caret_stops_so_the_caret_can_be_drawn_past_them() {
7084        // Markdown/Djot drop the trailing space in `hello ` from the `str` node,
7085        // so without help the row would end at `hello` and the caret couldn't be
7086        // drawn past column 5 — typing a space at a line's end wouldn't move it
7087        // on screen until the next visible character reparsed the space into an
7088        // interior node. The builder recovers it from the block's span/content_span
7089        // gap and emits it as a real, caret-stoppable glyph.
7090        let m = map("hello \n");
7091        assert_eq!(
7092            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7093            "hello "
7094        );
7095        assert_eq!(
7096            m.rows[0].end_src, 6,
7097            "the row now ends past the trailing space"
7098        );
7099        // The caret can rest both on and past the space.
7100        assert_eq!(m.pos_of_offset(5), (0, 5), "between 'o' and the space");
7101        assert_eq!(m.pos_of_offset(6), (0, 6), "past the space");
7102        // Two trailing spaces, both stops.
7103        let m = map("hello  \n");
7104        assert_eq!(
7105            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7106            "hello  "
7107        );
7108        assert_eq!(m.pos_of_offset(7), (0, 7));
7109    }
7110
7111    #[test]
7112    fn a_headings_trailing_space_is_a_caret_stop_too() {
7113        // The hidden `# ` marker means `# hi ` renders as `hi ` in three columns;
7114        // the caret past the trailing space lands on the third.
7115        let m = map("# hi \n");
7116        assert_eq!(
7117            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7118            "hi "
7119        );
7120        assert_eq!(m.pos_of_offset(5), (0, 3));
7121    }
7122
7123    #[test]
7124    fn a_table_cells_trailing_padding_is_not_mistaken_for_block_trailing_space() {
7125        // A cell's own `span` is the whole row, so the trailing-whitespace
7126        // recovery must not run for cells or it would swallow the `│` delimiters
7127        // and neighbours between the cell text and the row's end. The grid stays
7128        // exactly as before.
7129        let text = rendered(&map(TABLE));
7130        assert!(
7131            text.contains("│ Pear │   3 │"),
7132            "cell padding disturbed:\n{text}"
7133        );
7134    }
7135
7136    #[test]
7137    fn a_click_below_the_last_row_lands_on_the_last_stop_not_offset_zero() {
7138        // A drag into the empty space under a short document used to resolve to
7139        // offset 0 — the wrong direction, and not even a caret stop when the
7140        // document opens on hidden frontmatter (its `content_start` floor is not
7141        // a stop), which crashed the caret invariant. It now lands on the last
7142        // stop: the end of the document, where dragging downward should reach.
7143        let fm = "---\ntitle: n\n---\n";
7144        let m = map(&format!("{fm}# Hi\n\nbody\n"));
7145        let below = m.num_rows() + 5;
7146        let off = m.offset_of_pos(below, 0);
7147        assert!(
7148            m.is_stop(off),
7149            "offset {off} from a below-content click is not a stop"
7150        );
7151        assert_eq!(
7152            off,
7153            m.stops.last().copied().unwrap(),
7154            "should be the document's last stop"
7155        );
7156        assert!(
7157            off > fm.len(),
7158            "must not fall onto the hidden frontmatter floor"
7159        );
7160    }
7161
7162    #[test]
7163    fn offset_of_pos_is_a_stop_for_every_row_including_past_the_end() {
7164        // The invariant the caret motion asserts: whatever cell a click names,
7165        // the offset it resolves to is one the caret can actually rest at.
7166        for src in [
7167            "hello \n",
7168            "# A heading here \n\nbody text goes on \n",
7169            "---\nk: v\n---\n# Title\n\nprose here that wraps a bit \n",
7170        ] {
7171            let m = map(src);
7172            for row in 0..m.num_rows() + 3 {
7173                for col in 0..30 {
7174                    let off = m.offset_of_pos(row, col);
7175                    assert!(
7176                        m.is_stop(off),
7177                        "row {row} col {col} → {off} is not a stop in {src:?}"
7178                    );
7179                }
7180            }
7181        }
7182    }
7183
7184    /// `| Name | Qty |` with Name left-aligned and Qty right-aligned.
7185    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
7186
7187    #[test]
7188    fn a_table_renders_as_an_aligned_grid() {
7189        let text = rendered(&map(TABLE));
7190        assert_eq!(
7191            text,
7192            "┌──────┬─────┐\n\
7193             │ Name │ Qty │\n\
7194             ├──────┼─────┤\n\
7195             │ Pear │   3 │\n\
7196             │ Fig  │  12 │\n\
7197             └──────┴─────┘",
7198            "got:\n{text}"
7199        );
7200    }
7201
7202    #[test]
7203    fn table_columns_honour_their_alignment() {
7204        // Centre and default(left) come straight from twig's cell.alignment —
7205        // the delimiter row it's spelled in is consumed and has no node.
7206        let text = rendered(&map("| A | Bee |\n| --- | :---: |\n| x | y |\n"));
7207        assert!(text.contains("│ x │  y  │"), "centred column: {text:?}");
7208    }
7209
7210    #[test]
7211    fn table_borders_are_decoration_the_caret_never_lands_on() {
7212        let m = map(TABLE);
7213        // The top and header rules are whole decoration rows.
7214        for r in [0, 2] {
7215            assert!(m.rows[r].decoration, "row {r} should be a decoration rule");
7216            assert!(
7217                !m.rows[r].glyphs.iter().any(|g| g.stop),
7218                "row {r} has a stop"
7219            );
7220        }
7221        // The bottom border is the exception: no glyph of it is a stop, but
7222        // its end is the table's trailing caret home — the one place the caret
7223        // can stand past the last cell.
7224        let bottom = &m.rows[5];
7225        assert!(
7226            !bottom.decoration,
7227            "the bottom border holds the trailing stop"
7228        );
7229        assert!(
7230            !bottom.glyphs.iter().any(|g| g.stop),
7231            "the bottom border's glyphs are not stops"
7232        );
7233        assert!(m.is_stop(bottom.end_src), "the trailing stop is a stop");
7234        assert!(m.table_end_stop(bottom.end_src));
7235        assert_eq!(
7236            bottom.end_src,
7237            TABLE.trim_end_matches('\n').len(),
7238            "the trailing stop is the table's own end, before its newline"
7239        );
7240        assert!(
7241            !m.table_end_stop(TABLE.rfind("12").unwrap() + 2),
7242            "a cell's end is not the trailing stop"
7243        );
7244        // A content row's `│` and padding are decoration; only the cell text
7245        // and each cell's one end-stop are stops.
7246        let header = &m.rows[1];
7247        assert!(!header.decoration);
7248        for g in &header.glyphs {
7249            if g.ch == '│' {
7250                assert!(!g.stop, "a border is not a caret stop");
7251            }
7252        }
7253        let stops: String = header
7254            .glyphs
7255            .iter()
7256            .filter(|g| g.stop)
7257            .map(|g| g.ch)
7258            .collect();
7259        assert_eq!(stops, "Name Qty ", "cell text plus one end-stop space each");
7260    }
7261
7262    #[test]
7263    fn a_cell_maps_to_its_own_source_text() {
7264        let m = map(TABLE);
7265        // "Pear" starts at byte 32 in TABLE; the caret there draws on the 'P'.
7266        let pear = TABLE.find("Pear").unwrap();
7267        let (r, c) = m.pos_of_offset(pear);
7268        assert_eq!(m.rows[r].glyphs[c].ch, 'P');
7269        assert_eq!(m.offset_of_pos(r, c), pear, "round trips");
7270    }
7271
7272    #[test]
7273    fn a_wide_table_is_cut_to_fit_and_its_cells_wrap() {
7274        // Columns wider than the surface used to run off the right edge, where
7275        // nothing could reach them. They're cut to the budget instead, and the
7276        // text wraps down inside the column — the header rule stays put, and
7277        // an alignment holds on every line of a wrapped cell, not just the first.
7278        let src = "| Ingredient | Notes |\n|---|---:|\n\
7279                   | flour milled coarse | sift it twice |\n| salt | a pinch |\n";
7280        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7281        let m = build_t(&ed.nodes().unwrap(), src, Some(30));
7282        let text = rendered(&m);
7283        assert_eq!(
7284            text,
7285            "┌──────────────┬─────────────┐\n\
7286             │ Ingredient   │       Notes │\n\
7287             ├──────────────┼─────────────┤\n\
7288             │ flour milled │     sift it │\n\
7289             │ coarse       │       twice │\n\
7290             │ salt         │     a pinch │\n\
7291             └──────────────┴─────────────┘",
7292            "got:\n{text}"
7293        );
7294        for (r, row) in m.rows.iter().enumerate() {
7295            assert!(
7296                row.glyphs.len() <= 30,
7297                "row {r} overflows: {}",
7298                row.glyphs.len()
7299            );
7300        }
7301    }
7302
7303    #[test]
7304    fn a_column_too_narrow_for_a_word_breaks_it_rather_than_spilling() {
7305        // A paragraph lets an overlong word trail off the end of the line; a
7306        // table column can't — a glyph past the border lands on the border.
7307        let src = "| A | B |\n|---|---|\n| antidisestablishmentarianism | x |\n";
7308        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7309        let m = build_t(&ed.nodes().unwrap(), src, Some(20));
7310        for (r, row) in m.rows.iter().enumerate() {
7311            assert!(
7312                row.glyphs.len() <= 20,
7313                "row {r} overflows: {}",
7314                row.glyphs.len()
7315            );
7316        }
7317        // Broken across lines, but whole: every letter is still drawn, at its
7318        // own source byte, where the caret can reach it.
7319        let word = "antidisestablishmentarianism";
7320        let at = src.find(word).unwrap();
7321        for (i, ch) in word.char_indices() {
7322            assert!(
7323                m.rows
7324                    .iter()
7325                    .flat_map(|r| r.glyphs.iter())
7326                    .any(|g| g.stop && g.src == at + i && g.ch == ch),
7327                "{ch:?} at {} was lost to the break",
7328                at + i
7329            );
7330        }
7331    }
7332
7333    #[test]
7334    fn a_code_block_maps_each_line_to_its_own_source_text() {
7335        // Every glyph used to point at the block's start, which made the whole
7336        // block one offset — visible, but impossible to put a caret inside.
7337        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
7338        let m = map(src);
7339        for row in &m.rows {
7340            for g in row.glyphs.iter().filter(|g| g.stop) {
7341                assert_eq!(
7342                    src[g.src..].chars().next(),
7343                    Some(g.ch),
7344                    "glyph {:?} at {} isn't the source byte it claims",
7345                    g.ch,
7346                    g.src
7347                );
7348            }
7349        }
7350    }
7351
7352    #[test]
7353    fn an_indented_code_block_maps_past_its_stripped_indent() {
7354        // twig strips the four-space indent, so `text` isn't a source slice and
7355        // the lines have to be re-found. Offsets land on the code, not the indent.
7356        let src = "    indented\n    code\n";
7357        let m = map(src);
7358        let stops: Vec<(char, usize)> = m
7359            .rows
7360            .iter()
7361            .flat_map(|r| r.glyphs.iter().filter(|g| g.stop).map(|g| (g.ch, g.src)))
7362            .collect();
7363        assert_eq!(
7364            stops[0],
7365            ('i', 4),
7366            "first line should start past the indent"
7367        );
7368        assert!(
7369            stops.contains(&('c', 17)),
7370            "second line misplaced: {stops:?}"
7371        );
7372    }
7373
7374    #[test]
7375    fn a_fenced_block_whose_code_echoes_its_info_string_maps_to_the_code() {
7376        // The one case that defeats a forward search: the opening fence
7377        // ```` ```rust ```` ends with the same text as the code under it.
7378        let src = "```rust\nrust\n```\n";
7379        let m = map(src);
7380        let first = m.rows[0].glyphs.iter().find(|g| g.stop).unwrap();
7381        assert_eq!(first.src, 8, "matched the info string, not the code");
7382    }
7383
7384    #[test]
7385    fn a_code_block_carries_no_gutter_and_is_published_as_a_row_span() {
7386        // The old `▏ ` gutter is gone: a code row is the block prefix (none, at
7387        // the top level) plus the code text, and the whole run is named in
7388        // `code_blocks` so a frontend can box it.
7389        let src = "para\n\n```\ncode\nlines\n```\n\nafter\n";
7390        let m = map(src);
7391        assert_eq!(m.code_blocks.len(), 1, "one code block");
7392        let span = m.code_blocks[0].rows_span.clone();
7393        let rows: Vec<String> = m.rows[span.clone()]
7394            .iter()
7395            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7396            .collect();
7397        assert_eq!(rows, vec!["code".to_string(), "lines".to_string()]);
7398        assert!(!rendered(&m).contains('▏'), "gutter still drawn");
7399        assert!(
7400            m.rows[span].iter().all(|r| r.code),
7401            "every row in the span is flagged code"
7402        );
7403    }
7404
7405    #[test]
7406    fn an_empty_last_line_in_a_code_block_is_a_row_of_its_own() {
7407        // `trim_end_matches('\n')` cut the block's terminator *and* the newline
7408        // that spells a trailing empty line, so the row the Return had just made
7409        // never appeared and the caret on it fell through to the block below.
7410        // Every empty line is a row, wherever in the block it falls.
7411        let src = "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n";
7412        let m = map(src);
7413        let span = m.code_blocks[0].rows_span.clone();
7414        let rows: Vec<String> = m.rows[span.clone()]
7415            .iter()
7416            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7417            .collect();
7418        assert_eq!(
7419            rows,
7420            vec!["alpha".to_string(), "beta".to_string(), String::new()],
7421            "the empty last line gets a row"
7422        );
7423        assert!(
7424            m.rows[span.clone()].iter().all(|r| r.code),
7425            "the empty row is flagged code like the rest of the block"
7426        );
7427        // And it is the *source's* empty line, not a coarse fallback to the
7428        // block start: the offset the caret resolves to is the one Return made.
7429        let empty = span.end - 1;
7430        assert_eq!(
7431            m.rows[empty].end_src,
7432            src.find("beta\n\n").unwrap() + "beta\n".len(),
7433            "the empty row maps to the line the Return opened"
7434        );
7435
7436        // Nothing is invented where there is no empty line, and a second one is
7437        // a second row.
7438        assert_eq!(
7439            map("```\nalpha\nbeta\n```\n").code_blocks[0]
7440                .rows_span
7441                .len(),
7442            2,
7443            "a block that ends at its last code line keeps two rows"
7444        );
7445        assert_eq!(
7446            map("```\nalpha\n\n\n```\n").code_blocks[0].rows_span.len(),
7447            3,
7448            "two trailing empty lines are two rows"
7449        );
7450    }
7451
7452    #[test]
7453    fn a_directive_container_is_tinted_and_labeled_on_its_first_row() {
7454        // diaryx's `:::vis{.public .family}` visibility block, and any other
7455        // `:::name{.class}` fenced div — core is agnostic of `name`.
7456        let src = ":::vis{.public .family}\nhello\n\nworld\n:::\nafter\n";
7457        let m = map_directives(src);
7458
7459        let content_rows: Vec<usize> = (0..m.rows.len()).filter(|&i| m.rows[i].directive).collect();
7460        assert!(!content_rows.is_empty(), "some row is flagged directive");
7461
7462        let after_rows: Vec<usize> = (0..m.rows.len())
7463            .filter(|&i| !content_rows.contains(&i) && !m.rows[i].glyphs.is_empty())
7464            .collect();
7465        assert!(
7466            after_rows.iter().all(|&i| !m.rows[i].directive),
7467            "content outside the fence isn't tinted"
7468        );
7469
7470        let labels: Vec<&str> = content_rows
7471            .iter()
7472            .filter_map(|&i| m.rows[i].directive_label.as_deref())
7473            .collect();
7474        assert_eq!(
7475            labels,
7476            vec!["public family"],
7477            "only the first row carries the label"
7478        );
7479
7480        assert_eq!(
7481            rendered(&m)
7482                .lines()
7483                .filter(|l| !l.is_empty())
7484                .collect::<Vec<_>>(),
7485            vec!["hello", "world", "after"],
7486            "fence markers don't leak into the rendered text"
7487        );
7488    }
7489
7490    #[test]
7491    fn a_bare_word_directive_is_labeled_same_as_dot_classes() {
7492        // diaryx_core::visibility's own `:::vis{public family}` — no leading
7493        // dots — is what apps/web's directive serializer and the native
7494        // publish-time filter both actually write today, distinct from twig's
7495        // `.class` convention. Both must label the same way so every existing
7496        // diaryx `:::vis{...}` block reads, not just newly dot-authored ones.
7497        let src = ":::vis{public family}\nhello\n:::\n";
7498        let m = map_directives(src);
7499        let label = m.rows.iter().find_map(|r| r.directive_label.clone());
7500        assert_eq!(label.as_deref(), Some("public family"));
7501    }
7502
7503    #[test]
7504    fn a_text_directive_keeps_its_paragraph_visible() {
7505        // Regression: an inline `:name[label]{…}` used to make its paragraph
7506        // fail the "all children inline" test, so the whole line was walked as
7507        // a container of blocks and rendered as empty rows with NO caret stops —
7508        // the text vanished from the editor and the caret couldn't enter it.
7509        // diaryx's inline `:vis[…]` is exactly this shape.
7510        let src = "Text with :abbr[HTML]{title=\"HyperText\"} inline.\n";
7511        let m = map_directives(src);
7512        assert_eq!(rendered(&m).trim_end(), "Text with HTML inline.");
7513        // Every character of the line is a caret home, markup excluded — the
7514        // label reads as ordinary text, the way a link's does.
7515        let stops: usize = m
7516            .rows
7517            .iter()
7518            .map(|r| r.glyphs.iter().filter(|g| g.stop).count())
7519            .sum();
7520        assert_eq!(stops, "Text with HTML inline.".chars().count());
7521        // It is inline, so it is not the container form's tinted panel.
7522        assert!(m.rows.iter().all(|r| !r.directive));
7523    }
7524
7525    #[test]
7526    fn a_text_directives_label_maps_to_its_true_source_bytes() {
7527        // Regression (needs twig-doc >= 2.5.0): twig parses a `[label]` as a
7528        // detached slice, and until it rebased the enclosing scan's segments
7529        // onto it every node inside the label reported a span of `(0,0)`. Read
7530        // by anything that trusts a span that means "byte 0", so the label's
7531        // glyphs mapped to the START OF THE DOCUMENT — a click on the label put
7532        // the caret at the top of the file, its stops collided with the real
7533        // first line's, and an edit there landed on the wrong bytes entirely.
7534        //
7535        // The sibling test `a_text_directive_keeps_its_paragraph_visible` only
7536        // counts stops, which is exactly why this went unnoticed: the right
7537        // NUMBER of stops at completely wrong offsets.
7538        let src = "x :abbr[HTML]{title=\"y\"} z\n";
7539        let m = map_directives(src);
7540        let stops: Vec<(char, usize)> = m
7541            .rows
7542            .iter()
7543            .flat_map(|r| &r.glyphs)
7544            .filter(|g| g.stop)
7545            .map(|g| (g.ch, g.src))
7546            .collect();
7547        // `HTML` sits at 8..12. The name, brackets and `{…}` are hidden markup
7548        // the caret steps over, so the line's stops run 0, 1, 8..12, then 24.
7549        assert_eq!(
7550            stops,
7551            [
7552                ('x', 0),
7553                (' ', 1),
7554                ('H', 8),
7555                ('T', 9),
7556                ('M', 10),
7557                ('L', 11),
7558                (' ', 24),
7559                ('z', 25)
7560            ]
7561        );
7562    }
7563
7564    #[test]
7565    fn every_glyph_in_a_directive_label_points_at_its_source_byte() {
7566        // The `every_glyph_points_at_its_source_byte` invariant, extended over
7567        // directive labels now that their offsets are real. Nested markup is
7568        // included: its delimiters are hidden, so the visible glyphs must skip
7569        // them and still name their own bytes.
7570        let src = "x :abbr[a *b* c] y and :vis[family only] z\n";
7571        let m = map_directives(src);
7572        for g in m.rows.iter().flat_map(|r| &r.glyphs).filter(|g| g.stop) {
7573            let at = src[g.src..].chars().next();
7574            assert_eq!(
7575                at,
7576                Some(g.ch),
7577                "glyph {:?} claims byte {}, which is {at:?}",
7578                g.ch,
7579                g.src
7580            );
7581        }
7582        assert_eq!(rendered(&m).trim_end(), "x a b c y and family only z");
7583    }
7584
7585    #[test]
7586    fn a_directive_labels_nested_emphasis_keeps_both_its_style_and_its_offsets() {
7587        let src = "x :abbr[a *b* c] y\n";
7588        let m = map_directives(src);
7589        let b = m
7590            .rows
7591            .iter()
7592            .flat_map(|r| &r.glyphs)
7593            .find(|g| g.ch == 'b')
7594            .expect("the emphasised char");
7595        assert!(b.style.italic, "the label's *b* lost its emphasis");
7596        assert_eq!(b.src, 11, "the label's *b* lost its source byte");
7597    }
7598
7599    #[test]
7600    fn a_bare_colon_word_renders_as_the_prose_it_almost_always_is() {
7601        // Regression: twig matches a colon followed by any letter-led word, so
7602        // ordinary prose is full of "text directives" nobody meant to write.
7603        // With no `[label]` there are no children, and the arm recursed into
7604        // them — rendering *nothing*. The word vanished from the document with
7605        // no caret stop left behind, so it could not even be deleted.
7606        for src in ["a :word b\n", "note :see below\n", ":smile: hi\n"] {
7607            let m = map_directives(src);
7608            assert_eq!(
7609                rendered(&m).trim_end(),
7610                src.trim_end(),
7611                "prose was eaten: {src:?}"
7612            );
7613        }
7614    }
7615
7616    #[test]
7617    fn a_bare_colon_word_keeps_every_byte_a_caret_stop() {
7618        let src = "a :word b\n";
7619        let m = map_directives(src);
7620        // Nothing here is markup, so nothing is hidden: each byte maps to
7621        // itself and can be stood on, which is what makes the colon deletable.
7622        let stops: Vec<(char, usize)> = m
7623            .rows
7624            .iter()
7625            .flat_map(|r| &r.glyphs)
7626            .filter(|g| g.stop)
7627            .map(|g| (g.ch, g.src))
7628            .collect();
7629        assert_eq!(
7630            stops,
7631            "a :word b"
7632                .chars()
7633                .enumerate()
7634                .map(|(i, c)| (c, i))
7635                .collect::<Vec<_>>()
7636        );
7637    }
7638
7639    #[test]
7640    fn an_attribute_bearing_text_directive_draws_a_chip() {
7641        // `{…}` is deliberate in a way a bare colon is not — diaryx writes
7642        // `:vis{.family}` inline — so this one reads as an embed, on the same
7643        // `⧉ label` recipe the leaf form's placeholder row uses.
7644        // Both attribute conventions label it: twig's dot-prefixed classes and
7645        // the bare pandoc-style words diaryx also writes.
7646        for src in ["a :vis{.family} b\n", "a :vis{family} b\n"] {
7647            let m = map_directives(src);
7648            assert_eq!(rendered(&m).trim_end(), "a ⧉ vis family b", "{src:?}");
7649        }
7650        // A `key=value` attr is configuration, not a name, so it adds nothing.
7651        let m = map_directives("a :foo{title=\"x\"} b\n");
7652        assert_eq!(rendered(&m).trim_end(), "a ⧉ foo b");
7653    }
7654
7655    #[test]
7656    fn a_directive_chip_is_one_atomic_caret_stop_at_its_own_offset() {
7657        let src = "a :vis{.family} b\n";
7658        let m = map_directives(src);
7659        let stops: Vec<usize> = m
7660            .rows
7661            .iter()
7662            .flat_map(|r| &r.glyphs)
7663            .filter(|g| g.stop)
7664            .map(|g| g.src)
7665            .collect();
7666        // The chip contributes exactly one stop, at the directive's start (2),
7667        // so the caret steps over it whole instead of walking hidden markup a
7668        // byte at a time. `{.family}`'s bytes (3..15) are never stood on.
7669        assert_eq!(stops, [0, 1, 2, 15, 16]);
7670    }
7671
7672    #[test]
7673    fn a_paragraph_holding_only_a_chip_is_still_navigable() {
7674        // With no stop of its own the row would be unreachable — the caret
7675        // could never be put on the line to edit or delete the directive.
7676        let m = map_directives(":vis{.family}\n");
7677        assert!(
7678            m.row_is_navigable(0),
7679            "a chip-only paragraph has no caret home"
7680        );
7681        assert_eq!(
7682            m.offset_of_pos(0, 0),
7683            0,
7684            "its caret home isn't the directive's start"
7685        );
7686    }
7687
7688    #[test]
7689    fn a_ratio_or_a_clock_time_is_never_a_directive() {
7690        // twig requires a letter after the colon, so these stay prose — the
7691        // verbatim arm must not be reached for them at all.
7692        let src = "ratio 3:4 and 10:30\n";
7693        assert_eq!(
7694            rendered(&map_directives(src)).trim_end(),
7695            "ratio 3:4 and 10:30"
7696        );
7697    }
7698
7699    #[test]
7700    fn a_leaf_directive_is_a_placeholder_row_with_its_attrs_published() {
7701        // `::name{…}` is a standalone block with no body — an embed, a table of
7702        // contents. It used to emit no rows at all: invisible, no caret home,
7703        // vertical motion crossing a void. Now it draws the image recipe's
7704        // placeholder and publishes what the host app needs to paint the real
7705        // thing.
7706        let src = "before\n\n::embed{src=\"demo.html\" height=\"400\"}\n\nafter\n";
7707        let m = map_directives(src);
7708
7709        let row = m
7710            .rows
7711            .iter()
7712            .position(|r| r.leaf_directive.is_some())
7713            .expect("a placeholder row");
7714        assert_eq!(
7715            m.rows[row].glyphs.iter().map(|g| g.ch).collect::<String>(),
7716            "⧉ embed"
7717        );
7718        assert!(
7719            m.rows[row].glyphs.iter().any(|g| g.stop),
7720            "the caret can land on it"
7721        );
7722        assert!(
7723            m.rows[row].directive,
7724            "a frontend frames it like the container form"
7725        );
7726
7727        assert_eq!(m.directives.len(), 1);
7728        let info = &m.directives[0];
7729        assert_eq!(info.name, "embed");
7730        assert_eq!(info.rows_span, row..row + 1);
7731        assert_eq!(info.attr("src"), Some("demo.html"));
7732        assert_eq!(info.attr("height"), Some("400"));
7733        assert_eq!(info.attr("nope"), None);
7734        // The prose around it is untouched.
7735        assert!(rendered(&m).contains("before") && rendered(&m).contains("after"));
7736    }
7737
7738    #[test]
7739    fn a_leaf_directive_shows_its_label_and_honours_its_prefix() {
7740        // A `[label]` names the placeholder (the way an image's alt does), and a
7741        // quoted directive keeps the quote's gutter — it is a block like any
7742        // other, not a special case that escapes its container.
7743        let m = map_directives("::embed[Audience demo]{src=\"demo.html\"}\n");
7744        assert_eq!(rendered(&m).trim_end(), "⧉ Audience demo");
7745        assert_eq!(m.directives[0].label, "Audience demo");
7746
7747        let quoted = map_directives("> ::embed{src=\"x.html\"}\n");
7748        assert_eq!(rendered(&quoted).trim_end(), "│ ⧉ embed");
7749        assert_eq!(quoted.directives[0].name, "embed");
7750    }
7751
7752    #[test]
7753    fn a_container_directive_is_still_a_panel_not_a_placeholder() {
7754        // The three forms must not bleed into each other: only the leaf form is
7755        // a placeholder, and only the container form tints the blocks it wraps.
7756        let m = map_directives(":::note{.warning}\nBody\n:::\n");
7757        assert!(
7758            m.directives.is_empty(),
7759            "a container publishes no placeholder"
7760        );
7761        assert!(m.rows.iter().all(|r| r.leaf_directive.is_none()));
7762        assert_eq!(rendered(&m).trim_end(), "Body");
7763        assert!(
7764            m.rows
7765                .iter()
7766                .any(|r| r.directive && r.directive_label.as_deref() == Some("warning"))
7767        );
7768    }
7769
7770    /// A production-path build with both extensions on — the only way to put a
7771    /// promoted HTML element and a directive in one document, which is what the
7772    /// `container` kind made necessary to tell apart. Returns the whole `Doc`
7773    /// because [`VisualMap`] is not `Clone`; read `doc.vmap`.
7774    fn doc_built(src: &str) -> crate::Doc {
7775        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
7776        doc.build_visual(80);
7777        doc
7778    }
7779
7780    /// Every `container` node in `src`, parsed the way production does (both
7781    /// extensions on), paired with what [`container_is_directive`] makes of it.
7782    fn containers(src: &str) -> Vec<(String, bool, Option<DirectiveForm>)> {
7783        let mut ed = Editor::new_ext(
7784            src.as_bytes(),
7785            Format::Markdown,
7786            twig::MarkdownExtensions {
7787                directives: true,
7788                html_elements: true,
7789                ..Default::default()
7790            },
7791        )
7792        .unwrap();
7793        ed.nodes()
7794            .unwrap()
7795            .iter()
7796            .filter(|n| n.kind == Kind::Container)
7797            .map(|n| {
7798                (
7799                    n.name.clone().unwrap_or_default(),
7800                    container_is_directive(n),
7801                    n.directive_form,
7802                )
7803            })
7804            .collect()
7805    }
7806
7807    #[test]
7808    fn a_directive_and_an_html_element_are_told_apart_by_spelling_not_by_form() {
7809        // twig 2.8 folded `div`/`span`/`directive`/`element` into one `container`
7810        // kind. `directive_form` reads as though it separates them and does not:
7811        // a block-level `<div>` reports `Some(DirectiveForm::Container)` exactly
7812        // as a `:::note` does. Trusting it would draw directive chrome — a tinted
7813        // panel, a `.class` audience label — on every pasted Slack/Docs div.
7814        for (src, name, want) in [
7815            (":::note{.a}\nbody\n:::\n", "note", true),
7816            ("::embed{src=x}\n", "embed", true),
7817            ("a :vis[hi]{.b} b\n", "vis", true),
7818            ("<div class=\"x\">\nhi\n</div>\n", "div", false),
7819            ("<video src=\"v.mp4\" controls></video>\n", "video", false),
7820            ("<audio src=\"a.mp3\" controls></audio>\n", "audio", false),
7821            ("<figure>\n\nhi\n\n</figure>\n", "figure", false),
7822            // The `:` in an attribute must not read as a directive opener: the
7823            // `<` of the tag comes first, and first one wins.
7824            (
7825                "<video src=\"http://x.test/v.mp4\" controls></video>\n",
7826                "video",
7827                false,
7828            ),
7829            (
7830                "<source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\n",
7831                "source",
7832                false,
7833            ),
7834        ] {
7835            let found = containers(src);
7836            let hit = found.iter().find(|(n, ..)| n == name);
7837            let Some((_, is_directive, form)) = hit else {
7838                panic!("no `{name}` container in {src:?} — found {found:?}");
7839            };
7840            assert_eq!(*is_directive, want, "{name} in {src:?} (form was {form:?})");
7841        }
7842
7843        // And the reason this can't just read the field: for the one collision
7844        // that matters, the field says the same thing for both.
7845        let div = containers("<div class=\"x\">\nhi\n</div>\n");
7846        let note = containers(":::note{.a}\nbody\n:::\n");
7847        assert_eq!(
7848            div[0].2, note[0].2,
7849            "if these ever differ, `directive_form` became usable and this rule can go"
7850        );
7851    }
7852
7853    #[test]
7854    fn a_directive_nested_in_a_quote_or_list_is_still_a_directive() {
7855        // A container's span opens with its *block prefix*, not its own markup —
7856        // `> ::embed{…}` starts at the `>`. Reading only the first byte to tell a
7857        // directive from an element (both `container` since 2.8) therefore misses
7858        // every nested one, and the placeholder silently renders as nothing.
7859        for (src, ctx) in [
7860            ("> ::embed{src=\"x\"}\n", "quoted"),
7861            ("- ::embed{src=\"x\"}\n", "listed"),
7862            (">> ::embed{src=\"x\"}\n", "twice quoted"),
7863        ] {
7864            let m = map_directives(src);
7865            assert_eq!(m.directives.len(), 1, "{ctx} directive was lost");
7866            assert_eq!(m.directives[0].name, "embed", "{ctx}");
7867        }
7868    }
7869
7870    #[test]
7871    fn a_video_is_still_media_and_not_a_directive() {
7872        // The other side of the same coin: `<video>` is a `container` too, and
7873        // must reach `block_media` rather than the directive arms.
7874        let doc = doc_built("<video src=\"clip.mp4\" controls></video>\n");
7875        assert_eq!(doc.vmap.media.len(), 1, "the video is block media");
7876        assert!(
7877            doc.vmap.rows.iter().all(|r| !r.directive),
7878            "the video drew directive chrome"
7879        );
7880    }
7881
7882    #[test]
7883    fn a_directive_needs_the_extension_flag() {
7884        // `map` (twig's default extensions) leaves `directives` off — the fence
7885        // renders as literal paragraph text, same as any other unrecognized
7886        // punctuation, never corrupting or panicking.
7887        let src = ":::vis{.public}\nhello\n:::\n";
7888        let m = map(src);
7889        assert!(m.rows.iter().all(|r| !r.directive));
7890        assert!(rendered(&m).contains(":::vis{.public}"));
7891    }
7892
7893    #[test]
7894    fn a_footnote_reference_keeps_its_paragraph_visible() {
7895        // Regression: `footnote_reference` was in neither `is_inline_kind` nor
7896        // the inline walker, so a paragraph carrying one failed the "all children
7897        // inline" test, was walked as a container of blocks, and rendered as
7898        // empty rows with no caret stop anywhere — the whole line vanished.
7899        let src = "A claim[^1] and more.\n";
7900        let m = map(src);
7901        assert_eq!(rendered(&m).trim_end(), "A claim[1] and more.");
7902        // The `^` is spelling, not text: hidden the way a link's `](dest)` is.
7903        assert!(!rendered(&m).contains('^'));
7904    }
7905
7906    #[test]
7907    fn a_footnote_reference_is_raised_and_the_prose_around_it_is_not() {
7908        // What makes `[1]` read as a reference rather than as bracketed text.
7909        // The brackets ride with the label: the chip is one raised mark.
7910        let m = map("A claim[^1] and more.\n");
7911        assert_eq!(baselines_of(&m, '1'), vec![Baseline::Super]);
7912        assert_eq!(baselines_of(&m, '['), vec![Baseline::Super]);
7913        assert_eq!(baselines_of(&m, ']'), vec![Baseline::Super]);
7914        assert_eq!(baselines_of(&m, 'A'), vec![Baseline::Normal]);
7915    }
7916
7917    #[test]
7918    fn a_footnote_reference_keeps_the_link_role_it_had() {
7919        // The raised baseline is added to the role, not swapped for it: every
7920        // frontend already paints `Role::Link`, and a reference is one.
7921        let m = map("A claim[^1].\n");
7922        let label = m
7923            .rows
7924            .iter()
7925            .flat_map(|r| &r.glyphs)
7926            .find(|g| g.ch == '1')
7927            .unwrap();
7928        assert_eq!(label.style.role, Role::Link);
7929        assert_eq!(label.style.baseline, Baseline::Super);
7930    }
7931
7932    /// The [`Role`] of the first glyph spelling `ch` — how a test reads one
7933    /// run's styling off a map without caring which row it landed on.
7934    fn role_of(m: &VisualMap, ch: char) -> Role {
7935        m.rows
7936            .iter()
7937            .flat_map(|r| r.glyphs.iter())
7938            .find(|g| g.ch == ch)
7939            .unwrap_or_else(|| panic!("no glyph spelling {ch:?}"))
7940            .style
7941            .role
7942    }
7943
7944    #[test]
7945    fn a_markdown_highlight_is_a_mark_and_a_coloured_one_names_its_colour() {
7946        // twig 3.3's `highlight`/`highlight_colors`, which `parse_extensions`
7947        // turns on for every leaf document: `==text==` is a `mark` in Markdown
7948        // and not the literal `==` it used to be, and `==🔴 text==` is one
7949        // carrying a colour.
7950        //
7951        // `doc_built` rather than `map`, deliberately — the extensions are
7952        // leaf's choice, not twig's default, so a test that parsed bare
7953        // Markdown here would be testing a document leaf never builds.
7954        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
7955        assert_eq!(role_of(&doc.vmap, 'y'), Role::Mark(None));
7956        assert_eq!(
7957            role_of(&doc.vmap, 'r'),
7958            Role::Mark(Some(MarkColor::Red)),
7959            "the `data-color` twig stripped the emoji into"
7960        );
7961        assert_eq!(role_of(&doc.vmap, 'P'), Role::Body);
7962    }
7963
7964    #[test]
7965    fn the_emoji_that_named_a_highlight_is_markup_and_never_drawn() {
7966        // The colour is *spelling*: twig strips the emoji out of the mark's
7967        // content, so the reader sees the words and the wash, never the circle.
7968        // Drawing it would put a character in the rendered text that the author
7969        // wrote as syntax — the same mistake as drawing an emphasis's `*`.
7970        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
7971        let drawn: String = doc.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
7972        assert_eq!(drawn, "Plain yes and red ok");
7973    }
7974
7975    #[test]
7976    fn a_superscript_and_a_subscript_sit_off_the_baseline() {
7977        // Regression: both rendered flat, so the toolbar's superscript button
7978        // produced markup that looked exactly like the text around it.
7979        let m = map_djot("H~2~O and x^2^\n");
7980        assert_eq!(baselines_of(&m, '2'), vec![Baseline::Sub, Baseline::Super]);
7981        assert_eq!(baselines_of(&m, 'H'), vec![Baseline::Normal]);
7982        assert_eq!(baselines_of(&m, 'O'), vec![Baseline::Normal]);
7983    }
7984
7985    #[test]
7986    fn a_raised_glyph_keeps_the_style_it_was_raised_out_of() {
7987        // Why this is a `Baseline` and not a `Role`: raising a glyph says where
7988        // it sits, and must not cost it what it already was.
7989        let m = map_djot("# Heading x^2^\n");
7990        let two = m
7991            .rows
7992            .iter()
7993            .flat_map(|r| &r.glyphs)
7994            .find(|g| g.ch == '2')
7995            .unwrap();
7996        assert_eq!(two.style.baseline, Baseline::Super);
7997        assert_eq!(two.style.role, Role::Heading(1), "still heading text");
7998    }
7999
8000    #[test]
8001    fn a_footnote_references_brackets_are_decoration_and_only_its_label_is_a_stop() {
8002        let src = "see[^note] here\n";
8003        let m = map(src);
8004        // `[^note]` spans 3..10, its label `note` 5..9. The caret walks the
8005        // label; the brackets are drawn but never stood on, as a table's are,
8006        // and the `[^`/`]` bytes are stepped over like any hidden delimiter.
8007        let stops: Vec<usize> = m
8008            .rows
8009            .iter()
8010            .flat_map(|r| &r.glyphs)
8011            .filter(|g| g.stop)
8012            .map(|g| g.src)
8013            .collect();
8014        for off in 5..9 {
8015            assert!(
8016                stops.contains(&off),
8017                "label byte {off} isn't a caret stop: {stops:?}"
8018            );
8019        }
8020        for off in [3usize, 4, 9] {
8021            assert!(
8022                !stops.contains(&off),
8023                "delimiter byte {off} is a caret stop: {stops:?}"
8024            );
8025        }
8026    }
8027
8028    #[test]
8029    fn a_task_item_draws_its_box_where_the_bullet_would_be() {
8030        // Regression: the `[ ] ` is markup twig consumes — the item's paragraph
8031        // content starts past it — so a task item used to render as `• todo`,
8032        // identical to a plain bullet and with no way to see it was ticked.
8033        let m = map("- [ ] todo\n- [x] done\n- plain\n");
8034        assert_eq!(rendered(&m), "☐ todo\n☑ done\n• plain");
8035
8036        // The tick rides the item's first row, for a GUI that paints its own box.
8037        let ticks: Vec<Option<bool>> = m.rows.iter().map(|r| r.task).collect();
8038        assert_eq!(ticks, [Some(false), Some(true), None]);
8039    }
8040
8041    #[test]
8042    fn a_task_items_box_survives_a_wrap_and_marks_only_the_first_row() {
8043        let m = map_at(
8044            "- [x] a much longer task that has to wrap somewhere\n",
8045            Some(20),
8046        );
8047        assert!(m.rows.len() > 1, "the item should wrap: {:?}", rendered(&m));
8048        assert_eq!(m.rows[0].task, Some(true));
8049        assert!(
8050            m.rows[1..].iter().all(|r| r.task.is_none()),
8051            "only the first row"
8052        );
8053        // The continuation lines hang under the box, not under column zero.
8054        assert!(
8055            rendered(&m)
8056                .lines()
8057                .nth(1)
8058                .is_some_and(|l| l.starts_with("  "))
8059        );
8060    }
8061
8062    #[test]
8063    fn a_bracket_in_an_items_prose_is_not_a_checkbox() {
8064        // `task_checked` finds the box past the list marker; a plain item whose
8065        // text merely contains a bracket has none, and must keep its bullet.
8066        let m = map("- see [1] below\n");
8067        assert_eq!(rendered(&m), "• see [1] below");
8068        assert_eq!(m.rows[0].task, None);
8069    }
8070
8071    #[test]
8072    fn a_footnote_definition_renders_where_it_was_written() {
8073        // Regression: twig parses `[^1]: …` as a root *beside* `doc` — not a
8074        // child of it — so the walk from `doc` never reached one and every byte
8075        // of the note's body rendered as nothing at all.
8076        let src = "A claim[^1].\n\n[^1]: The note body.\n\nAfter.\n";
8077        let m = map(src);
8078        let text = rendered(&m);
8079        assert!(
8080            text.contains("The note body."),
8081            "the note body is invisible: {text:?}"
8082        );
8083        // In source order — between the paragraph that cites it and the one
8084        // after — not hoisted to the end, and marked to match its reference.
8085        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
8086        assert_eq!(lines, ["A claim[1].", "[1] The note body.", "After."]);
8087    }
8088
8089    #[test]
8090    fn a_footnote_definitions_body_maps_to_its_own_source_bytes() {
8091        let src = "x[^a].\n\n[^a]: body\n";
8092        let m = map(src);
8093        // `body` sits at 14..18. Its glyphs must map there — a marker that ate
8094        // the offsets would put the caret in the wrong place on every click.
8095        let body: Vec<(char, usize)> = m
8096            .rows
8097            .iter()
8098            .flat_map(|r| &r.glyphs)
8099            .filter(|g| g.stop && g.src >= 14)
8100            .map(|g| (g.ch, g.src))
8101            .collect();
8102        assert_eq!(body, [('b', 14), ('o', 15), ('d', 16), ('y', 17)]);
8103    }
8104
8105    #[test]
8106    fn an_empty_footnote_definition_still_shows_its_marker() {
8107        // The instant `[^1]: ` has been typed and nothing after it. `blocks`
8108        // renders no child, so without the explicit marker row the definition
8109        // wouldn't appear at all until something was typed into it.
8110        let src = "x[^1]\n\n[^1]:\n";
8111        let m = map(src);
8112        assert!(
8113            rendered(&m).contains("[1] "),
8114            "no marker row: {:?}",
8115            rendered(&m)
8116        );
8117    }
8118
8119    #[test]
8120    fn a_footnote_definition_wearing_a_long_label_indents_its_wrapped_body() {
8121        let src = "x[^src]\n\n[^src]: one two three four five six seven\n";
8122        let m = map_at(src, Some(24));
8123        let text = rendered(&m);
8124        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
8125        // Continuation lines hang under the marker, as a list item's do — the
8126        // indent is the marker's own width, not a fixed one.
8127        assert_eq!(lines[1].trim_end(), "[src] one two three four");
8128        assert!(
8129            lines[2].starts_with("      "),
8130            "body doesn't hang: {:?}",
8131            lines[2]
8132        );
8133        assert_eq!(lines[2].trim(), "five six seven");
8134    }
8135
8136    #[test]
8137    fn a_code_block_leaves_exactly_one_blank_row_below_it() {
8138        // The closing fence line used to be miscounted as a blank separator,
8139        // opening a phantom second gap under the block. One block boundary is
8140        // one blank row, code block or not.
8141        let src = "para\n\n```\ncode\n```\n\nafter\n";
8142        let m = map(src);
8143        let code_end = m.code_blocks[0].rows_span.end;
8144        let after = m
8145            .rows
8146            .iter()
8147            .position(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "after")
8148            .unwrap();
8149        assert_eq!(
8150            after - code_end,
8151            1,
8152            "exactly one row between code and 'after'"
8153        );
8154    }
8155
8156    #[test]
8157    fn a_fenced_block_publishes_its_language_on_its_code_block() {
8158        // The info string becomes the block's label; a bare fence and an indented
8159        // block carry none.
8160        assert_eq!(
8161            map("```rust\nlet x = 1;\n```\n").code_blocks[0]
8162                .lang
8163                .as_deref(),
8164            Some("rust")
8165        );
8166        assert_eq!(map("```\nplain\n```\n").code_blocks[0].lang, None);
8167        assert_eq!(map("    indented\n").code_blocks[0].lang, None);
8168    }
8169
8170    /// The token every glyph spelling `ch` carries, in row order — how a test
8171    /// reads a block's highlighting off the map.
8172    fn tokens_of(m: &VisualMap, ch: char) -> Vec<Option<Token>> {
8173        m.rows
8174            .iter()
8175            .flat_map(|r| r.glyphs.iter())
8176            .filter(|g| g.ch == ch)
8177            .map(|g| g.style.token)
8178            .collect()
8179    }
8180
8181    #[cfg(feature = "syntax")]
8182    #[test]
8183    fn a_fenced_block_in_a_known_language_carries_tokens() {
8184        // `let` is a keyword, the string literal a string, and the plain
8185        // identifier `x` nothing at all — it draws in the code colour. Every
8186        // glyph is still `Role::Code`: a token is beside the role, not instead.
8187        let m = map("```rust\nlet x = \"s\";\n```\n");
8188        assert_eq!(tokens_of(&m, 'l'), vec![Some(Token::Keyword)]);
8189        assert_eq!(tokens_of(&m, 'x'), vec![None]);
8190        assert_eq!(tokens_of(&m, '"'), vec![Some(Token::String); 2]);
8191        assert!(
8192            m.rows
8193                .iter()
8194                .filter(|r| r.code)
8195                .flat_map(|r| r.glyphs.iter())
8196                .all(|g| g.style.role == Role::Code),
8197            "a token replaced the code role"
8198        );
8199    }
8200
8201    #[cfg(feature = "syntax")]
8202    #[test]
8203    fn a_token_changes_nothing_about_where_a_glyph_is() {
8204        // The same block with and without a language it can be highlighted in
8205        // lays out identically: same rows, same offsets, same stops. Only the
8206        // token differs, so the caret walks a highlighted block as it walked an
8207        // unhighlighted one.
8208        let hl = map("```rust\nlet x = 1; // c\nfn f() {}\n```\n");
8209        let plain = map("```text\nlet x = 1; // c\nfn f() {}\n```\n");
8210        assert_eq!(hl.rows.len(), plain.rows.len());
8211        for (a, b) in hl.rows.iter().zip(&plain.rows) {
8212            assert_eq!(a.end_src, b.end_src);
8213            assert_eq!(a.glyphs.len(), b.glyphs.len());
8214            for (ga, gb) in a.glyphs.iter().zip(&b.glyphs) {
8215                assert_eq!((ga.ch, ga.src, ga.stop), (gb.ch, gb.src, gb.stop));
8216                assert_eq!(ga.style.token(None), gb.style);
8217            }
8218        }
8219        assert!(tokens_of(&hl, 'l').iter().any(Option::is_some));
8220        assert!(tokens_of(&plain, 'l').iter().all(Option::is_none));
8221    }
8222
8223    #[test]
8224    fn a_block_with_no_language_to_highlight_in_carries_no_tokens() {
8225        // A bare fence, an indented block, a fence in a language no grammar
8226        // covers, and inline code all draw as plain code — and so does a
8227        // `rust` fence when the `syntax` feature is off.
8228        for src in [
8229            "```\nlet x = 1;\n```\n",
8230            "    let x = 1;\n",
8231            "```no-such-language\nlet x = 1;\n```\n",
8232            "a `let x` b\n",
8233        ] {
8234            assert!(
8235                tokens_of(&map(src), 'l').iter().all(Option::is_none),
8236                "{src:?} was highlighted"
8237            );
8238        }
8239        #[cfg(not(feature = "syntax"))]
8240        assert!(
8241            tokens_of(&map("```rust\nlet x = 1;\n```\n"), 'l')
8242                .iter()
8243                .all(Option::is_none)
8244        );
8245    }
8246
8247    #[test]
8248    fn inline_code_is_not_a_code_block() {
8249        // A `code` span inside prose is styled by role, not boxed: it's part of a
8250        // normal paragraph row, so it names no `code_blocks` entry.
8251        let m = map("a `snippet` b\n");
8252        assert!(m.code_blocks.is_empty(), "inline code wrongly boxed");
8253        assert!(
8254            m.rows.iter().all(|r| !r.code),
8255            "inline code flagged a code row"
8256        );
8257    }
8258
8259    #[test]
8260    fn caret_steps_over_hidden_delimiters() {
8261        // "a **bold** c": bytes 8,9 are the closing ** — no glyph. Moving right
8262        // from 'd' (src 7) lands on the space before 'c' (src 10), not inside **.
8263        let m = map("a **bold** c\n");
8264        let (r, c) = m.pos_of_offset(7);
8265        assert_eq!(m.offset_of_pos(r, c + 1), 10);
8266    }
8267
8268    // ── the structural view of a table ───────────────────────────────────────
8269
8270    #[test]
8271    fn a_table_is_published_structurally_beside_its_picture() {
8272        let m = map(TABLE);
8273        let t = &m.tables[0];
8274        let cell = |r: usize, c: usize| -> String {
8275            t.grid[r].cells[c].glyphs.iter().map(|g| g.ch).collect()
8276        };
8277        assert_eq!(t.grid.len(), 3, "head + two body rows");
8278        assert_eq!(
8279            (cell(0, 0), cell(0, 1), cell(1, 0), cell(2, 1)),
8280            ("Name".into(), "Qty".into(), "Pear".into(), "12".into())
8281        );
8282        assert_eq!(
8283            t.grid.iter().map(|r| r.head).collect::<Vec<_>>(),
8284            [true, false, false]
8285        );
8286        // The alignment the delimiter row spelled, carried per cell — the only
8287        // place it survives, since the parser consumes that row.
8288        assert!(matches!(t.grid[1].cells[0].align, Alignment::Left));
8289        assert!(matches!(t.grid[1].cells[1].align, Alignment::Right));
8290    }
8291
8292    #[test]
8293    fn a_block_media_is_published_structurally_beside_its_placeholder() {
8294        let m = map("intro\n\n![a cat](img/cat.png)\n\nend\n");
8295        assert_eq!(m.media.len(), 1, "one block image");
8296        let img = &m.media[0];
8297        assert_eq!(img.destination, "img/cat.png");
8298        assert_eq!(img.alt, "a cat");
8299        // The placeholder row named by `rows_span` carries the label a plain
8300        // surface paints and a capable frontend replaces.
8301        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
8302        assert_eq!(
8303            img.rows_span.end - img.rows_span.start,
8304            1,
8305            "one placeholder row"
8306        );
8307        assert_eq!(row_text(img.rows_span.start), "🖼 a cat");
8308        // The row carries the mark `media_spans` derives the side-table from.
8309        assert!(m.rows[img.rows_span.start].media.is_some());
8310    }
8311
8312    #[test]
8313    fn an_image_without_alt_labels_itself_with_its_filename() {
8314        let m = map("![](photos/beach.jpg)\n");
8315        let row = &m.rows[m.media[0].rows_span.start];
8316        assert_eq!(
8317            row.glyphs.iter().map(|g| g.ch).collect::<String>(),
8318            "🖼 beach.jpg"
8319        );
8320        assert_eq!(m.media[0].alt, "");
8321    }
8322
8323    #[test]
8324    fn an_empty_cells_home_is_read_from_either_shape_of_span() {
8325        // A whole-row span: the cell's pipes are the `col`-th and next.
8326        let row = "|  |  |";
8327        assert_eq!(empty_cell_offset(row, 10, 0), 12);
8328        assert_eq!(empty_cell_offset(row, 10, 1), 15);
8329        // A cell's own span, opening pipe to closing pipe exclusive: the same
8330        // homes, each read from its own span.
8331        assert_eq!(empty_cell_offset("|  ", 10, 0), 12);
8332        assert_eq!(empty_cell_offset("|  ", 13, 1), 15);
8333        // Nothing to stand in: just inside the pipe, never past the span.
8334        assert_eq!(empty_cell_offset("|", 10, 0), 11);
8335        assert_eq!(empty_cell_offset("", 10, 1), 10);
8336    }
8337
8338    #[test]
8339    fn a_hidden_marks_content_end_is_a_caret_home_but_not_a_glyph_stop() {
8340        // `a **bold** b`: the `d` is at 7, the content ends at 8, the closing
8341        // `**` draws nothing, and the space after it is at 10. Two homes at one
8342        // spot on screen: 8 (inside the bold) and 10 (past it).
8343        let m = map("a **bold** b\n");
8344        assert!(
8345            !m.stops.contains(&8),
8346            "8 has no glyph, so it is no glyph stop"
8347        );
8348        assert_eq!(m.mark_ends, vec![8]);
8349        assert!(m.is_stop(8), "but the caret may rest there");
8350        assert_eq!(m.snap_to_stop(8), 8, "and is left there when placed there");
8351        // Left/Right take both homes; the character-pairing walk takes one.
8352        assert_eq!(m.caret_stop_after(7), Some(8));
8353        assert_eq!(m.caret_stop_after(8), Some(10));
8354        assert_eq!(m.caret_stop_before(10), Some(8));
8355        assert_eq!(m.caret_stop_before(8), Some(7));
8356        assert_eq!(m.stop_after(7), Some(10));
8357        assert_eq!(m.stop_before(10), Some(7));
8358        // Drawn where the next glyph is: after the `d`, not on it.
8359        assert_eq!(m.pos_of_offset(8), m.pos_of_offset(10));
8360    }
8361
8362    #[test]
8363    fn every_hidden_inline_mark_gives_its_content_end_a_home() {
8364        // One end per mark, whatever it is spelled with; nested marks closing
8365        // together share the outer's end and the inner's alike.
8366        assert_eq!(
8367            map("*em* `code` [link](u) ~~del~~\n").mark_ends,
8368            vec![3, 10, 17, 27]
8369        );
8370        assert_eq!(map("***both***\n").mark_ends, vec![7]);
8371        // A mark that closes at its row's end coincides with the row's own end
8372        // stop — one offset, in both tables.
8373        let m = map("**bold**\n");
8374        assert_eq!(m.mark_ends, vec![6]);
8375        assert!(m.stops.contains(&6));
8376        // Revealed, the delimiter is glyphs of its own and the end is an
8377        // ordinary glyph stop: nothing to add.
8378        let mut ed = Editor::new_str("a **bold** b\n", Format::Markdown).unwrap();
8379        let src = "a **bold** b\n";
8380        let revealed = build(
8381            &ed.nodes().unwrap(),
8382            src,
8383            Some(80),
8384            false,
8385            &Surface::default(),
8386            Some(Reveal::full(0..src.len())),
8387        );
8388        assert!(revealed.mark_ends.is_empty());
8389        assert!(revealed.stops.contains(&8));
8390    }
8391
8392    #[test]
8393    fn a_marks_content_end_is_a_home_inside_a_table_cell() {
8394        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
8395        let m = map(src);
8396        let end = src.find("bold").unwrap() + 4; // 32, before the closing `**`
8397        assert_eq!(m.mark_ends, vec![end]);
8398        assert_eq!(m.snap_to_stop(end), end);
8399        // Drawn after the `d`, in this cell — where the cell's own end stop is.
8400        assert_eq!(m.pos_of_offset(end), m.pos_of_offset(end + 2));
8401    }
8402
8403    #[test]
8404    fn a_block_media_gives_the_caret_a_home_before_and_after_it() {
8405        // `![x](y)` on its own line: the caret can rest in front of the image
8406        // (its start) and just past it (the row end), and nowhere inside the
8407        // markup — the same coarse mapping a thematic break uses.
8408        let src = "![x](y.png)\n";
8409        let m = map(src);
8410        let img = &m.rows[m.media[0].rows_span.start];
8411        let start = 0; // the image opens the document
8412        let end = "![x](y.png)".len();
8413        // Every placeholder glyph maps to the image start and is a stop there.
8414        assert!(img.glyphs.iter().all(|g| g.src == start && g.stop));
8415        assert_eq!(img.end_src, end, "the row ends past the image");
8416        assert_eq!(m.stops.first(), Some(&start));
8417        assert!(m.stops.contains(&end), "a stop sits after the image");
8418        // Nothing inside the markup is a stop.
8419        assert!(!m.stops.iter().any(|&s| s > start && s < end));
8420    }
8421
8422    #[test]
8423    fn an_inline_image_amid_text_is_not_a_block_media() {
8424        // An image sharing its line with prose isn't block-level: it stays in the
8425        // inline path (rendered as its alt text), and publishes no MediaInfo.
8426        let m = map("see ![a cat](cat.png) here\n");
8427        assert!(m.media.is_empty(), "not a block image");
8428        assert!(
8429            rendered(&m).contains("a cat"),
8430            "alt text still renders inline"
8431        );
8432    }
8433
8434    /// The block images `Doc` publishes for `src`, driven through the real
8435    /// production build (`build_visual` → `build_cached`) with `html_elements`
8436    /// on — the path a `<picture>` actually travels. Not the raw `build` the
8437    /// other tests use: the editor's flat whole-arena snapshot tangles the links
8438    /// of inline-promoted HTML (phantom roots, dangling `parent`s), which only
8439    /// the per-block subtree walk `build_cached` does untangles.
8440    fn doc_media(src: &str) -> Vec<MediaInfo> {
8441        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
8442        doc.build_visual(80);
8443        doc.vmap.media.clone()
8444    }
8445
8446    #[test]
8447    fn a_video_block_is_media_with_its_src_poster_and_kind() {
8448        // The load-bearing assumption of video support: twig has no `video` node
8449        // kind, so `html_elements` promotion must land a `<video>` as a generic
8450        // `element` whose tag name and attributes survive onto `FlatNode` — the
8451        // same treatment `<picture>` gets. If that ever stops holding, this is
8452        // the test that says so.
8453        let m = doc_media("<video src=\"clip.mp4\" poster=\"still.png\" controls>\n</video>\n");
8454        assert_eq!(m.len(), 1, "the video is one block media");
8455        assert_eq!(m[0].kind, MediaKind::Video);
8456        assert_eq!(m[0].destination, "clip.mp4");
8457        assert_eq!(m[0].poster, "still.png");
8458    }
8459
8460    #[test]
8461    fn a_single_line_video_is_a_block_too() {
8462        // The spelling everyone actually writes. It used to parse as a paragraph
8463        // of raw inline HTML — CommonMark opens a block on a complete tag only
8464        // when the line ends there, and its fixed tag list predates `<video>` —
8465        // so the tags never reached core as an element at all. twig 2.5.1 widened
8466        // that list under `html_elements`; this is the test that would catch the
8467        // pin sliding back.
8468        let m = doc_media("<video src=\"clip.mp4\" controls></video>\n");
8469        assert_eq!(m.len(), 1, "single-line <video> is a block");
8470        assert_eq!(m[0].kind, MediaKind::Video);
8471        assert_eq!(m[0].destination, "clip.mp4");
8472    }
8473
8474    #[test]
8475    fn a_single_line_picture_is_a_block_with_its_alternatives() {
8476        // `<picture>` had the identical gap and it went unnoticed because the
8477        // conventional spelling breaks the lines. Same twig fix covers it.
8478        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\
8479                   <img src=\"l.svg\" alt=\"banner\"></picture>\n";
8480        let m = doc_media(src);
8481        assert_eq!(m.len(), 1);
8482        assert_eq!(m[0].kind, MediaKind::Image);
8483        assert_eq!(m[0].destination, "l.svg");
8484        assert_eq!(m[0].resolve(ColorScheme::Dark), "d.svg");
8485    }
8486
8487    #[test]
8488    fn an_audio_block_is_media_with_no_poster() {
8489        let m = doc_media("<audio src=\"take.mp3\" controls>\n</audio>\n");
8490        assert_eq!(m.len(), 1);
8491        assert_eq!(m[0].kind, MediaKind::Audio);
8492        assert_eq!(m[0].destination, "take.mp3");
8493        assert!(m[0].poster.is_empty(), "audio has no poster frame");
8494    }
8495
8496    #[test]
8497    fn a_videos_source_children_are_its_candidates_typed_by_mime() {
8498        // A `<video>` with no `src` of its own — the common shape, since it's how
8499        // you offer more than one codec. The candidates come from `<source src>`
8500        // (not `srcset`, which is `<picture>`'s spelling) and carry their MIME.
8501        let src = "<video controls>\n\
8502                   <source src=\"a.webm\" type=\"video/webm\">\n\
8503                   <source src=\"a.mp4\" type=\"video/mp4\">\n\
8504                   fallback\n\
8505                   </video>\n";
8506        let m = doc_media(src);
8507        assert_eq!(m.len(), 1);
8508        assert!(
8509            m[0].destination.is_empty(),
8510            "no src attribute on the element"
8511        );
8512        assert_eq!(m[0].sources.len(), 2);
8513        assert_eq!(m[0].sources[0].srcset, "a.webm");
8514        assert_eq!(m[0].sources[0].mime, "video/webm");
8515        assert_eq!(m[0].sources[1].srcset, "a.mp4");
8516        // With an empty destination, `resolve` falls through to the first
8517        // candidate rather than handing the frontend nothing to load.
8518        assert_eq!(m[0].resolve(ColorScheme::Light), "a.webm");
8519    }
8520
8521    #[test]
8522    fn a_video_placeholder_row_carries_its_own_sigil_and_mark() {
8523        // The placeholder contract images already hold, now for a video: the row
8524        // renders as a labelled stand-in a plain surface can paint as-is, and
8525        // carries the mark a capable frontend replaces it from.
8526        let src = "<video src=\"clip.mp4\" controls>\n</video>\n";
8527        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
8528        doc.build_visual(80);
8529        let row = &doc.vmap.rows[doc.vmap.media[0].rows_span.start];
8530        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
8531        assert!(
8532            text.starts_with('🎬'),
8533            "video sigil, not the image one: {text:?}"
8534        );
8535        assert!(row.media.is_some(), "the mark rides the placeholder row");
8536    }
8537
8538    #[test]
8539    fn a_picture_block_carries_its_source_alternatives() {
8540        // A `<picture>` with a dark-mode `<source>`: one block image, whose
8541        // fallback destination is the `<img>` and whose `sources` carry the
8542        // `<source>`'s media + srcset for a theme-aware frontend to pick.
8543        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"banner\"></picture>\n";
8544        let images = doc_media(src);
8545        assert_eq!(images.len(), 1, "the picture is one block image");
8546        let img = &images[0];
8547        assert_eq!(img.destination, "light.svg", "fallback is the <img>");
8548        assert_eq!(img.alt, "banner");
8549        assert_eq!(
8550            img.sources,
8551            vec![MediaSource {
8552                media: "(prefers-color-scheme: dark)".into(),
8553                srcset: "dark.svg".into(),
8554                mime: String::new(),
8555            }],
8556        );
8557    }
8558
8559    #[test]
8560    fn a_picture_inside_a_heading_is_still_a_block_media_with_sources() {
8561        // fig.md's shape: the banner is an `<h1>` wrapping the `<picture>`.
8562        let src = "<h1><picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\"><img src=\"l.svg\" alt=\"fig\"></picture></h1>\n";
8563        let images = doc_media(src);
8564        assert_eq!(images.len(), 1, "heading-wrapped picture is a block image");
8565        assert_eq!(images[0].destination, "l.svg");
8566        assert_eq!(images[0].sources.len(), 1);
8567        assert_eq!(images[0].sources[0].srcset, "d.svg");
8568    }
8569
8570    #[test]
8571    fn a_plain_image_has_no_media_sources() {
8572        // A bare Markdown image carries an empty `sources` — nothing to pick from.
8573        let images = doc_media("![alt](p.png)\n");
8574        assert_eq!(images.len(), 1);
8575        assert!(
8576            images[0].sources.is_empty(),
8577            "no <picture>, no alternatives"
8578        );
8579    }
8580
8581    #[test]
8582    fn resolve_picks_the_source_matching_the_scheme() {
8583        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"b\"></picture>\n";
8584        let images = doc_media(src);
8585        let img = &images[0];
8586        // Dark theme takes the dark source; light falls through to the <img>.
8587        assert_eq!(img.resolve(ColorScheme::Dark), "dark.svg");
8588        assert_eq!(img.resolve(ColorScheme::Light), "light.svg");
8589    }
8590
8591    #[test]
8592    fn resolve_falls_back_for_a_plain_image_and_unknown_media() {
8593        // A plain image ignores the scheme.
8594        let plain = doc_media("![a](p.png)\n");
8595        assert_eq!(plain[0].resolve(ColorScheme::Dark), "p.png");
8596
8597        // A <source> with an unrecognized media query is skipped; a light source
8598        // is taken under a light theme.
8599        let m = doc_media(
8600            "<picture><source media=\"print\" srcset=\"p.svg\"><source media=\"(prefers-color-scheme: light)\" srcset=\"l.svg\"><img src=\"f.svg\" alt=\"x\"></picture>\n",
8601        );
8602        assert_eq!(m[0].resolve(ColorScheme::Light), "l.svg");
8603        assert_eq!(
8604            m[0].resolve(ColorScheme::Dark),
8605            "f.svg",
8606            "no dark source → <img>"
8607        );
8608    }
8609
8610    #[test]
8611    fn resolve_reads_the_first_srcset_url_ignoring_descriptors() {
8612        // A comma/descriptor srcset resolves to its first URL.
8613        assert_eq!(first_srcset_url("a.png 1x, b.png 2x"), Some("a.png"));
8614        assert_eq!(first_srcset_url("  solo.svg  "), Some("solo.svg"));
8615        assert_eq!(first_srcset_url(""), None);
8616        // An empty (unconditional) media always matches.
8617        assert!(media_matches("", ColorScheme::Light));
8618        assert!(media_matches(
8619            "(prefers-color-scheme:dark)",
8620            ColorScheme::Dark
8621        ));
8622        assert!(!media_matches(
8623            "(prefers-color-scheme: dark)",
8624            ColorScheme::Light
8625        ));
8626    }
8627
8628    #[test]
8629    fn a_block_media_carries_its_list_prefix() {
8630        // An image that is a list item's body opens past the bullet, like every
8631        // other block does.
8632        let m = map("- ![alt](p.png)\n");
8633        let row = &m.rows[m.media[0].rows_span.start];
8634        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
8635        assert!(
8636            text.starts_with("• "),
8637            "the list marker prefixes the image row: {text:?}"
8638        );
8639        assert!(text.contains("🖼 alt"));
8640    }
8641
8642    #[test]
8643    fn the_structural_table_spans_exactly_its_drawn_rows() {
8644        // A frontend drawing its own grid skips `rows_span` and renders from
8645        // `grid`. If the span were short the leftover border rows would be
8646        // painted as text under the real table; if long it would eat a
8647        // neighbouring paragraph. Both are silent, so pin it to the picture.
8648        let m = map(&format!("before\n\n{TABLE}\nafter\n"));
8649        let t = &m.tables[0];
8650        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
8651        assert!(
8652            row_text(t.rows_span.start).starts_with('┌'),
8653            "opens on the top border"
8654        );
8655        assert!(
8656            row_text(t.rows_span.end - 1).starts_with('└'),
8657            "closes on the bottom border"
8658        );
8659        assert!(
8660            !row_text(t.rows_span.start - 1).contains('┌'),
8661            "the row before the span is not the table's"
8662        );
8663        assert_eq!(
8664            row_text(t.rows_span.end),
8665            "",
8666            "the span ends before the gap row"
8667        );
8668    }
8669
8670    #[test]
8671    fn a_nested_tables_structure_carries_the_block_prefix() {
8672        // The picture puts the quote's gutter on every row of the grid. A
8673        // frontend drawing its own table has to draw that too and start past it,
8674        // so the prefix has to travel with the structure — without it a quoted
8675        // table renders flush at the margin and leaves the quote it's in.
8676        let m = map("> | a | b |\n> |---|---|\n> | c | d |\n");
8677        let t = &m.tables[0];
8678        let prefix: String = t.prefix.iter().map(|g| g.ch).collect();
8679        assert_eq!(prefix, "│ ", "the quote's gutter should ride the structure");
8680        // And it matches what the picture actually drew.
8681        let drawn: String = m.rows[t.rows_span.start]
8682            .glyphs
8683            .iter()
8684            .map(|g| g.ch)
8685            .collect();
8686        assert!(
8687            drawn.starts_with(&prefix),
8688            "picture and structure disagree: {drawn:?}"
8689        );
8690    }
8691
8692    #[test]
8693    fn a_top_level_table_carries_no_prefix() {
8694        assert!(map(TABLE).tables[0].prefix.is_empty());
8695    }
8696
8697    #[test]
8698    fn structural_cells_are_unwrapped_even_when_the_picture_wraps_them() {
8699        // The picture wraps a cell to its column; a frontend laying the grid out
8700        // in pixels needs the text as the document spells it, before that
8701        // decision. Narrow enough that the drawn cell must break.
8702        let src = "| Name |\n|------|\n| alpha beta gamma |\n";
8703        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8704        let m = build_t(&ed.nodes().unwrap(), src, Some(12));
8705        let drawn = rendered(&m);
8706        let cell: String = m.tables[0].grid[1].cells[0]
8707            .glyphs
8708            .iter()
8709            .map(|g| g.ch)
8710            .collect();
8711        assert_eq!(
8712            cell, "alpha beta gamma",
8713            "structure must not carry the wrap"
8714        );
8715        assert!(
8716            drawn.lines().count() > 5,
8717            "the picture should have wrapped, else this proves nothing:\n{drawn}"
8718        );
8719    }
8720
8721    // ── display columns ──────────────────────────────────────────────────────
8722
8723    #[test]
8724    fn a_table_column_is_as_wide_as_its_cells_are_drawn() {
8725        // A column sized by counting characters is drawn narrower than the text
8726        // it has to hold — `你好` is two characters in four cells — and the cell
8727        // spills over the border it is supposed to sit inside, taking the whole
8728        // grid out of square with it. Squareness is the property: every row of a
8729        // grid is drawn to the same column, whatever its cells are spelled with.
8730        for src in [
8731            "| A | B |\n|---|---|\n| 你好 | y |\n",
8732            "| A | B |\n|---|---|\n| a👨‍👩‍👧b | y |\n",
8733            "| A | 漢字 |\n|---|---|\n| x | y |\n",
8734        ] {
8735            let m = map(src);
8736            let widths: Vec<usize> = m.rows.iter().map(|r| r.width()).collect();
8737            assert!(
8738                widths.windows(2).all(|w| w[0] == w[1]),
8739                "ragged grid {widths:?} for {src:?}:\n{}",
8740                rendered(&m)
8741            );
8742        }
8743    }
8744
8745    #[test]
8746    fn a_cell_wrapped_narrow_never_breaks_inside_a_character() {
8747        // A column too narrow for its cell hard-breaks the text, and every line
8748        // of it is given an end stop just past its last glyph. Broken into runs
8749        // of four glyphs, the first line of this cell ends between `👨‍👩` and the
8750        // joiner holding `👧` on — so its end stop lands inside a character,
8751        // where a click or Down can reach it and the next Backspace takes the
8752        // cluster apart from the middle.
8753        let src = "| A |\n|---|\n| 👨‍👩‍👧👨‍👩‍👧 |\n";
8754        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8755        let m = build_t(&ed.nodes().unwrap(), src, Some(8));
8756        let boundaries: Vec<usize> = src
8757            .grapheme_indices(true)
8758            .map(|(i, _)| i)
8759            .chain(std::iter::once(src.len()))
8760            .collect();
8761        for off in (0..=src.len()).filter(|&o| m.is_stop(o)) {
8762            assert!(
8763                boundaries.contains(&off),
8764                "stop at {off} is inside a character:\n{}",
8765                rendered(&m)
8766            );
8767        }
8768    }
8769
8770    #[test]
8771    fn a_wrapped_cell_keeps_every_line_inside_its_column() {
8772        // The width is a promise in a table, where a glyph past the column lands
8773        // on the border or in the next cell — and it is a promise about cells,
8774        // which is not what a count of glyphs measures.
8775        let src = "| A |\n|---|\n| 你好世界漢字 |\n";
8776        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8777        let m = build_t(&ed.nodes().unwrap(), src, Some(14));
8778        for r in &m.rows {
8779            assert_eq!(r.width(), 14, "{:?} is not drawn to the grid", rendered(&m));
8780        }
8781    }
8782
8783    #[test]
8784    fn a_hard_break_falls_between_clusters_and_measures_in_cells() {
8785        let glyphs = |s: &str| {
8786            let mut out = Vec::new();
8787            push_text(&mut out, s, 0, Style::default());
8788            out
8789        };
8790        let piece = |p: &[Glyph]| p.iter().map(|g| g.ch).collect::<String>();
8791
8792        // Six cells of CJK broken at four: two characters, then one — never
8793        // between the two cells of `好`.
8794        let w = glyphs("你好世");
8795        let pieces: Vec<String> = hard_break(&w, 4).iter().map(|p| piece(p)).collect();
8796        assert_eq!(pieces, ["你好", "世"]);
8797
8798        // A character wider than the column has nowhere legal to break, so it
8799        // keeps its cells rather than being cut in half.
8800        let w = glyphs("你好");
8801        let pieces: Vec<String> = hard_break(&w, 1).iter().map(|p| piece(p)).collect();
8802        assert_eq!(pieces, ["你", "好"]);
8803
8804        // An empty word yields no pieces at all — a double space stays a space.
8805        assert!(hard_break(&[], 4).is_empty());
8806    }
8807
8808    #[test]
8809    fn an_empty_list_item_still_gets_a_bulleted_row_with_a_caret_home() {
8810        // Pressing Enter at the end of a list item opens a new, empty item —
8811        // a childless `list_item`. Without a row of its own the new bullet
8812        // wouldn't appear until something was typed into it (the caret would be
8813        // stranded on an offset no row draws). It now renders as one prefixed
8814        // row whose end is a caret stop, so the bullet shows and the caret lands
8815        // just past the marker.
8816        let m = map("- item\n- \n");
8817        assert_eq!(m.num_rows(), 2, "the empty second item needs its own row");
8818        assert_eq!(
8819            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8820            "• ",
8821            "the empty item draws just its bullet",
8822        );
8823        // Its end is the caret home (past the `- ` marker), and it's a real stop.
8824        assert!(
8825            m.is_stop(m.rows[1].end_src),
8826            "the empty item's caret home is not a stop"
8827        );
8828        assert_eq!(
8829            m.pos_of_offset(m.rows[1].end_src),
8830            (1, 2),
8831            "caret sits after '• '"
8832        );
8833    }
8834
8835    #[test]
8836    fn a_notes_row_range_stops_at_the_note_even_when_it_ends_in_a_link() {
8837        // The peek bug: a note whose body ends in a link has its last byte
8838        // inside the hidden destination, so mapping `end - 1` through
8839        // `pos_of_offset` snapped *forward* — past its own row, past the drawn
8840        // gap, and onto the next note's row. The popover then drew both notes.
8841        let src = "A[^1] B[^2].\n\n[^1]: bare text\n\n[^2]: [title](https://example.com/x)\n\n[^3]: last\n";
8842        let m = map(src);
8843        let body = src.find("[title]").unwrap();
8844        let end = src.find("\n\n[^3]").unwrap();
8845
8846        let (first, last) = m.row_range_for(body..end);
8847        assert_eq!(
8848            first, last,
8849            "a one-block note is one row, not a span onto the next"
8850        );
8851
8852        // The old arithmetic, kept here as the thing that must stay wrong: it
8853        // is what this method exists instead of.
8854        assert_ne!(
8855            m.pos_of_offset(end - 1).0,
8856            last,
8857            "the forward snap still leaves the note's row — that is the whole point",
8858        );
8859
8860        // A note ending in *visible* text was never broken, and still isn't:
8861        // both readings agree there, which is why the original test missed it.
8862        let plain = src.find("bare text").unwrap();
8863        let plain_end = src.find("\n\n[^2]").unwrap();
8864        let (pf, pl) = m.row_range_for(plain..plain_end);
8865        assert_eq!(pf, pl);
8866        assert_eq!(m.pos_of_offset(plain_end - 1).0, pl);
8867    }
8868
8869    #[test]
8870    fn a_row_range_covers_every_row_of_a_block_that_spans_several() {
8871        // The range is a span, not a point: a quote of two paragraphs covers its
8872        // gap row and both of its text rows, so a peek draws the whole thing.
8873        let src = "> one\n>\n> two\n\nafter\n";
8874        let m = map(src);
8875        let (first, last) = m.row_range_for(0..src.find("\n\nafter").unwrap());
8876        assert_eq!((first, last), (0, 2));
8877
8878        // And a range with no visible byte at all still covers the row it opened
8879        // on, rather than collapsing to nothing.
8880        let (f, l) = m.row_range_for(0..1);
8881        assert_eq!((f, l), (0, 0));
8882    }
8883
8884    #[test]
8885    fn an_empty_block_quote_still_gets_a_gutter_row_with_a_caret_home() {
8886        // The peer of the empty list item, and the case that made an empty line
8887        // in a quote draw as plain body text: a childless `block_quote` — a bare
8888        // `> `, which is what the toolbar's Quote button leaves on a blank line —
8889        // has no inner block to carry the gutter, so the whole quote used to
8890        // render as *nothing*. It didn't merely lose its bar; the row went away
8891        // and the caret had no home on it.
8892        let m = map("a\n\n> \n\nb\n");
8893        assert_eq!(
8894            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
8895            "│ ",
8896            "the empty quote draws just its gutter",
8897        );
8898        assert!(
8899            m.rows[2]
8900                .glyphs
8901                .iter()
8902                .all(|g| g.style.role == Role::QuoteGutter)
8903        );
8904        assert!(
8905            !m.rows[2].decoration,
8906            "it is a line text can go on, not a drawn gap"
8907        );
8908        assert!(
8909            m.is_stop(m.rows[2].end_src),
8910            "the empty quote's caret home is not a stop"
8911        );
8912        assert_eq!(
8913            m.pos_of_offset(m.rows[2].end_src),
8914            (2, 2),
8915            "caret sits after '│ '"
8916        );
8917
8918        // And a document that is *only* an empty quote still renders a row — it
8919        // used to render none at all, leaving the caret nowhere to stand.
8920        let m = map("> \n");
8921        assert_eq!(m.num_rows(), 1);
8922        assert_eq!(
8923            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
8924            "│ "
8925        );
8926    }
8927
8928    #[test]
8929    fn a_quotes_own_trailing_marker_lines_stay_inside_the_quote() {
8930        // Enter at the end of `> a` writes `> a\n>\n> \n`. Those last two lines
8931        // hold no block — a quote's `content_span` stops at its last child — so
8932        // the children walk never reaches them, and they used to fall through to
8933        // the document-level trailing pass, which knows no prefix: the gutter
8934        // stopped and the writer's new line drew as plain prose. Fixable only
8935        // since twig 3.2.0, where the quote's *span* covers its own marker lines
8936        // (`0..3` before, `0..8` now) and there is finally a node saying they
8937        // are the quote's.
8938        let m = map("> a\n>\n> \n");
8939        assert_eq!(m.num_rows(), 3, "one row per line the quote spells");
8940        for (i, row) in m.rows.iter().enumerate() {
8941            let text = row.glyphs.iter().map(|g| g.ch).collect::<String>();
8942            assert!(text.starts_with("│ "), "row {i} lost the gutter: {text:?}");
8943            assert!(
8944                !row.decoration,
8945                "row {i} is a line to type on, not a drawn gap"
8946            );
8947            assert!(m.is_stop(row.end_src), "row {i} has no caret home");
8948        }
8949        assert_eq!(
8950            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
8951            "│ a"
8952        );
8953        // Distinct offsets, so ↑/↓ between them moves the caret rather than
8954        // landing twice on the same byte.
8955        assert!(m.rows[0].end_src < m.rows[1].end_src);
8956        assert!(m.rows[1].end_src < m.rows[2].end_src);
8957
8958        // A blank line *after* the quote is not the quote's: it is spelled with
8959        // no marker, so it stays an ordinary boundary and the gutter ends.
8960        let m = map("> a\n\nb\n");
8961        assert_eq!(m.num_rows(), 3);
8962        assert_eq!(
8963            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
8964            "b"
8965        );
8966        assert!(
8967            !m.rows[1]
8968                .glyphs
8969                .iter()
8970                .any(|g| g.style.role == Role::QuoteGutter)
8971        );
8972
8973        // Nesting is the case this could get wrong, and the depth has to come
8974        // from which quote's span the line falls in rather than from the row
8975        // above it. A trailing `>` under `> > a` matches only the OUTER quote,
8976        // so it wears one gutter; spell it `> >` and it wears two.
8977        let m = map("> > a\n>\n");
8978        assert_eq!(
8979            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
8980            "│ │ a"
8981        );
8982        assert_eq!(
8983            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8984            "│ "
8985        );
8986        let m = map("> > a\n> >\n");
8987        assert_eq!(
8988            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8989            "│ │ "
8990        );
8991
8992        // And a marker line BETWEEN two quoted paragraphs is untouched: that is
8993        // the boundary `emit_separators_before` spells, and it stays a drawn gap
8994        // rather than becoming a line to type on.
8995        let m = map("> a\n>\n> b\n");
8996        assert_eq!(m.num_rows(), 3);
8997        assert!(
8998            m.rows[1].decoration,
8999            "the gap between two quoted blocks is still a gap"
9000        );
9001    }
9002
9003    #[test]
9004    fn an_empty_ordered_item_gets_its_number_and_a_caret_home() {
9005        let m = map("1. item\n2. \n");
9006        assert_eq!(m.num_rows(), 2);
9007        assert_eq!(
9008            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
9009            "2. "
9010        );
9011        assert!(m.is_stop(m.rows[1].end_src));
9012        assert_eq!(
9013            m.pos_of_offset(m.rows[1].end_src),
9014            (1, 3),
9015            "caret sits after '2. '"
9016        );
9017    }
9018
9019    #[test]
9020    fn an_empty_headings_caret_home_is_past_its_hidden_marker() {
9021        // The toolbar's H1 on a blank line writes `# ` and nothing else. The row
9022        // it renders is empty (the marker is hidden), so its end *is* its only
9023        // caret stop — and it has to be the offset past the `# `, where typing
9024        // continues the heading. Anchored at the block's start instead, the caret
9025        // drew in front of the hashes and the first character typed there landed
9026        // before them (`x# `), which isn't a heading at all.
9027        let m = map("# \n");
9028        assert_eq!(m.num_rows(), 1);
9029        assert!(m.rows[0].glyphs.is_empty(), "the `# ` marker is hidden");
9030        assert_eq!(m.rows[0].end_src, 2, "the caret home is past the marker");
9031        assert!(m.is_stop(2), "the empty heading's caret home is not a stop");
9032    }
9033
9034    #[test]
9035    fn a_headings_rows_carry_its_level_even_with_nothing_typed_in_it() {
9036        // The row-level fact a proportional frontend sizes a whole line by. An
9037        // empty heading has no glyph to read a `Role::Heading` off, so a renderer
9038        // scanning glyphs drew `# ` (and its caret) at body height until the
9039        // first character landed.
9040        let m = map("# \n");
9041        assert_eq!(
9042            m.rows[0].heading,
9043            Some(1),
9044            "the empty heading knows its level"
9045        );
9046
9047        // Every row of one that wraps, not just the first — and nothing else.
9048        let m = map_at(
9049            "## a heading long enough to wrap over two rows\n\nbody\n",
9050            Some(20),
9051        );
9052        let heads: Vec<Option<u8>> = m.rows.iter().map(|r| r.heading).collect();
9053        assert!(
9054            heads.iter().filter(|h| **h == Some(2)).count() >= 2,
9055            "got {heads:?}"
9056        );
9057        assert_eq!(
9058            m.rows.last().and_then(|r| r.heading),
9059            None,
9060            "the paragraph under it is not a heading",
9061        );
9062    }
9063
9064    #[test]
9065    fn an_empty_heading_leaves_the_rows_under_it_at_their_own_offsets() {
9066        // The row's end is also what the *next* row's separator is measured from,
9067        // so an empty heading that under-reported it shifted every offset below —
9068        // and the blank line under the heading then claimed the same offset as the
9069        // heading's own end. `pos_of_offset` resolves such a tie downstream (a
9070        // soft wrap belongs to the row below), so the caret at the end of the
9071        // heading was drawn two rows lower, on the blank line.
9072        // `text\n\n# \n\n`: the heading's content opens at 8, and the two rows
9073        // under it end at 9 and 10 — the blank line and the document's end.
9074        let m = map("text\n\n# \n\n");
9075        let end = m.rows.last().expect("a trailing blank row").end_src;
9076        assert_eq!(end, 10, "the trailing rows must end at their real offsets");
9077        // The heading's caret home is its own row's, not one shared with a row
9078        // below — the tie that drew the caret two rows down.
9079        assert_eq!(m.pos_of_offset(8), (2, 0), "the empty heading's own row");
9080        assert!(
9081            m.rows[3..].iter().all(|r| r.end_src > 8),
9082            "rows below own later offsets"
9083        );
9084    }
9085
9086    // ── block boundaries ─────────────────────────────────────────────────────
9087
9088    /// Every drawn boundary in `src`, in order, as `(above, below)`.
9089    fn boundaries(m: &VisualMap) -> Vec<(BlockClass, BlockClass)> {
9090        m.rows
9091            .iter()
9092            .filter_map(|r| r.boundary)
9093            .map(|b| (b.above, b.below))
9094            .collect()
9095    }
9096
9097    #[test]
9098    fn a_boundary_says_which_blocks_it_divides() {
9099        use BlockClass::*;
9100        let m = map("one\n\ntwo\n\n# Head\n\ntail\n\n> quoted\n\n```\ncode\n```\n\n");
9101        assert_eq!(
9102            boundaries(&m),
9103            vec![
9104                (Paragraph, Paragraph),
9105                (Paragraph, Heading),
9106                (Heading, Paragraph),
9107                (Paragraph, Quote),
9108                (Quote, Code),
9109                // The blank line the document trails off with is a boundary too
9110                // — it closes the last block above the empty paragraph the caret
9111                // rests on. See `emit_trailing_blank_lines`.
9112                (Code, Paragraph),
9113            ],
9114            "each gap names the pair it falls between, in document order"
9115        );
9116    }
9117
9118    #[test]
9119    fn a_closing_fence_at_the_end_of_the_document_opens_no_phantom_row() {
9120        // The code block's last row ends at its last line of code; the closing
9121        // fence under it has no row. Counted from the row, the fence's line read
9122        // as a trailing blank line and opened an empty paragraph whose offset
9123        // was inside the fence — typing on it wrote into the backticks.
9124        let m = map("para\n\n```\ncode\n```\n");
9125        let texts: Vec<String> = m
9126            .rows
9127            .iter()
9128            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9129            .collect();
9130        assert_eq!(texts, vec!["para", "", "code"], "a row under the fence");
9131        assert!(
9132            m.rows.last().is_some_and(|r| r.code),
9133            "the last row is the code"
9134        );
9135        // One more newline is the real empty paragraph, past the fence.
9136        let m = map("para\n\n```\ncode\n```\n\n");
9137        let last = m.rows.last().expect("a trailing row");
9138        assert_eq!(last.end_src, 20, "the trailing row stands past the fence");
9139        assert!(!last.decoration, "the trailing row is somewhere to type");
9140        // A setext underline is the same shape: markup under the last row.
9141        let m = map("Head\n====\n");
9142        assert_eq!(
9143            m.rows.len(),
9144            1,
9145            "a row under the underline: {:?}",
9146            m.rows.len()
9147        );
9148    }
9149
9150    // ── hidden blocks ────────────────────────────────────────────────────────
9151
9152    /// The row texts of `m`, one string per row.
9153    fn row_texts(m: &VisualMap) -> Vec<String> {
9154        m.rows
9155            .iter()
9156            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9157            .collect()
9158    }
9159
9160    #[test]
9161    fn a_div_s_closing_tag_is_not_a_blank_row() {
9162        // The `</div>` sits on a line of its own under the div's last child and
9163        // draws nothing. Counting the separator from the child's end read that
9164        // line as a blank line between the div and the block below — a
9165        // navigable empty row the author never opened — and at the end of the
9166        // file, as an empty trailing paragraph.
9167        let m = map("above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n");
9168        assert_eq!(row_texts(&m), ["above", "", "hello", "", "below"]);
9169        assert!(!m.is_stop(36), "the `</div>` line is not a caret home");
9170        assert_eq!(
9171            m.stop_after(34),
9172            Some(44),
9173            "from `hello` the next stop is `below`"
9174        );
9175
9176        let m = map("above\n\n<div class=\"center\">\n\nhello\n\n</div>\n");
9177        assert_eq!(row_texts(&m), ["above", "", "hello"], "no trailing rows");
9178    }
9179
9180    #[test]
9181    fn a_comment_between_two_blocks_is_stepped_over_not_drawn_as_a_gap() {
9182        // `<!-- exec -->` is a top-level block that draws no rows. The blocks
9183        // either side of it meet across the one boundary a paragraph and a code
9184        // block always meet across — not that boundary *plus* one blank row per
9185        // line of the comment, which is what counting the separator from the
9186        // paragraph's end used to spell.
9187        let m = map("para one\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n");
9188        assert_eq!(row_texts(&m), ["para one", "", "code", "", "after"]);
9189        assert_eq!(
9190            boundaries(&m),
9191            vec![
9192                (BlockClass::Paragraph, BlockClass::Code),
9193                (BlockClass::Code, BlockClass::Paragraph),
9194            ],
9195            "the boundary names the drawn blocks either side, not the comment"
9196        );
9197        // The gap stands past the comment, so the caret's row lookup never
9198        // resolves inside it.
9199        assert_eq!(
9200            m.rows[1].end_src, 23,
9201            "the gap row ends at the comment's end"
9202        );
9203    }
9204
9205    #[test]
9206    fn a_comment_opening_the_document_draws_no_leading_gap() {
9207        let m = map("<!-- lead -->\n\npara\n");
9208        assert_eq!(row_texts(&m), ["para"]);
9209        assert_eq!(m.content_start, 0, "the comment is still the first block");
9210    }
9211
9212    #[test]
9213    fn a_comment_closing_the_document_is_not_trailing_blank_lines() {
9214        // Its lines are not blank lines the author opened with Enter, so no
9215        // gap-plus-empty-paragraph is fabricated under the last drawn block.
9216        let m = map("para\n\n<!-- trail -->\n");
9217        assert_eq!(row_texts(&m), ["para"]);
9218        // Enter at the end of the document still opens the empty paragraph the
9219        // caret rests on: the newlines *after* the comment count as they would
9220        // after any block.
9221        let m = map("para\n\n<!-- trail -->\n\n");
9222        assert_eq!(row_texts(&m), ["para", "", ""]);
9223    }
9224
9225    #[test]
9226    fn a_comment_in_a_list_item_leaves_the_bullet_to_what_follows_it() {
9227        // The first *drawn* child wears the item's marker; a hidden first child
9228        // would otherwise take it and leave the text without one.
9229        let m = map("- <!-- note -->\n\n  text\n- two\n");
9230        let texts = row_texts(&m);
9231        assert!(
9232            texts.iter().any(|t| t == "• text"),
9233            "the text wears the bullet: {texts:?}"
9234        );
9235        assert!(
9236            !texts.iter().any(|t| t == "• "),
9237            "no empty bullet row for the comment: {texts:?}"
9238        );
9239    }
9240
9241    #[test]
9242    fn the_cached_build_does_not_spell_the_document_out_as_blank_rows_after_a_comment() {
9243        // The bug as seen: a 200-line document with one comment in it rendered
9244        // ~200 blank rows after the comment, one per source line, because the
9245        // comment's per-block builder handed back a `last_off` of 0. Parity with
9246        // `build` alone would not catch a *shared* wrong answer, so the count is
9247        // pinned outright.
9248        let body = (0..200)
9249            .map(|i| format!("line {i}"))
9250            .collect::<Vec<_>>()
9251            .join("\n\n");
9252        let src = format!("intro\n\n<!-- exec -->\n{body}\n");
9253        let mut ed = Editor::new_str(&src, Format::Markdown).unwrap();
9254        let mut cache = BlockCache::default();
9255        let (plain, cached) = render_both(&mut ed, &src, Some(80), &mut cache);
9256        assert_maps_eq(&plain, &cached, "comment then 200 paragraphs");
9257        // intro, then 200 × (gap, paragraph): 401 rows and not a row more.
9258        assert_eq!(cached.rows.len(), 401);
9259    }
9260
9261    #[test]
9262    fn a_link_reference_definition_is_stepped_over_like_a_comment() {
9263        // `[a]: /a` is a root beside `doc` with no rows of its own. Merged into
9264        // the walk it is a hidden block: the blocks either side meet across one
9265        // boundary, and its line is not a blank row.
9266        let m = map("see [a]\n\n[a]: /a\n\nafter\n");
9267        assert_eq!(row_texts(&m), ["see a", "", "after"]);
9268        assert_eq!(
9269            boundaries(&m),
9270            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
9271        );
9272    }
9273
9274    #[test]
9275    fn link_reference_definitions_closing_the_document_are_not_trailing_blank_lines() {
9276        // The README shape: prose, then a `[links]` block nobody reads. Its
9277        // lines used to be counted as blank ones, an empty paragraph per
9278        // definition under the last real block.
9279        let m = map("see [a] and [b]\n\n<!-- links -->\n[a]: /a\n[b]: /b \"bee\"\n");
9280        assert_eq!(row_texts(&m), ["see a and b"]);
9281    }
9282
9283    #[test]
9284    fn a_definition_glued_under_a_paragraph_stays_inside_it() {
9285        // `[a]: /a` at the front of a paragraph's lines is stripped from the
9286        // paragraph's text, but the paragraph's span still starts on its line.
9287        // Both blocks start at the same offset; the definition, sorted first,
9288        // is stepped over, and the paragraph draws as it always did — one gap
9289        // above it, none inside.
9290        let m = map("intro\n\n[a]: /a\ntext [a]\n");
9291        assert_eq!(row_texts(&m), ["intro", "", "text a"]);
9292    }
9293
9294    #[test]
9295    fn a_definition_with_no_span_is_left_out_of_the_walk() {
9296        // twig before 3.3.3 reported `0..0` for every link reference
9297        // definition. One of those has nowhere to be merged: sorted first by
9298        // its zero start it would open the document with a phantom block, and
9299        // the walk would step back to offset 0. It is simply not a block. A
9300        // footnote definition is always placed; it has a body to draw.
9301        assert!(!is_placed_definition(&Kind::Reference, &(0..0)));
9302        assert!(is_placed_definition(&Kind::Reference, &(7..14)));
9303        assert!(is_placed_definition(&Kind::Footnote, &(0..0)));
9304        assert!(!is_placed_definition(&Kind::Str, &(7..14)));
9305    }
9306
9307    #[test]
9308    fn the_trailing_gap_closes_the_last_block() {
9309        // Two Enters at the end of a document: a drawn gap, then the navigable
9310        // empty paragraph. Only the gap is labelled, so a frontend that shrinks
9311        // boundaries shrinks the spacer and leaves the row being typed on alone.
9312        let m = map("# Head\n\n\n");
9313        assert_eq!(
9314            boundaries(&m),
9315            vec![(BlockClass::Heading, BlockClass::Paragraph)]
9316        );
9317    }
9318
9319    #[test]
9320    fn only_the_drawn_gap_rows_carry_a_boundary() {
9321        let m = map("one\n\ntwo\n");
9322        for row in &m.rows {
9323            assert_eq!(
9324                row.boundary.is_some(),
9325                row.decoration,
9326                "a boundary is exactly a drawn gap row: {:?}",
9327                row.glyphs.iter().map(|g| g.ch).collect::<String>()
9328            );
9329        }
9330    }
9331
9332    #[test]
9333    fn preserve_flow_labels_no_boundary() {
9334        // Every blank line is a caret home there — somewhere text can go, not a
9335        // gap between blocks — so nothing is drawn-only and nothing is labelled.
9336        // A frontend keying its spacing off `boundary` can't shrink a row the
9337        // author is about to type on.
9338        let m = map_preserve("one\n\ntwo\n\n# Head\n", Some(80));
9339        assert!(boundaries(&m).is_empty());
9340    }
9341
9342    #[test]
9343    fn a_list_draws_no_boundary_between_its_items() {
9344        // Tight or loose, core puts no gap row between two items of one list —
9345        // so an item↔item boundary is a shape no frontend will ever be handed,
9346        // and spacing one is spacing something that isn't there.
9347        for src in ["- one\n- two\n", "- one\n\n- two\n"] {
9348            let m = map(src);
9349            assert!(
9350                boundaries(&m).is_empty(),
9351                "no gap row inside the list of {src:?}"
9352            );
9353        }
9354        // Leaving the list is an ordinary boundary, and the list is named as
9355        // what sits above it.
9356        let m = map("- one\n- two\n\npara\n");
9357        assert_eq!(
9358            boundaries(&m),
9359            vec![(BlockClass::List, BlockClass::Paragraph)]
9360        );
9361    }
9362
9363    #[test]
9364    fn a_nested_boundary_names_the_blocks_inside_the_container() {
9365        // Two paragraphs inside a blockquote are divided by a Paragraph↔Paragraph
9366        // boundary — the quote is the container they're both in, not what the gap
9367        // separates.
9368        let m = map("> one\n>\n> two\n");
9369        assert_eq!(
9370            boundaries(&m),
9371            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
9372        );
9373    }
9374
9375    #[test]
9376    fn a_directive_container_draws_one_boundary_like_every_other_block() {
9377        // A container's rows stop at its last *child*, so without anchoring
9378        // `last_off` past the closing `:::` the separator logic counted the fence
9379        // line as a blank row of its own and drew the gap twice — one authored
9380        // blank line, two boundaries, and a frontend spacing each of them put
9381        // double margin under every fenced div. The code-block arm anchors past
9382        // its ``` for exactly this reason; compare the two here.
9383        let fenced = map_directives(":::note\nin\n:::\n\ntwo\n");
9384        assert_eq!(
9385            boundaries(&fenced),
9386            vec![(BlockClass::Directive, BlockClass::Paragraph)],
9387            "one authored gap, one boundary row"
9388        );
9389        let code = map("```\nc\n```\n\ntwo\n");
9390        assert_eq!(
9391            boundaries(&code).len(),
9392            boundaries(&fenced).len(),
9393            "a fenced div spaces like a fenced code block"
9394        );
9395        // Nesting closes several fences at once; still one gap.
9396        let nested = map_directives(":::a\n:::b\nin\n:::\n:::\n\ntwo\n");
9397        assert_eq!(
9398            boundaries(&nested),
9399            vec![(BlockClass::Directive, BlockClass::Paragraph)]
9400        );
9401    }
9402
9403    #[test]
9404    fn a_block_media_names_itself_in_the_boundaries_either_side() {
9405        use BlockClass::*;
9406        // A block image is never a node of its own — `media_only` promotes the
9407        // *paragraph* wrapping it — so classifying the node the walk stands on
9408        // called the picture `Paragraph` and left `BlockClass::Media` unreachable:
9409        // a frontend could not give a photo more air than a line of prose.
9410        // `label_media_boundaries` reads it back off the finished rows instead.
9411        let m = map("one\n\n![alt](p.png)\n\ntwo\n");
9412        assert_eq!(boundaries(&m), vec![(Paragraph, Media), (Media, Paragraph)]);
9413        // At the edges of the document too: the leading gap has no boundary of
9414        // its own, and the trailing one is `emit_trailing_blank_lines`'.
9415        let edges = map("![a](p.png)\n\nmid\n\n![b](q.png)\n");
9416        assert_eq!(
9417            boundaries(&edges),
9418            vec![(Media, Paragraph), (Paragraph, Media)]
9419        );
9420        // One gap spelled with several rows — the row closing the block above and
9421        // the row opening the one below, with the author's spare blank line
9422        // navigable between them — carries the same pair on every drawn row.
9423        let roomy = map("one\n\n\n\n![alt](p.png)\n");
9424        assert_eq!(
9425            boundaries(&roomy),
9426            vec![(Paragraph, Media), (Paragraph, Media)]
9427        );
9428    }
9429
9430    #[test]
9431    fn a_block_video_is_media_at_its_boundaries_not_a_directive_panel() {
9432        // Worse than the image case before `label_media_boundaries`: a `<video>`
9433        // arrives as twig's generic `container`, which classifies `Directive` —
9434        // the one class a frontend reads as "draw a tinted panel here". A movie
9435        // got the chrome of a fenced div.
9436        let mut doc = crate::Doc::from_source(
9437            "one\n\n<video src=\"v.mp4\"></video>\n\ntwo\n".to_string(),
9438            Format::Markdown,
9439        )
9440        .unwrap();
9441        doc.build_visual(80);
9442        assert_eq!(
9443            boundaries(&doc.vmap),
9444            vec![
9445                (BlockClass::Paragraph, BlockClass::Media),
9446                (BlockClass::Media, BlockClass::Paragraph),
9447            ]
9448        );
9449    }
9450
9451    #[test]
9452    fn the_incremental_walk_labels_boundaries_like_the_full_one() {
9453        // `assert_maps_eq` compares boundaries too, so this pins the two doors
9454        // into `BlockClass::from_node_kind` — a `FlatNode`'s kind on the full
9455        // build, a query match's on the cached one — against a document with one
9456        // of every boundary in it.
9457        let src = "one\n\n# Head\n\ntwo\n\n- a\n- b\n\n> q\n\n```\nc\n```\n\npara\n";
9458        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
9459        let mut cache = BlockCache::default();
9460        let (full, cached) = render_both(&mut ed, src, Some(80), &mut cache);
9461        assert_maps_eq(&full, &cached, "boundary labelling");
9462        assert!(
9463            !boundaries(&full).is_empty(),
9464            "the fixture has boundaries to compare"
9465        );
9466    }
9467
9468    #[test]
9469    fn every_caret_stop_opens_a_cluster_of_its_row() {
9470        // The two ways of finding a cluster have to agree. `push_text` marks the
9471        // stops by segmenting one run of text; the column mapping segments the
9472        // whole row, decoration and all. A stop that came out as the *middle* of
9473        // some row-level cluster would be a caret with no column of its own —
9474        // drawn at the column of whatever swallowed it.
9475        let src = "# 標題\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` 你好\n\n\
9476                   - 項目 one\n- e\u{0301}dge\n\n> 引用 text\n\n\
9477                   | A | 值 |\n|---|---|\n| 你好 | 👩‍🚀 |\n";
9478        let m = map(src);
9479        for (r, row) in m.rows.iter().enumerate() {
9480            let openers: Vec<usize> = clusters(&row.glyphs).iter().map(|c| c.glyph).collect();
9481            for (i, g) in row.glyphs.iter().enumerate() {
9482                assert!(
9483                    !g.stop || openers.contains(&i),
9484                    "row {r}: the stop at glyph {i} ({:?}) is inside a cluster, \
9485                     so it is drawn at another glyph's column",
9486                    g.ch
9487                );
9488            }
9489        }
9490    }
9491
9492    // ── the presentation vocabulary ─────────────────────────────────────────
9493
9494    /// A block's own attributes, in the three formats that spell one on the
9495    /// block itself: HTML's tag, djot's `{…}` line, and — the odd one — a
9496    /// Markdown `<div>` around it, which is where twig has to put a Markdown
9497    /// block's attributes because the format has nowhere else.
9498    #[test]
9499    fn a_block_carries_its_alignment_on_every_row_it_draws() {
9500        // HTML, on the paragraph. `lead` is somebody else's class and is
9501        // neither read nor in the way.
9502        let html = map_leaf("<p class=\"lead center\">hi</p>\n", Format::Html);
9503        assert_eq!(line_facts(&html), vec![(Some(Align::Center), None)]);
9504
9505        // djot's attribute line, on the block.
9506        let dj = map_leaf("{.right}\nhi\n", Format::Djot);
9507        assert_eq!(line_facts(&dj), vec![(Some(Align::Right), None)]);
9508
9509        // A heading carries it too, and on every row a wrapped one draws.
9510        let h = map_leaf("{.center}\n# a heading\n", Format::Djot);
9511        assert_eq!(line_facts(&h), vec![(Some(Align::Center), None)]);
9512        assert_eq!(h.rows[0].heading, Some(1));
9513
9514        // Both keys at once, and the line spacing is read the same way.
9515        let both = map_leaf("{.justify data-line-height=\"1.5\"}\nhi\n", Format::Djot);
9516        assert_eq!(
9517            line_facts(&both),
9518            vec![(
9519                Some(Align::Justify),
9520                Some(LineHeight::Step(LineSpacing::OneHalf))
9521            )]
9522        );
9523
9524        // An unknown token is somebody else's and the block draws at the
9525        // theme's alignment; a ratio outside the menu's three is the author's
9526        // own and draws at exactly what they wrote.
9527        let other = map_leaf("{.lead data-line-height=\"1.3\"}\nhi\n", Format::Djot);
9528        assert_eq!(line_facts(&other), vec![(None, LineHeight::ratio(1.3))]);
9529
9530        // A value the grammar does not cover is neither: carried by the
9531        // document, drawn at the theme's spacing, and read as nothing at all.
9532        let em = map_leaf("{data-line-height=\"1.3em\"}\nhi\n", Format::Djot);
9533        assert_eq!(line_facts(&em), vec![(None, None)]);
9534    }
9535
9536    /// `<div class="center">` around three paragraphs centres all three, which
9537    /// is what the author of that HTML meant — and around one is the sole-child
9538    /// shape twig's `set_block_attrs` writes in Markdown.
9539    #[test]
9540    fn a_div_lends_its_alignment_to_every_block_inside_it() {
9541        let m = map_leaf(
9542            "<div class=\"center\" data-line-height=\"2\">\n\none\n\ntwo\n\n</div>\n",
9543            Format::Markdown,
9544        );
9545        assert_eq!(
9546            line_facts(&m),
9547            vec![
9548                (
9549                    Some(Align::Center),
9550                    Some(LineHeight::Step(LineSpacing::Double))
9551                ),
9552                (
9553                    Some(Align::Center),
9554                    Some(LineHeight::Step(LineSpacing::Double))
9555                ),
9556            ]
9557        );
9558
9559        // The nearer node wins, and the block after the div is untouched — the
9560        // context is restored, not left running.
9561        let nested = map_leaf(
9562            "<div class=\"center\">\n\n<div class=\"right\">\n\ninner\n\n</div>\n\nouter\n\n</div>\n\nafter\n",
9563            Format::Markdown,
9564        );
9565        assert_eq!(
9566            line_facts(&nested),
9567            vec![
9568                (Some(Align::Right), None),
9569                (Some(Align::Center), None),
9570                (None, None),
9571            ]
9572        );
9573    }
9574
9575    /// Size, face and colour are the run's, and the block's when the whole
9576    /// block is meant — read at both levels with the nearer winning.
9577    #[test]
9578    fn a_span_s_size_beats_its_block_s_and_its_face_falls_through() {
9579        // `<div data-font>` over `<p data-size>` over `<span data-size>`: the
9580        // span wins on size, the block is still what says the face.
9581        // The span is not first on its line: a `<span …>` opening one is an
9582        // HTML *block* to CommonMark, which is a fact about Markdown and not
9583        // about this.
9584        let m = map_leaf(
9585            "<div data-font=\"serif\">\n\nc <span data-size=\"small\">a</span> b\n\n</div>\n",
9586            Format::Markdown,
9587        );
9588        let a = style_of(&m, 'a');
9589        assert_eq!(a.size, Some(FontSize::Step(SizeStep::Small)));
9590        assert_eq!(a.font, Some(FaceRef::Generic(FontFamily::Serif)));
9591        // The text outside the span keeps the div's face and no size at all.
9592        let b = style_of(&m, 'b');
9593        assert_eq!(b.size, None);
9594        assert_eq!(b.font, Some(FaceRef::Generic(FontFamily::Serif)));
9595
9596        // djot spells the same span anonymously and it reads identically.
9597        let dj = map_leaf(
9598            "{data-size=\"large\"}\nx [y]{data-size=\"xx-large\" data-color=\"blue\"} z\n",
9599            Format::Djot,
9600        );
9601        assert_eq!(
9602            style_of(&dj, 'x').size,
9603            Some(FontSize::Step(SizeStep::Large))
9604        );
9605        assert_eq!(
9606            style_of(&dj, 'y').size,
9607            Some(FontSize::Step(SizeStep::XxLarge))
9608        );
9609        assert_eq!(
9610            style_of(&dj, 'y').color,
9611            Some(TextColor::Named(MarkColor::Blue))
9612        );
9613        // The block's size is still the block's outside the span.
9614        assert_eq!(
9615            style_of(&dj, 'z').size,
9616            Some(FontSize::Step(SizeStep::Large))
9617        );
9618        assert_eq!(style_of(&dj, 'z').color, None);
9619    }
9620
9621    /// The exact half of the vocabulary reaches a glyph and a row by the same
9622    /// doors the names do — the fold has one rule, not one per form. A named
9623    /// family is the one that cannot ride the glyph as itself: the walker
9624    /// interns it and the glyph carries the id.
9625    #[test]
9626    fn an_exact_size_face_and_colour_reach_the_glyph_and_the_row() {
9627        let m = map_leaf(
9628            "<div data-line-height=\"1.3\">\n\nc <span data-size=\"14pt\" \
9629             data-color=\"#c03030\" data-font=\"Garamond\">a</span> b\n\n</div>\n",
9630            Format::Markdown,
9631        );
9632        let a = style_of(&m, 'a');
9633        assert_eq!(a.size, FontSize::points(14.0));
9634        assert_eq!(
9635            a.color,
9636            Some(TextColor::Rgb {
9637                r: 0xc0,
9638                g: 0x30,
9639                b: 0x30
9640            })
9641        );
9642        assert_eq!(a.font, Some(FaceRef::Named(FaceId::of("Garamond"))));
9643        assert_eq!(m.face_name(FaceId::of("Garamond")), Some("Garamond"));
9644        // The div's ratio is the row's, on every row the block draws.
9645        assert_eq!(line_facts(&m), vec![(None, LineHeight::ratio(1.3))]);
9646        // And the text outside the span has none of the span's three.
9647        let b = style_of(&m, 'b');
9648        assert_eq!((b.size, b.font, b.color), (None, None, None));
9649
9650        // One name, one entry, however many spans wear it — the table is what
9651        // keeps a `Style` `Copy` and it should not grow per run.
9652        let twice = map_leaf(
9653            "x <span data-font=\"Garamond\">a</span> y <span data-font=\"Garamond\">b</span>\n",
9654            Format::Markdown,
9655        );
9656        assert_eq!(twice.faces().len(), 1);
9657        assert_eq!(
9658            style_of(&twice, 'a').font,
9659            style_of(&twice, 'b').font,
9660            "one family, one id"
9661        );
9662
9663        // A generic needs no entry at all: it names itself.
9664        let generic = map_leaf(
9665            "<div data-font=\"serif\">\n\nhi\n\n</div>\n",
9666            Format::Markdown,
9667        );
9668        assert_eq!(
9669            style_of(&generic, 'h').font,
9670            Some(FaceRef::Generic(FontFamily::Serif))
9671        );
9672        assert!(generic.faces().is_empty());
9673    }
9674
9675    /// The one key two nodes share. `data-color` on a `mark` is the highlight's
9676    /// *background* and reaches a glyph through [`Role::Mark`]; the same key on
9677    /// an attributed span is the text's foreground. Same vocabulary, same enum,
9678    /// no collision — and a mark inside a coloured span wears both.
9679    #[test]
9680    fn a_mark_keeps_its_highlight_colour_and_a_span_colours_the_text() {
9681        let m = map_leaf("a ==\u{1f534} red== b\n", Format::Markdown);
9682        let r = style_of(&m, 'r');
9683        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)));
9684        assert_eq!(r.color, None, "a highlight is not a text colour");
9685
9686        let both = map_leaf(
9687            "<span data-color=\"blue\">a ==\u{1f534} red== b</span>\n",
9688            Format::Markdown,
9689        );
9690        let r = style_of(&both, 'r');
9691        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)), "the highlight");
9692        assert_eq!(
9693            r.color,
9694            Some(TextColor::Named(MarkColor::Blue)),
9695            "the letters"
9696        );
9697    }
9698
9699    /// A page break is the `::page-break` leaf directive, and djot spells the
9700    /// same document as an empty `::: page-break` fence whose name comes back
9701    /// as a class. Both draw the placeholder row every leaf directive gets and
9702    /// both carry the same [`DirectiveMark`], because a frontend that opens a
9703    /// page at one must not be able to tell which format the file is in.
9704    #[test]
9705    fn a_page_break_reads_the_same_in_markdown_and_in_djot() {
9706        for (fmt, src) in [
9707            (Format::Markdown, "a\n\n::page-break\n\nb\n"),
9708            (Format::Djot, "a\n\n::: page-break\n:::\n\nb\n"),
9709        ] {
9710            let m = map_leaf(src, fmt);
9711            let marks: Vec<&DirectiveMark> = m
9712                .rows
9713                .iter()
9714                .filter_map(|r| r.leaf_directive.as_ref())
9715                .collect();
9716            assert_eq!(marks.len(), 1, "{fmt:?} draws one placeholder");
9717            assert_eq!(marks[0].name, "page-break", "{fmt:?}");
9718            assert!(marks[0].attrs.is_empty(), "{fmt:?}: {:?}", marks[0].attrs);
9719            assert!(
9720                m.rows
9721                    .iter()
9722                    .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>()
9723                        == "\u{29c9} page-break"),
9724                "{fmt:?} draws the label, got {:?}",
9725                m.rows
9726                    .iter()
9727                    .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
9728                    .collect::<Vec<_>>()
9729            );
9730        }
9731
9732        // A Markdown `:::note` with nothing in it is *not* this: its name is
9733        // its own, and nothing about it says "a block with no body" the way
9734        // djot's spelling of a leaf directive does.
9735        let empty_fence = map_leaf("::: note\n:::\n", Format::Markdown);
9736        assert!(
9737            empty_fence.rows.iter().all(|r| r.leaf_directive.is_none()),
9738            "a named empty fence keeps the reading it has"
9739        );
9740    }
9741
9742    /// A djot fence carrying more than its name keeps the rest as an attribute
9743    /// rather than folding it into the name: the *first* class token is the
9744    /// name, because that is where `insert_directive` puts it.
9745    #[test]
9746    fn a_djot_fence_s_first_class_is_the_directive_s_name_and_the_rest_is_attributes() {
9747        let m = map_leaf("{.page-break .wide}\n:::\n:::\n", Format::Djot);
9748        let mark = m
9749            .rows
9750            .iter()
9751            .find_map(|r| r.leaf_directive.as_ref())
9752            .expect("a placeholder");
9753        assert_eq!(mark.name, "page-break");
9754        assert_eq!(
9755            mark.attrs,
9756            vec![("class".to_string(), Some("wide".to_string()))]
9757        );
9758    }
9759
9760    // ── math ─────────────────────────────────────────────────────────────────
9761
9762    /// [`map_leaf`] on a chosen surface and reveal — the whole of what a math
9763    /// rendering turns on.
9764    fn map_math(src: &str, format: Format, surface: &Surface, reveal: Option<Reveal>) -> VisualMap {
9765        let mut ed =
9766            Editor::new_ext(src.as_bytes(), format, crate::doc::parse_extensions()).unwrap();
9767        build(&ed.nodes().unwrap(), src, Some(80), false, surface, reveal)
9768    }
9769
9770    fn pictures() -> Surface {
9771        Surface {
9772            inline_pictures: true,
9773            ..Default::default()
9774        }
9775    }
9776
9777    #[test]
9778    fn markdown_reads_math_and_a_dollar_before_whitespace_stays_prose() {
9779        // The `math` extension is on for every leaf document; twig's own rule
9780        // keeps a price out of it.
9781        let m = map_leaf("Say $E = mc^2$ for $5 and $6.\n", Format::Markdown);
9782        assert_eq!(row_texts(&m), vec!["Say E = mc^2 for $5 and $6."]);
9783        let e = m.rows[0].glyphs.iter().find(|g| g.ch == 'E').unwrap();
9784        assert_eq!(
9785            e.style.role,
9786            Role::Code,
9787            "the formula's TeX, in the code style"
9788        );
9789        assert_eq!(e.src, 5, "at its own byte, past the `$`");
9790        let five = m.rows[0].glyphs.iter().find(|g| g.ch == '5').unwrap();
9791        assert_eq!(five.style.role, Role::Body);
9792        assert!(m.math.is_empty(), "no picture stands in on a plain surface");
9793    }
9794
9795    #[test]
9796    fn a_plain_surface_draws_inline_math_as_code_with_the_delimiters_hidden() {
9797        // The verbatim treatment, in both languages — what `inline_math` always
9798        // rendered as — with the caret's home at the content's end.
9799        for (src, fmt) in [
9800            ("a $x+y$ b\n", Format::Markdown),
9801            ("a $`x+y` b\n", Format::Djot),
9802        ] {
9803            let m = map_leaf(src, fmt);
9804            assert_eq!(row_texts(&m), vec!["a x+y b"], "{src:?}");
9805            let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
9806            assert_eq!(x.style.role, Role::Code);
9807            assert!(!m.mark_ends.is_empty(), "the content end is a caret home");
9808        }
9809    }
9810
9811    #[test]
9812    fn display_math_in_a_line_of_prose_puts_its_text_at_the_text_s_own_offset() {
9813        // `display_math` had no arm and fell to the default one, which pushed
9814        // the text at the *node's* start: three bytes short in djot, past `$$`
9815        // and the backtick.
9816        let m = map_leaf("Before $$`x`$$ after\n", Format::Djot);
9817        let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
9818        assert_eq!(x.src, "Before $$`".len());
9819        assert_eq!(x.style.role, Role::Code);
9820        let m = map_leaf("Before $$x$$ after\n", Format::Markdown);
9821        let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
9822        assert_eq!(x.src, "Before $$".len());
9823    }
9824
9825    #[test]
9826    fn a_surface_that_paints_in_a_line_gets_one_atom_per_inline_formula() {
9827        let src = "Say $E = mc^2$ and $a$.\n";
9828        let m = map_math(src, Format::Markdown, &pictures(), None);
9829        assert_eq!(row_texts(&m), vec!["Say ∑ and ∑."]);
9830        assert_eq!(m.math.len(), 2);
9831        let first = &m.math[0];
9832        assert_eq!(first.tex, "E = mc^2");
9833        assert!(!first.display);
9834        assert_eq!(first.row, 0);
9835        assert_eq!(first.rows_span, 0..1);
9836        assert_eq!(first.glyph, Some(4));
9837        assert_eq!(first.src, 4, "the formula's start, where a click lands");
9838        let atom = &m.rows[0].glyphs[4];
9839        assert_eq!(atom.ch, MATH_ATOM);
9840        assert_eq!(atom.style.role, Role::Math);
9841        assert!(atom.stop);
9842        assert_eq!(atom.src, 4);
9843        // The caret has a stop on the atom and the next glyph's past it, and
9844        // nothing inside the markup.
9845        assert_eq!(m.stop_after(4), Some("Say $E = mc^2$".len()));
9846        assert!(m.mark_ends.is_empty(), "no home inside the hidden markup");
9847        // The row carries the marks the side-table is derived from.
9848        assert_eq!(m.rows[0].math.len(), 2);
9849        assert_eq!(m.rows[0].math[1].glyph, Some(m.math[1].glyph.unwrap()));
9850        assert_eq!(m.math[1].tex, "a");
9851    }
9852
9853    #[test]
9854    fn a_display_formula_written_inline_is_an_atom_in_display_style() {
9855        let m = map_math("Before $$x$$ after\n", Format::Markdown, &pictures(), None);
9856        assert_eq!(row_texts(&m), vec!["Before ∑ after"]);
9857        assert_eq!(m.math.len(), 1);
9858        assert!(m.math[0].display);
9859        assert_eq!(m.math[0].tex, "x");
9860    }
9861
9862    #[test]
9863    fn an_atom_follows_its_glyph_across_a_wrap() {
9864        // Fifteen words, then a formula that wraps onto the second row: the
9865        // mark is drained onto the row the glyph landed on, at its index there.
9866        let src = format!("{}$x$ end\n", "word ".repeat(15));
9867        let mut ed = Editor::new_ext(
9868            src.as_bytes(),
9869            Format::Markdown,
9870            crate::doc::parse_extensions(),
9871        )
9872        .unwrap();
9873        let m = build(
9874            &ed.nodes().unwrap(),
9875            &src,
9876            Some(40),
9877            false,
9878            &pictures(),
9879            None,
9880        );
9881        assert!(m.rows.len() >= 2);
9882        assert_eq!(m.math.len(), 1);
9883        let info = &m.math[0];
9884        let g = &m.rows[info.row].glyphs[info.glyph.unwrap()];
9885        assert_eq!(g.ch, MATH_ATOM);
9886        assert_eq!(g.src, src.find("$x$").unwrap());
9887        assert!(m.rows[..info.row].iter().all(|r| r.math.is_empty()));
9888    }
9889
9890    #[test]
9891    fn an_atom_in_a_table_cell_rides_the_cell_s_row() {
9892        let m = map_math(
9893            "| a | b |\n|---|---|\n| $x$ | c |\n",
9894            Format::Markdown,
9895            &pictures(),
9896            None,
9897        );
9898        assert_eq!(m.math.len(), 1);
9899        let info = &m.math[0];
9900        assert_eq!(m.rows[info.row].glyphs[info.glyph.unwrap()].ch, MATH_ATOM);
9901    }
9902
9903    #[test]
9904    fn a_display_formula_on_its_own_lines_is_a_block_placeholder_on_every_surface() {
9905        for (src, fmt) in [
9906            (
9907                "intro\n\n$$\n\\int_0^1 x\\,dx\n$$\n\nend\n",
9908                Format::Markdown,
9909            ),
9910            ("intro\n\n$$`\\int_0^1 x\\,dx`\n\nend\n", Format::Djot),
9911        ] {
9912            for surface in [Surface::default(), pictures()] {
9913                let m = map_math(src, fmt, &surface, None);
9914                assert_eq!(
9915                    row_texts(&m),
9916                    vec!["intro", "", "∑ \\int_0^1 x\\,dx", "", "end"],
9917                    "{src:?}"
9918                );
9919                assert_eq!(m.math.len(), 1);
9920                let info = &m.math[0];
9921                assert!(info.display);
9922                assert_eq!(info.glyph, None, "a block, not an atom");
9923                assert_eq!(info.rows_span, 2..3);
9924                assert_eq!(info.tex.trim(), "\\int_0^1 x\\,dx");
9925                let start = src.find("$$").unwrap();
9926                let end = start + src[start..].find("\n\nend").unwrap();
9927                assert_eq!(info.src, start);
9928                // Every label glyph at the formula's start, a stop there and
9929                // one past the block, nothing inside — a picture's two homes.
9930                let row = &m.rows[2];
9931                assert!(
9932                    row.glyphs
9933                        .iter()
9934                        .all(|g| g.src == start && g.style.role == Role::Math)
9935                );
9936                assert_eq!(row.end_src, end);
9937                assert_eq!(m.stop_after(start), Some(end));
9938                assert_eq!(m.stop_before(end), Some(start));
9939                // The gaps either side are labelled as a formula's.
9940                assert_eq!(m.rows[1].boundary.map(|b| b.below), Some(BlockClass::Math));
9941                assert_eq!(m.rows[3].boundary.map(|b| b.above), Some(BlockClass::Math));
9942            }
9943        }
9944    }
9945
9946    #[test]
9947    fn a_display_block_reserves_the_rows_the_frontend_measured() {
9948        let src = "$$\nx\n$$\n\nend\n";
9949        let surface = Surface {
9950            math_rows: HashMap::from([("\nx\n".to_string(), 4)]),
9951            ..Default::default()
9952        };
9953        let m = map_math(src, Format::Markdown, &surface, None);
9954        assert_eq!(m.math[0].rows_span, 0..4);
9955        assert_eq!(row_texts(&m)[..5], ["∑ x", "", "", "", ""]);
9956        // The fillers are decoration: drawn, no caret, anchored past the block.
9957        for r in &m.rows[1..4] {
9958            assert!(r.decoration);
9959            assert_eq!(r.end_src, 7);
9960        }
9961        assert_eq!(m.stop_after(0), Some(7));
9962        // A height keyed by TeX that does not match reserves nothing.
9963        let surface = Surface {
9964            math_rows: HashMap::from([("x".to_string(), 4)]),
9965            ..Default::default()
9966        };
9967        let m = map_math(src, Format::Markdown, &surface, None);
9968        assert_eq!(m.math[0].rows_span, 0..1);
9969    }
9970
9971    #[test]
9972    fn a_paragraph_with_prose_beside_a_display_formula_is_not_a_block() {
9973        let m = map_math("see\n$$\nx\n$$\n", Format::Markdown, &pictures(), None);
9974        assert!(
9975            m.math.iter().all(|i| i.glyph.is_some()),
9976            "an atom, not a placeholder"
9977        );
9978        let m = map_math(
9979            "$$\nx\n$$\n$$\ny\n$$\n",
9980            Format::Markdown,
9981            &pictures(),
9982            None,
9983        );
9984        assert_eq!(m.math.len(), 2);
9985        assert!(
9986            m.math.iter().all(|i| i.glyph.is_some()),
9987            "two formulas is prose with math in it"
9988        );
9989    }
9990
9991    #[test]
9992    fn a_formula_on_the_reveal_line_is_its_tex_in_every_mode() {
9993        let src = "Say $E = mc^2$ here.\n";
9994        // The hidden modes' reveal: only the formula shows its markup.
9995        let m = map_math(
9996            src,
9997            Format::Markdown,
9998            &pictures(),
9999            Some(Reveal::math(0..src.len() - 1)),
10000        );
10001        assert_eq!(row_texts(&m), vec!["Say $E = mc^2$ here."]);
10002        assert!(
10003            m.math.is_empty(),
10004            "nothing stands in for a revealed formula"
10005        );
10006        let dollar = m.rows[0].glyphs.iter().find(|g| g.ch == '$').unwrap();
10007        assert_eq!(dollar.style.role, Role::Delimiter);
10008        let e = m.rows[0].glyphs.iter().find(|g| g.ch == 'E').unwrap();
10009        assert_eq!(e.style.role, Role::Code);
10010        // Full's reveal draws the same, and an emphasis beside it reveals too
10011        // where the hidden modes' does not.
10012        let src = "*a* $x$\n";
10013        let hidden = map_math(
10014            src,
10015            Format::Markdown,
10016            &pictures(),
10017            Some(Reveal::math(0..src.len() - 1)),
10018        );
10019        assert_eq!(row_texts(&hidden), vec!["a $x$"]);
10020        let full = map_math(
10021            src,
10022            Format::Markdown,
10023            &pictures(),
10024            Some(Reveal::full(0..src.len() - 1)),
10025        );
10026        assert_eq!(row_texts(&full), vec!["*a* $x$"]);
10027        // A reveal line that does not meet the formula leaves the atom.
10028        let other = map_math(
10029            "$x$\n\ntext\n",
10030            Format::Markdown,
10031            &pictures(),
10032            Some(Reveal::math(5..9)),
10033        );
10034        assert_eq!(row_texts(&other)[0], "∑");
10035    }
10036
10037    #[test]
10038    fn a_display_block_on_the_reveal_line_is_its_source_lines_in_the_code_style() {
10039        let src = "intro\n\n$$\n\\int_0^1 x\n$$\n\nend\n";
10040        // Any line of the block reveals the whole of it: here the middle one.
10041        let mid = src.find("\\int").unwrap();
10042        let line = mid..mid + "\\int_0^1 x".len();
10043        let m = map_math(src, Format::Markdown, &pictures(), Some(Reveal::math(line)));
10044        assert_eq!(
10045            row_texts(&m),
10046            vec!["intro", "", "$$", "\\int_0^1 x", "$$", "", "end"]
10047        );
10048        assert!(m.math.is_empty());
10049        let fence = m.rows[2].glyphs.iter().find(|g| g.ch == '$').unwrap();
10050        assert_eq!(fence.style.role, Role::Delimiter);
10051        assert_eq!(fence.src, 7);
10052        let x = m.rows[3].glyphs.iter().find(|g| g.ch == 'x').unwrap();
10053        assert_eq!(x.style.role, Role::Code);
10054        assert_eq!(x.src, src.find("x\n$$").unwrap());
10055        // Every byte of the source is reachable: a stop on each fence and each
10056        // character between.
10057        assert!(m.is_stop(7));
10058        assert!(m.is_stop(mid));
10059        // The closing fence's line too, and the same for djot.
10060        let close = src.rfind("$$").unwrap();
10061        let m = map_math(
10062            src,
10063            Format::Markdown,
10064            &pictures(),
10065            Some(Reveal::math(close..close + 2)),
10066        );
10067        assert_eq!(row_texts(&m)[2], "$$");
10068        let src = "$$`\n\\int\n`\n";
10069        let m = map_math(src, Format::Djot, &pictures(), Some(Reveal::math(4..8)));
10070        assert_eq!(row_texts(&m), vec!["$$`", "\\int", "`"]);
10071    }
10072
10073    #[test]
10074    fn a_block_that_holds_a_formula_says_so_to_the_cache() {
10075        let src = "plain\n\nwith $x$ in it\n\n$$\ny\n$$\n";
10076        let mut ed = Editor::new_ext(
10077            src.as_bytes(),
10078            Format::Markdown,
10079            crate::doc::parse_extensions(),
10080        )
10081        .unwrap();
10082        let mut cache = BlockCache::default();
10083        let top = top_blocks(&mut ed);
10084        let _ = build_cached(
10085            &top,
10086            src,
10087            None,
10088            false,
10089            &pictures(),
10090            None,
10091            &mut cache,
10092            |id| ed.subtree(NodeId(id)).unwrap_or_default(),
10093        );
10094        assert!(!cache.math_meets(&(0..5)), "the plain paragraph");
10095        assert!(cache.math_meets(&(7..21)), "the one with an atom");
10096        assert!(
10097            cache.math_meets(&(26..27)),
10098            "the middle line of the display block"
10099        );
10100        // A hit carries the answer without a walk: build again from the cache.
10101        let _ = build_cached(
10102            &top,
10103            src,
10104            None,
10105            false,
10106            &pictures(),
10107            None,
10108            &mut cache,
10109            |_| Vec::new(),
10110        );
10111        assert!(cache.math_meets(&(7..21)));
10112        assert!(!cache.math_meets(&(0..5)));
10113    }
10114
10115    #[test]
10116    fn incremental_builds_agree_with_the_reference_on_math() {
10117        for src in [
10118            "a $x$ b\n\n$$\ny\n$$\n\nc\n",
10119            "one\n\ntwo $\\frac{a}{b}$ three\n",
10120            "$$\n\\int\n$$\n",
10121        ] {
10122            for surface in [Surface::default(), pictures()] {
10123                let mut ed = Editor::new_ext(
10124                    src.as_bytes(),
10125                    Format::Markdown,
10126                    crate::doc::parse_extensions(),
10127                )
10128                .unwrap();
10129                let all = ed.nodes().unwrap();
10130                let plain = build(&all, src, Some(80), false, &surface, None);
10131                let mut cache = BlockCache::default();
10132                let top = top_blocks(&mut ed);
10133                let cached = build_cached(
10134                    &top,
10135                    src,
10136                    Some(80),
10137                    false,
10138                    &surface,
10139                    None,
10140                    &mut cache,
10141                    |id| ed.subtree(NodeId(id)).unwrap_or_default(),
10142                );
10143                assert_eq!(row_texts(&plain), row_texts(&cached), "{src:?}");
10144                assert_eq!(plain.math, cached.math, "{src:?}");
10145                assert_eq!(plain.stops, cached.stops, "{src:?}");
10146            }
10147        }
10148    }
10149}