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;
26
27use twig::{Alignment, ContainerOrigin, DirectiveForm, Editor, FlatNode, Kind, QueryMatch};
28use unicode_segmentation::UnicodeSegmentation;
29use unicode_width::UnicodeWidthStr;
30
31use crate::style::{
32    Align, Baseline, FontFamily, LineSpacing, MarkColor, Role, SizeStep, Style, Token,
33};
34
35/// One rendered character plus the source byte offset it originates from.
36/// Synthetic glyphs (a list bullet, a quote gutter) point at their block's
37/// start, so clicking one lands the caret at the start of that block.
38#[derive(Clone)]
39pub struct Glyph {
40    pub ch: char,
41    pub style: Style,
42    pub src: usize,
43    /// Whether the caret may *rest* on this glyph. Decoration — a table border
44    /// or a cell's alignment padding — is visible but isn't text, so the caret
45    /// steps over it instead of into it. It also can't be a stop even in
46    /// principle: a run of decoration shares one `src`, and a caret can only
47    /// move by changing offset, so resting on it would pin horizontal motion.
48    /// A click still maps through `src`, which is why decoration points at the
49    /// text it decorates.
50    ///
51    /// Real text is a stop once per *grapheme cluster*, on the glyph that opens
52    /// it: the continuation glyphs of an emoji or an accented letter are drawn,
53    /// but standing between them is standing inside a character.
54    pub stop: bool,
55}
56
57/// One visual line. `end_src` is the source offset a caret sits at when placed
58/// at the line's end (past its last glyph) — the anchor for end-of-line and
59/// click-past-content.
60///
61/// `Clone` so a block's rows can be cached and re-emitted at a shifted offset
62/// across an edit — see [`BlockCache`].
63#[derive(Clone)]
64pub struct VRow {
65    pub glyphs: Vec<Glyph>,
66    pub end_src: usize,
67    /// A row that is drawn but holds no caret: a table's `├───┼───┤` rules, and
68    /// the blank gap a block boundary is spelled with. Vertical motion steps
69    /// over it, `pos_of_offset` never resolves onto it, and its stops (it has
70    /// none) and `end_src` stay out of the map's stop table.
71    ///
72    /// Emptiness isn't the test — an empty paragraph is a blank row too, and a
73    /// real caret stop. The test is whether the row is somewhere text can go.
74    pub decoration: bool,
75    /// This row is one line of a fenced or indented code block. Set on every row
76    /// the `"code_block"` arm emits — including its blank lines, which carry no
77    /// glyph to tell them apart otherwise. A frontend draws its own chrome (a
78    /// border and a tinted background) around each maximal run of these, and
79    /// scrolls them horizontally instead of wrapping; see
80    /// [`VisualMap::code_blocks`]. Survives the row shuffling of [`BlockCache`]
81    /// reuse and [`build_spliced`] because it rides on the row, not on a
82    /// row-index span the way a table's picture does.
83    pub code: bool,
84    /// A fenced code block's info string (its language), carried on the *first*
85    /// row of the block so it survives row reuse the way [`code`](Self::code)
86    /// does. `None` on every other row, and on an indented block (which has no
87    /// fence to label). A frontend paints it as a small label on the block's box
88    /// and edits it through a prompt — see [`CodeBlockInfo::lang`]. It's a plain
89    /// display string, not a source slice, so it needs no offset shifting; the
90    /// label re-derives from twig on the next build.
91    pub code_lang: Option<String>,
92    /// This row belongs to a `:::name{.class}` directive container — twig's
93    /// generic fenced-div block, whose meaning is entirely up to the host app
94    /// (diaryx's `:::vis{.audience}` visibility blocks, say). Set on every row
95    /// the `"directive"` arm emits, the same way [`code`](Self::code) marks a
96    /// code block's rows, so a frontend can draw a tinted panel around each
97    /// maximal run of these.
98    pub directive: bool,
99    /// A directive container's space-joined attrs — dot-prefixed classes
100    /// (`.public .family` → `"public family"`) unioned with bare pandoc-style
101    /// words (`public family`, no leading dot — diaryx's other `:::vis{...}`
102    /// convention), carried on the block's *first* row only — the
103    /// [`code_lang`](Self::code_lang) pattern. `None` on every other row, and
104    /// when the directive carries no such attrs. A frontend paints it as a
105    /// small label on the block's panel; it's a plain display string, not a
106    /// source slice, so it rides row reuse untouched.
107    pub directive_label: Option<String>,
108    /// Set on the single placeholder row a block-level image renders to, carrying
109    /// the image's destination and alt text; `None` on every other row. The row's
110    /// glyphs are the default `🖼 alt` label (which a plain surface paints as-is);
111    /// an image-capable frontend reads this to paint the real picture instead,
112    /// skipping the row named by [`MediaInfo::rows_span`]. Like
113    /// [`code_lang`](Self::code_lang) it's plain display strings, not source
114    /// slices, so it rides row reuse and needs no offset shifting; the map's
115    /// [`media`](VisualMap::media) side-table is derived from it once the rows
116    /// are final, the same way [`code_blocks`](VisualMap::code_blocks) is.
117    pub media: Option<MediaMark>,
118    /// Set on the **first** row of a task list item, carrying whether its box is
119    /// ticked; `None` on every other row, including a plain `list_item`'s. The
120    /// row's glyphs already draw the box as `☐ `/`☑ ` in the marker's place, so a
121    /// plain surface needs nothing further; a GUI reads this to paint a real
122    /// checkbox widget and to know which way it is facing.
123    ///
124    /// A `bool` rather than a source span, for the reason
125    /// [`code_lang`](Self::code_lang) is a plain string: it rides [`BlockCache`]
126    /// reuse and [`build_spliced`] untouched, needing no offset shifting. To
127    /// *toggle* the box, a frontend maps its click to a source offset the way it
128    /// maps any other — the marker's glyphs carry the item's own `src` — and
129    /// hands that to [`crate::Doc::toggle_task_at`].
130    pub task: Option<bool>,
131    /// Set on the single placeholder row a **leaf** directive (`::name{…}`)
132    /// renders to, carrying its name and attributes; `None` on every other row.
133    /// The container form isn't this — it wraps real blocks and marks each of
134    /// them [`directive`](Self::directive) instead. Like [`media`](Self::media)
135    /// it's plain display strings, so it rides row reuse untouched, and the map's
136    /// [`directives`](VisualMap::directives) side-table is derived from it once
137    /// the rows are final.
138    pub leaf_directive: Option<DirectiveMark>,
139    /// The heading level (1–6) of the block this row belongs to, on every row a
140    /// `heading` emits (a long one wraps to several) and `None` everywhere else.
141    ///
142    /// A frontend that sizes a whole line — a proportional renderer giving the
143    /// row a bigger line box — needs the level *per row*, and the glyphs can't
144    /// always supply it: an empty heading (`# ` with nothing typed after it,
145    /// which is what the toolbar's H1 leaves on a blank line) has no glyph to
146    /// carry a [`Role::Heading`] at all, so a glyph scan called it body text and
147    /// the line drew at body height until the first character landed. Riding the
148    /// row says it once, for the empty case and the wrapped case alike.
149    ///
150    /// Per-*glyph* styling still comes from [`Role::Heading`] on the glyphs; this
151    /// is the row-level fact, and the two agree wherever a heading has content —
152    /// same `u8` level, clamped the same way [`heading_style`] clamps it.
153    pub heading: Option<u8>,
154    /// How this row's block is aligned across the measure — the author's
155    /// `class="center"`, on every row the block emits and `None` for the
156    /// theme's default, which is left.
157    ///
158    /// A *row* fact and not a glyph one for [`heading`](Self::heading)'s reason,
159    /// and more sharply: alignment is a property of the *line*, not of the
160    /// letters on it, so an empty paragraph the author has just centred has to
161    /// carry it with no glyph to hang it on. It rides the row like a plain
162    /// `Copy` flag, so [`BlockCache`] reuse and [`build_spliced`] carry it
163    /// untouched.
164    ///
165    /// Read from the paragraph's or heading's own attributes and from those of
166    /// every `div` around it, the nearest winning — so `<div class="center">`
167    /// around three paragraphs centres all three, which is what the author of
168    /// that HTML meant.
169    pub align: Option<Align>,
170    /// How far apart this row's block sets its lines, as a multiple of the
171    /// theme's own line height — the author's `data-line-height`, on every row
172    /// the block emits and `None` for the theme's spacing.
173    ///
174    /// A frontend that lays rows out in pixels scales the row's height by
175    /// [`LineSpacing::ratio`]; one that draws a row per terminal line ignores it,
176    /// the way it ignores a heading's size. Read at the same two levels
177    /// [`align`](Self::align) is.
178    pub line_height: Option<LineSpacing>,
179    /// What this row divides, on the blank rows a block boundary is *drawn* with
180    /// and `None` on every other row — including the navigable blank lines of
181    /// preserve-soft flow, which are somewhere text can go rather than a gap
182    /// between blocks. So `boundary.is_some()` is exactly "this row is a drawn
183    /// block boundary", the [`decoration`](Self::decoration) rows that come from
184    /// [`Builder::emit_separators_before`].
185    ///
186    /// It exists because a boundary's *height* is a frontend decision but its
187    /// *kind* is not. Typography spaces a boundary by what it separates — the
188    /// margin above a heading is wider than the one between two paragraphs, so
189    /// the heading groups with the text it introduces — and a frontend that has
190    /// only rows to look at has to re-derive the structure by sniffing glyph
191    /// roles. Three frontends sniffing separately is three chances to disagree
192    /// about the same document. Core already knows, having just walked the AST
193    /// to emit this row, so it says so once here and each frontend multiplies by
194    /// its own spacing.
195    pub boundary: Option<Boundary>,
196    /// The offsets on this row where an inline mark's *content* ends under a
197    /// hidden closing delimiter — the end of the `d` in `**bold**`, one byte
198    /// before the `**` that draws nothing. Each is a caret stop with no glyph
199    /// of its own: the caret standing there is drawn where the next glyph is,
200    /// but typing there extends the mark, where typing past the delimiter
201    /// leaves it. See [`VisualMap::mark_ends`] for the rule.
202    ///
203    /// Source offsets, so [`shift_row`] moves them with the glyphs; empty on
204    /// decoration rows and on every row no mark closes on.
205    pub mark_ends: Vec<usize>,
206}
207
208/// What a drawn block boundary separates: the kinds of the blocks it falls
209/// between — the pair a frontend spaces by.
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211pub struct Boundary {
212    pub above: BlockClass,
213    pub below: BlockClass,
214}
215
216/// The block kinds core tells apart when it walks a document — the vocabulary
217/// [`Boundary`] is spelled in. A statement about *structure*, not about how any
218/// of it should look: what a frontend does with "this gap sits above a heading"
219/// is entirely the frontend's.
220///
221/// `Class` rather than `Kind` because [`twig::BlockKind`] already means
222/// something else in this crate's public surface — the *command* vocabulary
223/// (`Paragraph | Heading(n)`) a toolbar passes to [`Doc::set_block`](crate::Doc::set_block).
224/// This is the reverse direction: what a block already *is*, read back off a
225/// rendered row.
226///
227/// [`BlockClass::Other`] is the honest answer for a node kind core doesn't
228/// separate out, so adding one here is additive for every frontend: nothing has
229/// to change until it wants to space that kind differently.
230#[derive(Clone, Copy, Debug, PartialEq, Eq)]
231pub enum BlockClass {
232    Paragraph,
233    Heading,
234    /// A whole list. Its *items* are [`BlockClass::ListItem`]; note that core
235    /// draws no boundary row between two items of one list, tight or loose, so
236    /// an item↔item pair never reaches a frontend.
237    List,
238    ListItem,
239    Quote,
240    Code,
241    Table,
242    /// A block-level image, video, or audio.
243    ///
244    /// Never reached through [`from_node_kind`](BlockClass::from_node_kind): a
245    /// block picture is not a node of its own — [`Builder::media_only`] promotes
246    /// the paragraph (or `<picture>`/`<video>` container) wrapping it — so the
247    /// walk only ever sees the wrapper's kind. [`label_media_boundaries`] reads
248    /// it back off the finished rows instead, after the fact.
249    Media,
250    /// A `:::name{.class}` directive container.
251    Directive,
252    Rule,
253    Footnote,
254    Other,
255}
256
257impl BlockClass {
258    /// Classify a twig node kind — the same vocabulary [`Builder::block`]
259    /// matches on, so the two can't drift about what a block is. Both the
260    /// whole-arena walk (which has [`FlatNode`]s) and the incremental top-level
261    /// walk (which has only a query match's kind) reach it by this one door.
262    pub fn from_node_kind(kind: &Kind) -> BlockClass {
263        match kind {
264            Kind::Para => BlockClass::Paragraph,
265            Kind::Heading => BlockClass::Heading,
266            Kind::BulletList | Kind::OrderedList | Kind::TaskList => BlockClass::List,
267            Kind::ListItem | Kind::TaskListItem => BlockClass::ListItem,
268            Kind::BlockQuote => BlockClass::Quote,
269            Kind::CodeBlock => BlockClass::Code,
270            Kind::Table => BlockClass::Table,
271            Kind::Image => BlockClass::Media,
272            // twig 2.8 folded `div`/`span`/`directive`/`element` into one
273            // `container` kind, so a `:::note` panel and a promoted `<video>`
274            // arrive here indistinguishable — telling them apart needs the
275            // node's `origin`, and the incremental walk has only this kind.
276            // `Directive` is the right answer for the case that motivates the
277            // class (nothing else draws a tinted panel) and a harmless one for
278            // the rest: `BlockClass` is descriptive and core never branches on
279            // it. The one case where it was actively wrong — a promoted
280            // `<video>`, which would have been handed to a frontend as something
281            // to draw a fenced-div panel around — is corrected by
282            // [`label_media_boundaries`] once the rows are final, along the same
283            // door as a block image. Anything else that must be exact reads
284            // [`container_is_directive`] off a real node.
285            Kind::Container => BlockClass::Directive,
286            Kind::ThematicBreak => BlockClass::Rule,
287            Kind::Footnote => BlockClass::Footnote,
288            _ => BlockClass::Other,
289        }
290    }
291}
292
293/// The name and attributes a leaf directive's placeholder row carries, so a
294/// frontend that knows the host app's vocabulary can paint the real thing —
295/// an embedded page for diaryx's `::embed{src=…}`, a generated table of
296/// contents for a `::toc`, and the plain `⧉ name` label for one it doesn't
297/// know. The peer of [`MediaMark`], and plain strings for the same reason: they
298/// survive the row shuffling of [`BlockCache`] reuse and [`build_spliced`].
299#[derive(Clone, Debug, PartialEq, Eq)]
300pub struct DirectiveMark {
301    /// The directive's type — `embed`, `toc`, `vis` — with no leading colons.
302    /// Core is agnostic of what it means: the vocabulary is the host app's.
303    pub name: String,
304    /// Its `{…}` attributes as `(key, value)` pairs in source order. A bare
305    /// attribute (`{public}`) has a `None` value, the way twig reports it.
306    pub attrs: Vec<(String, Option<String>)>,
307    /// The directive's `[label]` text, flattened from its inline children, or
308    /// empty when it has none. Also what the placeholder label shows.
309    pub label: String,
310    /// How many visual rows this directive reserves — the label row plus blank
311    /// filler rows below it, so a frontend painting something real has the
312    /// vertical room. `1` is the bare placeholder, and the only value core
313    /// produces today: unlike an image (whose height a terminal frontend
314    /// measures and reports back), nothing has told core how tall an embed is.
315    /// A pixel-laid-out GUI sets its own height regardless.
316    pub rows: usize,
317}
318
319/// What a block-level media placeholder actually is, so a frontend knows which
320/// widget to build over the reserved rows: a raster, a movie player, or a
321/// transport with no picture at all. Core classifies and stops there — it opens
322/// nothing, so this is a statement about the *markup*, not about a file it has
323/// verified exists or can decode.
324#[derive(Clone, Copy, Debug, PartialEq, Eq)]
325pub enum MediaKind {
326    /// A `![](…)` / `<img>` / `<picture>` — a still picture.
327    Image,
328    /// An HTML `<video>`. Markdown and Djot spell no video of their own, so this
329    /// only ever arrives through `html_elements` promotion (or a `::video{…}`
330    /// directive a host app maps itself, which core reports as a directive).
331    Video,
332    /// An HTML `<audio>` — a transport with no picture, so a frontend gives it a
333    /// fixed control height rather than measuring an aspect ratio.
334    Audio,
335}
336
337/// Which of the two caret homes a block media has — see
338/// [`VisualMap::block_media_stop`].
339#[derive(Clone, Copy, Debug, PartialEq, Eq)]
340pub enum MediaStop {
341    /// The stop in front of the picture. What is typed here belongs above it.
342    Before,
343    /// The stop just past it. What is typed here belongs below it.
344    After,
345}
346
347impl MediaKind {
348    /// The emoji a plain surface prefixes the placeholder label with — the
349    /// `🖼`/`🎬`/`🔊` that makes the row read as *a thing* rather than as text.
350    fn sigil(self) -> char {
351        match self {
352            MediaKind::Image => '🖼',
353            MediaKind::Video => '🎬',
354            MediaKind::Audio => '🔊',
355        }
356    }
357}
358
359/// The destination and label a block-level media placeholder row carries, so a
360/// capable frontend can resolve and paint the real thing. Plain strings (no
361/// source offsets), so they survive the row shuffling of [`BlockCache`] reuse
362/// and [`build_spliced`] untouched — see [`VRow::media`].
363#[derive(Clone, Debug, PartialEq, Eq)]
364pub struct MediaMark {
365    /// Whether this is a picture, a movie, or a sound — which widget the
366    /// frontend builds over the reserved rows.
367    pub kind: MediaKind,
368    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
369    /// the AST. A frontend resolves a relative path against the document's
370    /// directory itself; core holds no I/O.
371    ///
372    /// Empty is possible and legal for a `<video>`/`<audio>`, which may carry no
373    /// `src` of its own and name its candidates in child `<source>`s instead —
374    /// unlike an `<img>`, whose `src` *is* the picture. A frontend with an empty
375    /// destination takes its URL from [`sources`](MediaMark::sources).
376    pub destination: String,
377    /// A `<picture>`'s theme/media alternatives, in document order, when this
378    /// block image came from one; empty for a plain `![](…)` / bare `<img>`. Each
379    /// is a `<source>`'s media query + candidate URL(s); a frontend that knows its
380    /// theme picks the first whose media matches and falls back to [`destination`]
381    /// (the `<img>`). Core keeps them verbatim and picks nothing — it has no theme.
382    ///
383    /// [`destination`]: MediaMark::destination
384    pub sources: Vec<MediaSource>,
385    /// The media's alt text (its rendered inline children, flattened), or empty
386    /// when it has none. Also what the placeholder label shows. For a `<video>`/
387    /// `<audio>` this is the element's own text content — the "your browser does
388    /// not support…" fallback, which doubles as its accessible name.
389    pub alt: String,
390    /// A `<video poster="…">`'s still frame, verbatim, or empty when there is
391    /// none (and always empty for an image or audio). It is an *image*
392    /// destination, so a frontend already able to draw a picture can show it
393    /// before the movie loads — or in place of one it can't play at all.
394    pub poster: String,
395    /// How many visual rows this media reserves — the placeholder label row plus
396    /// the blank filler rows below it, so a frontend that paints a real raster has
397    /// the vertical room to draw it. `1` is the bare placeholder (a frontend that
398    /// can't draw pictures, or an image it couldn't resolve). A terminal frontend
399    /// asks for as many rows as the fitted picture is tall; the pixel-laid-out GUI
400    /// ignores this and sets its own row height, so it always leaves it `1`. The
401    /// count comes from the frontend (via [`crate::Doc::set_media_rows`]) because
402    /// core does no I/O and can't measure the image itself. See [`VRow::media`].
403    pub rows: usize,
404}
405
406/// One `<source>` under a `<picture>`, `<video>`, or `<audio>`: a candidate URL
407/// plus whichever of the two things HTML lets a `<source>` be chosen by — a
408/// media query (`<picture>`) or a MIME type (`<video>`/`<audio>`). Verbatim from
409/// the AST: core carries the alternatives and resolves none of them, having
410/// neither a theme nor a codec list to judge them by.
411///
412/// The two spellings are normalised onto one field. `<picture>` writes
413/// `srcset`, `<video>`/`<audio>` write `src`; both land in
414/// [`srcset`](MediaSource::srcset), since a frontend wants the URL either way
415/// and only `<picture>` ever uses the descriptor syntax.
416#[derive(Clone, Debug, PartialEq, Eq)]
417pub struct MediaSource {
418    /// The `<source media="…">` query, verbatim (`"(prefers-color-scheme: dark)"`),
419    /// or empty for a `<source>` with no `media` (an unconditional override, and
420    /// the norm for `<video>`/`<audio>`, which pick by codec rather than theme).
421    pub media: String,
422    /// The candidate URL(s): a `<picture>`'s `srcset` verbatim — one URL, or a
423    /// comma-separated candidate list with `1x`/`2x`/width descriptors — or a
424    /// `<video>`/`<audio>` `<source>`'s plain `src`. A frontend takes the first
425    /// URL token; the theme and codec cases both only ever need that.
426    pub srcset: String,
427    /// The `<source type="…">` MIME type (`"video/webm"`), verbatim, or empty
428    /// when the `<source>` declares none. How a `<video>`/`<audio>` frontend
429    /// picks a candidate it can actually decode; a `<picture>`'s sources
430    /// normally leave it empty and are chosen by [`media`](MediaSource::media).
431    pub mime: String,
432}
433
434/// The rendered document plus the offset⇄position mapping the caret rides on.
435#[derive(Clone, Default)]
436pub struct VisualMap {
437    /// The document's **default monospace rendering** — one [`VRow`] of glyphs
438    /// per visual line, tables spelled with box-drawing borders (`│ ─ ┌┬┐…`) and
439    /// cells padded to whole character-cell columns. Any monospace surface can
440    /// draw these verbatim, so a consumer gets a working view for free: the TUI
441    /// paints them as-is, and a five-line plain-text dump would too.
442    ///
443    /// It's a *default*, not the only truth. A frontend with its own geometry —
444    /// a proportional GUI — lays text out in its own units, and for a table
445    /// skips the box-drawn rows named by [`TableInfo::rows_span`] and draws from
446    /// the structural [`TableInfo`] instead. The box glyphs live here rather than
447    /// in a frontend precisely because they *are* a renderable default: unlike a
448    /// colour (a role each surface must map to its own palette — see
449    /// [`crate::style`]), `┌─┐` is finished text that needs no interpretation.
450    pub rows: Vec<VRow>,
451    /// The first source offset that is actually rendered — the caret floor for
452    /// the WYSIWYG view. Non-zero when a leading `metadata` block (YAML/TOML
453    /// frontmatter) is skipped: the frontmatter is preserved in the source and
454    /// editable in the source view, but hidden and unreachable here, so the
455    /// caret and selection can't wander into it (and copy won't grab it).
456    pub content_start: usize,
457    /// Every offset the caret may rest at, ascending and deduplicated: each
458    /// row's stop glyphs plus the row's own end (the "after the last character"
459    /// spot every line needs). Decoration contributes nothing.
460    ///
461    /// Left/Right read this instead of walking the grid, because the grid isn't
462    /// laid out in offset order: a table with wrapped cells puts column 1's
463    /// second line *below* column 2's first, so "the next stop rightward" and
464    /// "the next stop in the document" part ways. Following the document is what
465    /// a caret means — and on every row that *is* in order the two agree anyway,
466    /// so nothing else has to change.
467    stops: Vec<usize>,
468    /// The caret's second home at the end of every hidden inline mark: the
469    /// offset where the mark's content ends, one byte before its closing
470    /// delimiter — ascending and deduplicated, from every row's
471    /// [`VRow::mark_ends`].
472    ///
473    /// With delimiters hidden, `**bold** tail` draws one spot after the `d`
474    /// and the source has two offsets for it: the content end (inside the
475    /// mark, where typing extends the bold) and the byte past the `**` (where
476    /// typing leaves it). Only the second is a glyph's offset, so only it was
477    /// a stop, and a caret asked to rest at the first was snapped a whole
478    /// character back onto the `d` — a drag over `bold` came back one letter
479    /// short. The delete and backspace paths already settle the caret on the
480    /// content end as its natural home there
481    /// ([`crate::Doc::settle_inside_close_delims`]); this makes it one the
482    /// caret can be placed at and step onto too.
483    ///
484    /// Kept apart from [`stops`](Self::stops) rather than merged in, because
485    /// the two lists answer different questions. A stop with no glyph is
486    /// invisible to a walk that pairs stops with characters — a system text
487    /// input counting `position(from:offset:)` steps against the text it was
488    /// shown would drift a character at every mark — and to word motion, which
489    /// classifies a stop by the source byte under it (a `*`). So
490    /// [`stop_after`](Self::stop_after) and its kin walk the glyph stops alone,
491    /// and only the places a caret *rests* — snapping, resting checks, and
492    /// Left/Right — read both.
493    mark_ends: Vec<usize>,
494    /// Every table in the document, in order, described structurally rather than
495    /// drawn — see [`TableInfo`] for why both exist.
496    pub tables: Vec<TableInfo>,
497    /// Every fenced/indented code block, in order, as the range of [`rows`] it
498    /// occupies — a frontend draws one bordered, tinted box around each and
499    /// scrolls it horizontally rather than wrapping. Derived from the per-row
500    /// [`VRow::code`] flag once the rows are final (so it survives incremental
501    /// row reuse), the same way [`collect_stops`] derives the stop table.
502    ///
503    /// [`rows`]: VisualMap::rows
504    pub code_blocks: Vec<CodeBlockInfo>,
505    /// Every block-level image in the document, in order — one per placeholder
506    /// row a frontend replaces with a real picture. Derived from the per-row
507    /// [`VRow::media`] mark once the rows are final (so it survives incremental
508    /// row reuse), the same way [`code_blocks`](VisualMap::code_blocks) is
509    /// derived from [`VRow::code`].
510    pub media: Vec<MediaInfo>,
511    /// Every **leaf** directive in the document, in order — one per placeholder
512    /// row a frontend may replace with whatever the host app's vocabulary makes
513    /// of it. Derived from the per-row [`VRow::leaf_directive`] mark once the
514    /// rows are final, exactly as [`media`](VisualMap::media) is.
515    pub directives: Vec<DirectiveInfo>,
516}
517
518impl VisualMap {
519    pub fn num_rows(&self) -> usize {
520        self.rows.len()
521    }
522
523    /// The width of `row` in display columns — the rightmost column its caret
524    /// can occupy, and so what a goal column is clamped to on the way in.
525    pub fn row_width(&self, row: usize) -> usize {
526        self.rows.get(row).map_or(0, |r| r.width())
527    }
528
529    /// The screen `(row, col)` for a source offset — where to draw the caret:
530    /// the *nearest* stop at or past `off`. Snaps a hidden offset (inside a
531    /// delimiter) to the next visible glyph, and never resolves onto decoration
532    /// (a table border, a cell's padding), which is drawn but holds no caret.
533    ///
534    /// "Nearest" rather than "the first one found" because a table's wrapped
535    /// cells put rows slightly out of offset order: scanning top to bottom, the
536    /// second line of column 1 comes *after* the first line of column 2 but
537    /// holds smaller offsets. Where rows are in order the two rules agree.
538    ///
539    /// A soft wrap is the one place two rows want the same offset: the row above
540    /// ends where the row below opens, the space the wrap ate being drawn on the
541    /// row above and the offset past it being the row below's first character.
542    /// It resolves *downstream*, to the row that character is on — the row
543    /// above's last column is a phantom, a place the caret can be drawn but
544    /// never sent, and resolving upstream into it is what pinned Down at the
545    /// first wrap of a paragraph: it aimed at the row below's column 0, landed
546    /// on the offset it already had, and read that back as the row above's end.
547    pub fn pos_of_offset(&self, off: usize) -> (usize, usize) {
548        let mut best: Option<(usize, usize, usize)> = None; // (src, row, col)
549        for (r, row) in self.rows.iter().enumerate() {
550            if row.decoration {
551                continue;
552            }
553            // Offsets ascend *within* a row, so its first stop at or past `off`
554            // is the best this row has to offer.
555            let cand = row
556                .glyphs
557                .iter()
558                .enumerate()
559                .find(|(_, g)| g.stop && g.src >= off)
560                .map(|(i, g)| (g.src, r, row.col_of_glyph(i)))
561                .or_else(|| (row.end_src >= off).then_some((row.end_src, r, row.width())));
562            if let Some(c) = cand {
563                // `<=`, so a tie goes to the later row: the only offset two rows
564                // both hold is a wrap boundary, and it belongs to the row below.
565                if best.is_none_or(|b| c.0 <= b.0) {
566                    best = Some(c);
567                }
568            }
569            // A row's *first* stop never decreases from one row to the next —
570            // true even across a table's wrapped cells, since a cell's lines run
571            // downward. So once a row opens past the best found so far, no later
572            // row can beat it and the scan stays proportional to `off`.
573            if let (Some(b), Some(first)) = (best, row.glyphs.iter().find(|g| g.stop))
574                && first.src > b.0
575            {
576                break;
577            }
578        }
579        match best {
580            Some((_, r, c)) => (r, c),
581            None => {
582                let r = self.last_stop_row();
583                (r, self.row_width(r))
584            }
585        }
586    }
587
588    /// The rows a source range occupies, inclusive: `(first, last)`.
589    ///
590    /// A *different question* from [`pos_of_offset`](Self::pos_of_offset), which
591    /// is why it can't be spelled with two calls to it. That one answers "where
592    /// does the caret go", and for a caret its forward snap is right — an offset
593    /// inside a hidden delimiter has no column of its own, so the caret belongs
594    /// at the next visible glyph, wherever that turns out to be. This one asks
595    /// "which rows does this block cover", and there the snap is a trap: a
596    /// footnote whose body *ends* in a link (`[^2]: [title](url)`) has a last
597    /// byte inside the hidden destination, so `pos_of_offset(end - 1)` walked
598    /// clean off the note's row and landed on the next note's — and a peek
599    /// slicing `first..=last` out of the frame drew two notes where the reader
600    /// asked for one. Every block ending in a link, an image, or any trailing
601    /// hidden markup had the same fault; only a block ending in visible text
602    /// (which is what the tests happened to use) did not.
603    ///
604    /// `row.end_src` is no help either: it is where the *rendered* text of a row
605    /// ends, not how far into the source the block reaches, and redefining it
606    /// would move every end-of-line caret.
607    ///
608    /// So the last row is found by asking which rows *open* before the range
609    /// does, rather than by mapping its last byte: a row belongs to the range
610    /// when its first caret stop lies before `range.end`. Decoration is skipped
611    /// (a drawn gap between blocks is not part of either), and the answer is
612    /// never shorter than one row — a range whose every byte is hidden still
613    /// covers the row it started on.
614    pub fn row_range_for(&self, range: Range<usize>) -> (usize, usize) {
615        if self.rows.is_empty() {
616            return (0, 0);
617        }
618        let first = self.pos_of_offset(range.start).0;
619        let mut last = first;
620        for (r, row) in self.rows.iter().enumerate().skip(first) {
621            if row.decoration {
622                continue;
623            }
624            let open = row
625                .glyphs
626                .iter()
627                .find(|g| g.stop)
628                .map_or(row.end_src, |g| g.src);
629            if open >= range.end {
630                // A row's first stop never decreases from one row to the next —
631                // the invariant `pos_of_offset` breaks on, true even across a
632                // table's wrapped cells — so nothing below can be in range.
633                break;
634            }
635            last = r;
636        }
637        (first, last)
638    }
639
640    /// The source offset of the task checkbox drawn at `(row, col)`, or `None`
641    /// when that cell holds no box — the hit-test a frontend runs on a click
642    /// before treating it as a tick rather than a caret placement.
643    ///
644    /// Only the box's own cells answer. Clicking an item's *text* places the
645    /// caret like any other click, so the box is a target aimed at rather than
646    /// something tripped over while editing — which is also why this is a
647    /// separate question from [`offset_of_pos`](Self::offset_of_pos) instead of
648    /// a flag on the offset it returns.
649    pub fn task_box_at(&self, row: usize, col: usize) -> Option<usize> {
650        let r = self.rows.get(row)?;
651        self.task_box_at_glyph(row, r.glyph_at_col(col)?)
652    }
653
654    /// [`task_box_at`](Self::task_box_at) keyed by glyph index rather than
655    /// display column — for a frontend that shapes its own rows (the GUI) and so
656    /// resolves a click to a glyph before it ever has a column.
657    pub fn task_box_at_glyph(&self, row: usize, glyph: usize) -> Option<usize> {
658        let r = self.rows.get(row)?;
659        r.task?;
660        let g = r.glyphs.get(glyph)?;
661        (g.style.role == Role::ListMarker).then_some(g.src)
662    }
663
664    /// The source offset for a screen `(row, col)` — where a click or a
665    /// visual-space move lands the caret. Clicking decoration maps through its
666    /// `src`, which points at the text it decorates, so a click on a border or
667    /// on a cell's padding lands in that cell.
668    ///
669    /// The inverse of [`pos_of_offset`](Self::pos_of_offset), which it has to
670    /// agree with: `col` is a display column, and the one it names may be the
671    /// far cell of a wide glyph — [`VRow::glyph_at_col`] is where that lands.
672    pub fn offset_of_pos(&self, row: usize, col: usize) -> usize {
673        let Some(r) = self.rows.get(row) else {
674            // A click or drag below the last row — a short document with empty
675            // space under it, dragged into to extend a selection. Land on the
676            // document's last caret stop (its end), not offset 0: jumping the
677            // caret to the top is the wrong direction, and 0 isn't even a stop
678            // when the document opens on hidden frontmatter or a `# ` marker, so
679            // returning it would leave the caret where it draws in one place and
680            // types in another (`move_to` would then clamp it onto the unhomeable
681            // frontmatter floor). `None` only for a document with no stops at all
682            // (empty), where the caret has nowhere to be but 0.
683            return self.stops.last().copied().unwrap_or(0);
684        };
685        match r.glyph_at_col(col).and_then(|i| r.glyphs.get(i)) {
686            // A glyph that holds no caret is clickable, but where it points
687            // isn't always somewhere the caret can be: the blank gap between two
688            // paragraphs stands at an offset that belongs to neither of them,
689            // and the tail of a grapheme cluster stands inside a character.
690            // Land on the nearest real stop instead of handing back an offset
691            // that looks like the gap but types into the paragraph above.
692            Some(g) if !g.stop => self.nearest_stop(g.src),
693            Some(g) => g.src,
694            // A row's end is a stop by construction — unless the row is
695            // decoration, which contributes none.
696            None if r.decoration => self.nearest_stop(r.end_src),
697            None => r.end_src,
698        }
699    }
700
701    /// Which of a block media's two caret homes `off` is, or `None` for every
702    /// other offset in the document.
703    ///
704    /// [`block_media`](Builder::block_media) gives a block-level image, video, or
705    /// audio exactly two stops — one in front of it and one just past it — and
706    /// nothing inside the markup. Both are ordinary offsets to everything else in
707    /// core, but they are the two places where inserting text would *dissolve the
708    /// picture*: `![](p.png)` with anything typed against it is no longer a block
709    /// image but a paragraph with an inline one, and the frontend that was
710    /// painting a photo there paints a text run instead. A caller that is about to
711    /// insert asks this so it can open a paragraph first — see
712    /// [`Doc::insert`](crate::Doc::insert).
713    ///
714    /// An *inline* image reports `None`: it has no placeholder row and no stops of
715    /// its own, and typing beside one is ordinary editing.
716    ///
717    /// Answers with the media's own source span as well, since a caller that has
718    /// to keep the picture whole usually has to address it — [`Doc::backspace`]
719    /// takes the picture out in one piece rather than nibbling a byte off its
720    /// markup, which is the same dissolution from the other side.
721    ///
722    /// [`Doc::backspace`]: crate::Doc::backspace
723    pub fn block_media_stop(&self, off: usize) -> Option<(MediaStop, Range<usize>)> {
724        for m in &self.media {
725            let Some(row) = self.rows.get(m.rows_span.start) else {
726                continue;
727            };
728            // Every glyph of the `🖼 alt` label maps to the media's start offset;
729            // the row's end is past its markup. Read the start off the label
730            // rather than the first glyph, which on a quoted or listed picture is
731            // the block prefix and points at the gutter.
732            let Some(start) = row
733                .glyphs
734                .iter()
735                .find(|g| g.style.role == Role::Image)
736                .map(|g| g.src)
737            else {
738                continue;
739            };
740            if off == start {
741                return Some((MediaStop::Before, start..row.end_src));
742            }
743            if off == row.end_src {
744                return Some((MediaStop::After, start..row.end_src));
745            }
746        }
747        None
748    }
749
750    /// Whether `off` is a table's trailing caret stop — the one home past a
751    /// table's last cell, at the block's own end ([`TableInfo::end_src`]).
752    ///
753    /// The table's peer of [`block_media_stop`](Self::block_media_stop)'s
754    /// `After`: text inserted at that offset joins the table's last source
755    /// line, and a line glued under a table is a row of it (`| 1 | 2 |x`), so
756    /// a caller about to insert there opens a paragraph first — see
757    /// [`Doc::insert`](crate::Doc::insert). Nothing else about the offset is
758    /// special: it is where Down from the last row lands and where a click in
759    /// the blank space under a trailing table lands.
760    pub fn table_end_stop(&self, off: usize) -> bool {
761        self.tables.iter().any(|t| t.end_src == off)
762    }
763
764    /// Snap `off` to the nearest caret stop — the funnel a frontend that
765    /// hit-tests pixels straight to a source offset must run its result through.
766    /// A click or drag can land in the blank gap a paragraph break is drawn with,
767    /// or inside a hidden delimiter; both are offsets the caret can't rest at, so
768    /// resting there would draw the caret in one place and type in another. This
769    /// settles it on a real caret home instead. Idempotent on an offset that is
770    /// already a stop — the `(row, col)` click path already snaps this way inside
771    /// [`offset_of_pos`](Self::offset_of_pos), and this gives the pixel path the
772    /// same guarantee. Returns `off` unchanged only for an empty document (no
773    /// stops at all).
774    pub fn snap_to_stop(&self, off: usize) -> usize {
775        self.nearest_stop(off)
776    }
777
778    /// The caret stop nearest `off`, preferring the one before it when `off`
779    /// falls exactly between two. Returns `off` unchanged if there are no stops
780    /// at all (an empty document). A mark's content end counts: it is a place
781    /// the caret rests, and the one a drag ending on a marked word means.
782    fn nearest_stop(&self, off: usize) -> usize {
783        let before = Self::last_at_or_before(&self.stops, off)
784            .max(Self::last_at_or_before(&self.mark_ends, off));
785        let after = match (
786            Self::first_at_or_after(&self.stops, off),
787            Self::first_at_or_after(&self.mark_ends, off),
788        ) {
789            (Some(a), Some(b)) => Some(a.min(b)),
790            (a, b) => a.or(b),
791        };
792        match (before, after) {
793            (Some(b), Some(a)) if off - b <= a - off => b,
794            (_, Some(a)) => a,
795            (Some(b), None) => b,
796            (None, None) => off,
797        }
798    }
799
800    /// The glyph stop nearest `off` — [`nearest_stop`](Self::nearest_stop)
801    /// for a walk that pairs stops with characters, which a mark's content
802    /// end has none of. A caret resting on one resolves to the glyph stop
803    /// drawn at the same spot, the one just past the hidden delimiter, so the
804    /// text a system input is shown from there and the steps it counts agree.
805    pub fn snap_to_glyph_stop(&self, off: usize) -> usize {
806        if self.mark_ends.binary_search(&off).is_ok()
807            && let Some(next) = Self::first_at_or_after(&self.stops, off)
808        {
809            return next;
810        }
811        let before = Self::last_at_or_before(&self.stops, off);
812        let after = Self::first_at_or_after(&self.stops, off);
813        match (before, after) {
814            (Some(b), Some(a)) if off - b <= a - off => b,
815            (_, Some(a)) => a,
816            (Some(b), None) => b,
817            (None, None) => off,
818        }
819    }
820
821    /// The last of `sorted` at or before `off`, if any.
822    fn last_at_or_before(sorted: &[usize], off: usize) -> Option<usize> {
823        let i = sorted.partition_point(|&s| s <= off);
824        i.checked_sub(1).map(|i| sorted[i])
825    }
826
827    /// The first of `sorted` at or after `off`, if any.
828    fn first_at_or_after(sorted: &[usize], off: usize) -> Option<usize> {
829        let i = sorted.partition_point(|&s| s < off);
830        sorted.get(i).copied()
831    }
832
833    /// The next place the caret rests past `off` — the next glyph stop or the
834    /// next mark's content end, whichever comes first. What Right walks:
835    /// leaving `**bold**` from the `d` is two presses, one onto the end of the
836    /// bold (still bold, the toolbar lit) and one past its delimiter, at the
837    /// same spot on screen. [`stop_after`](Self::stop_after) is the walk that
838    /// skips the first, for every caller that pairs stops with characters.
839    pub fn caret_stop_after(&self, off: usize) -> Option<usize> {
840        match (
841            self.stop_after(off),
842            Self::first_at_or_after(&self.mark_ends, off + 1),
843        ) {
844            (Some(a), Some(b)) => Some(a.min(b)),
845            (a, b) => a.or(b),
846        }
847    }
848
849    /// The previous place the caret rests before `off` — the mirror of
850    /// [`caret_stop_after`](Self::caret_stop_after), what Left walks.
851    pub fn caret_stop_before(&self, off: usize) -> Option<usize> {
852        self.stop_before(off).max(
853            off.checked_sub(1)
854                .and_then(|o| Self::last_at_or_before(&self.mark_ends, o)),
855        )
856    }
857
858    /// Whether the caret can occupy `row` at all: decoration rows (a table's
859    /// border rules) are stepped over by vertical motion.
860    pub fn row_is_navigable(&self, row: usize) -> bool {
861        self.rows.get(row).is_some_and(|r| !r.decoration)
862    }
863
864    /// The first offset the caret can rest at on `row` — its first stop, or the
865    /// row's own end when it holds no text (an empty paragraph). `None` for a
866    /// decoration row, which holds no caret at all.
867    ///
868    /// Not `offset_of_pos(row, 0)`: column 0 of a quoted or listed row is the
869    /// gutter, and a gutter's `src` points at the *block* it opens, so the stop
870    /// nearest it is the one on the block's first row rather than on this one.
871    /// Which is right for a click — the gutter decorates the whole block — and
872    /// wrong for Home, whose whole question is where *this* row starts.
873    pub fn row_start(&self, row: usize) -> Option<usize> {
874        let r = self.rows.get(row).filter(|r| !r.decoration)?;
875        Some(
876            r.glyphs
877                .iter()
878                .find(|g| g.stop)
879                .map_or(r.end_src, |g| g.src),
880        )
881    }
882
883    /// The last row the caret can rest on — the fallback when an offset is past
884    /// everything rendered (a table's bottom border must not swallow the caret).
885    fn last_stop_row(&self) -> usize {
886        (0..self.rows.len())
887            .rev()
888            .find(|&r| self.row_is_navigable(r))
889            .unwrap_or(0)
890    }
891
892    /// The nearest row above `row` the caret can occupy, skipping decoration.
893    pub fn navigable_above(&self, row: usize) -> Option<usize> {
894        (0..row.min(self.rows.len()))
895            .rev()
896            .find(|&r| self.row_is_navigable(r))
897    }
898
899    /// The nearest row below `row` the caret can occupy, skipping decoration.
900    pub fn navigable_below(&self, row: usize) -> Option<usize> {
901        ((row + 1)..self.rows.len()).find(|&r| self.row_is_navigable(r))
902    }
903
904    /// The caret stop just before `off` — one press of Left. `None` at the
905    /// first stop in the document.
906    ///
907    /// Runs of decoration (a table border, a cell's alignment padding) are
908    /// stepped over in a single press: they hold no stop, so they aren't in the
909    /// table to land on.
910    pub fn stop_before(&self, off: usize) -> Option<usize> {
911        let i = self.stops.partition_point(|&s| s < off);
912        i.checked_sub(1).map(|i| self.stops[i])
913    }
914
915    /// The caret stop just after `off` — one press of Right. `None` at the last
916    /// stop in the document.
917    pub fn stop_after(&self, off: usize) -> Option<usize> {
918        let i = self.stops.partition_point(|&s| s <= off);
919        self.stops.get(i).copied()
920    }
921
922    /// The first caret stop at or past `off` — where the caret at a hidden
923    /// offset is *drawn*, and so where a rightward walk over the rendered text
924    /// starts from.
925    pub fn stop_at_or_after(&self, off: usize) -> Option<usize> {
926        let i = self.stops.partition_point(|&s| s < off);
927        self.stops.get(i).copied()
928    }
929
930    /// The last caret stop at or before `off` — where a leftward walk starts
931    /// from. Snapping the way the walk is headed, rather than always forward,
932    /// is what keeps a leftward motion from ever moving the caret right.
933    pub fn stop_at_or_before(&self, off: usize) -> Option<usize> {
934        let i = self.stops.partition_point(|&s| s <= off);
935        i.checked_sub(1).map(|i| self.stops[i])
936    }
937
938    /// Whether the caret may rest at `off` — the invariant every motion in this
939    /// view has to leave standing. A glyph stop, a row's end, or a hidden
940    /// mark's content end ([`mark_ends`](Self::mark_ends)).
941    pub fn is_stop(&self, off: usize) -> bool {
942        self.stops.binary_search(&off).is_ok() || self.mark_ends.binary_search(&off).is_ok()
943    }
944
945    /// The visible text a caret crosses walking rightward from `from` up to
946    /// (but not including) `to` — `UITextInput.text(in:)`'s `[from, to)` in
947    /// *this* view. A hidden inline-mark delimiter (`**`, `` ` ``, `_`, an
948    /// escape backslash) never got a glyph in the first place — see
949    /// [`push_text`]/[`synth`] — so it contributes nothing; what's left is
950    /// what's drawn on screen for that span, one character per caret stop.
951    ///
952    /// **Exactly one character per stop** is the contract, and it is the
953    /// system text input's, not a nicety: `UITextInput`'s tokenizer reads a
954    /// window of this text around a tap, indexes into it by the integer
955    /// `offset(from:to:)` reports (`distance_offset` in `leaf-ffi`, a count of
956    /// [`stop_after`](Self::stop_after) hops), finds a word boundary at some
957    /// character index, and hands the delta back through
958    /// `position(from:offset:)`, which hops stops again. If the text ever
959    /// spends a character on something that is not a stop, or a stop on
960    /// nothing, every index past that point is off by one and the word the
961    /// reader double-tapped comes back shifted — into the header row of a
962    /// table, or one letter short. So a stop that draws a glyph is spelled
963    /// as that glyph, and a stop that draws none is spelled `'\n'`:
964    ///
965    /// - a row's own end stop ([`VRow::end_src`]) — the caret home past a
966    ///   paragraph's, heading's, list item's, or code line's last glyph. This
967    ///   is also what keeps two blocks' words apart: without it the last word
968    ///   of one paragraph and the first of the next read as one run of
969    ///   letters (`"…edb\n\nhello\n"` came back as `"edbhello"`), and the
970    ///   tokenizer selected across the boundary. A list item's end is a
971    ///   row end like any other, though no blank gap row follows it.
972    /// - a table cell's end, which [`push_table_row`] draws as the gutter
973    ///   space before the next `│` so the caret has somewhere to stand past
974    ///   the cell's last character. To a reader of *this* text a cell ends a
975    ///   line: spelled as a space, a touch surface that lands a tap at a
976    ///   word's end past the space that follows it stepped into the next
977    ///   cell — or the next row, from the last column.
978    ///
979    /// A hidden mark's content end ([`mark_ends`](Self::mark_ends)) is a place
980    /// the caret rests but not a stop the walks above count, so it has no
981    /// character here either; `from` is snapped to the glyph stop drawn at
982    /// the same spot first, exactly as [`snap_to_glyph_stop`] does for those
983    /// walks. `to` is left as given, so a stop landing exactly on it is still
984    /// excluded — the same half-open range `distance_offset`'s loop counts.
985    ///
986    /// [`push_table_row`]: Builder::push_table_row
987    /// [`snap_to_glyph_stop`]: Self::snap_to_glyph_stop
988    pub fn visible_text(&self, from: usize, to: usize) -> String {
989        self.visible_items(from, to)
990            .into_iter()
991            .map(|(_, ch)| ch.unwrap_or('\n'))
992            .collect()
993    }
994
995    /// The UTF-16 length of `visible_text(from, to)` — what an `NSRange`
996    /// location into that text is, without building the string.
997    ///
998    /// AppKit's `NSTextInputClient` and `NSAccessibility` speak in UTF-16
999    /// units of *the text as the system sees it*, which for leaf is the visible
1000    /// text — delimiters hidden. A frontend reporting its selection to the
1001    /// system converts each end with this and gets back an index into the
1002    /// string `visible_text(0, end)` returns, which is exactly what the system
1003    /// will index into.
1004    pub fn visible_utf16_len(&self, from: usize, to: usize) -> usize {
1005        self.visible_items(from, to)
1006            .into_iter()
1007            .map(|(_, ch)| ch.map_or(1, char::len_utf16))
1008            .sum()
1009    }
1010
1011    /// The inverse of `visible_utf16_len(0, ·)`: the source offset of the
1012    /// visible character a UTF-16 index into `visible_text(0, to)` lands on.
1013    ///
1014    /// An index inside a surrogate pair resolves to the character that owns
1015    /// it; one at or past the end of the text returns `None`, so a caller can
1016    /// substitute the document's end stop. The `\n` a row's or a cell's end
1017    /// is spelled with resolves to that end stop — a caret home, so a caller
1018    /// placing a caret there needs no snap.
1019    pub fn offset_at_visible_utf16(&self, to: usize, index: usize) -> Option<usize> {
1020        let mut seen = 0usize;
1021        for (src, ch) in self.visible_items(0, to) {
1022            let len = ch.map_or(1, char::len_utf16);
1023            if index < seen + len {
1024                return Some(src);
1025            }
1026            seen += len;
1027        }
1028        None
1029    }
1030
1031    /// The items `visible_text` spells, in order — one per caret stop in
1032    /// `[from, to)`, keyed by the stop's source offset: the glyph it draws
1033    /// (`Some`), or `None` for a stop with no character of its own, which the
1034    /// text spells `'\n'`. See [`visible_text`](Self::visible_text) for which
1035    /// stops those are and why.
1036    fn visible_items(&self, from: usize, to: usize) -> Vec<(usize, Option<char>)> {
1037        let from = self.snap_to_glyph_stop(from);
1038        let lo = self.stops.partition_point(|&s| s < from);
1039        // The document's last stop is the end of the text, not a character in
1040        // it: `distance_offset` has no hop past it to pair one with.
1041        let last = self.stops.len().saturating_sub(1);
1042        let hi = self.stops.partition_point(|&s| s < to).min(last).max(lo);
1043        let stops = &self.stops[lo..hi];
1044
1045        // The glyph each stop draws — the first at its offset in row order,
1046        // since a media row's label glyphs all share the media's offset and a
1047        // wrapped line's end is the next line's first glyph. Sorted because
1048        // row order only follows source order outside a table's wrapped
1049        // cells (see `pos_of_offset`); the sort is stable, so "first" holds.
1050        let mut glyphs: Vec<(usize, char)> = self
1051            .rows
1052            .iter()
1053            .filter(|r| !r.decoration)
1054            .flat_map(|r| r.glyphs.iter())
1055            .filter(|g| g.stop && g.src >= from && g.src < to)
1056            .map(|g| (g.src, g.ch))
1057            .collect();
1058        glyphs.sort_by_key(|&(src, _)| src);
1059        glyphs.dedup_by_key(|&mut (src, _)| src);
1060
1061        // A cell's end stop has a glyph (the gutter space) but is spelled as
1062        // a line end; the structural grid is where the cells' offsets live.
1063        let mut cell_ends: Vec<usize> = self
1064            .tables
1065            .iter()
1066            .flat_map(|t| t.grid.iter())
1067            .flat_map(|r| r.cells.iter())
1068            .map(|c| c.end)
1069            .filter(|&e| e >= from && e < to)
1070            .collect();
1071        cell_ends.sort_unstable();
1072        cell_ends.dedup();
1073
1074        let mut gi = 0;
1075        stops
1076            .iter()
1077            .map(|&s| {
1078                while gi < glyphs.len() && glyphs[gi].0 < s {
1079                    gi += 1;
1080                }
1081                let ch = match glyphs.get(gi) {
1082                    Some(&(src, ch)) if src == s && cell_ends.binary_search(&s).is_err() => {
1083                        Some(ch)
1084                    }
1085                    _ => None,
1086                };
1087                (s, ch)
1088            })
1089            .collect()
1090    }
1091}
1092
1093/// Collect the caret stops of a laid-out grid: every stop glyph's offset plus
1094/// every row's end, ascending and deduplicated. Duplicates are the norm rather
1095/// than the exception — a wrapped line's end is the same offset as the next
1096/// line's first glyph — and collapsing them is what makes one press of Left or
1097/// Right cross exactly one stop.
1098fn collect_stops(rows: &[VRow]) -> Vec<usize> {
1099    let mut stops: Vec<usize> = rows
1100        .iter()
1101        .filter(|r| !r.decoration)
1102        .flat_map(|r| {
1103            r.glyphs
1104                .iter()
1105                .filter(|g| g.stop)
1106                .map(|g| g.src)
1107                .chain(std::iter::once(r.end_src))
1108        })
1109        .collect();
1110    stops.sort_unstable();
1111    stops.dedup();
1112    stops
1113}
1114
1115/// Collect every row's [`VRow::mark_ends`] into one ascending, deduplicated
1116/// table — the peer of [`collect_stops`] for the caret's second home at the
1117/// end of a hidden mark. A mark that closes at a row's end coincides with the
1118/// row's own end stop; that offset is in both tables, and harmlessly so.
1119fn collect_mark_ends(rows: &[VRow]) -> Vec<usize> {
1120    let mut ends: Vec<usize> = rows
1121        .iter()
1122        .filter(|r| !r.decoration)
1123        .flat_map(|r| r.mark_ends.iter().copied())
1124        .collect();
1125    ends.sort_unstable();
1126    ends.dedup();
1127    ends
1128}
1129
1130/// Group the rows tagged [`VRow::code`] into one [`CodeBlockInfo`] per maximal
1131/// run — the block-level view a frontend needs to box and scroll each code
1132/// block. Two code blocks are always parted by the blank separator row a block
1133/// boundary is spelled with (never itself a code row), so a contiguous run is
1134/// exactly one block. Derived from the final rows rather than tracked through
1135/// the builder so it comes out right no matter how [`build_cached`] and
1136/// [`build_spliced`] shuffle rows around.
1137fn code_block_spans(rows: &[VRow]) -> Vec<CodeBlockInfo> {
1138    let mut blocks = Vec::new();
1139    let mut start: Option<usize> = None;
1140    for (i, row) in rows.iter().enumerate() {
1141        match (row.code, start) {
1142            (true, None) => start = Some(i),
1143            (false, Some(s)) => {
1144                blocks.push(CodeBlockInfo {
1145                    rows_span: s..i,
1146                    lang: rows[s].code_lang.clone(),
1147                });
1148                start = None;
1149            }
1150            _ => {}
1151        }
1152    }
1153    if let Some(s) = start {
1154        blocks.push(CodeBlockInfo {
1155            rows_span: s..rows.len(),
1156            lang: rows[s].code_lang.clone(),
1157        });
1158    }
1159    blocks
1160}
1161
1162/// The value of `node`'s `key` attribute, if it carries one *with* a value. A
1163/// bare attribute (`controls`, `muted`) has a `None` value and so reads as
1164/// absent here — a caller wanting presence-not-value tests the list directly.
1165/// Shared by the media element and `<source>` readers.
1166fn attr_of(node: &FlatNode, key: &str) -> Option<String> {
1167    node.attrs
1168        .iter()
1169        .find(|(k, _)| k == key)
1170        .and_then(|(_, v)| v.clone())
1171}
1172
1173/// Collect one [`MediaInfo`] per row carrying a [`VRow::media`] mark — the
1174/// block-level view a frontend needs to replace each placeholder row with a real
1175/// picture. The mark rides the block's *first* row and names how many rows the
1176/// media reserves ([`MediaMark::rows`]); the rows below it are blank
1177/// [`decoration`](VRow::decoration) fillers that hold the vertical space and no
1178/// caret. So the span runs from the marked row across those fillers. Derived from
1179/// the final rows rather than tracked through the builder so it survives however
1180/// [`build_cached`] and [`build_spliced`] shuffle rows around.
1181fn media_spans(rows: &[VRow]) -> Vec<MediaInfo> {
1182    rows.iter()
1183        .enumerate()
1184        .filter_map(|(i, row)| {
1185            row.media.as_ref().map(|m| MediaInfo {
1186                rows_span: i..i + m.rows.max(1),
1187                kind: m.kind,
1188                destination: m.destination.clone(),
1189                sources: m.sources.clone(),
1190                alt: m.alt.clone(),
1191                poster: m.poster.clone(),
1192            })
1193        })
1194        .collect()
1195}
1196
1197/// Re-label the drawn block boundaries either side of a block-level media
1198/// placeholder, so the pair a frontend spaces by names the picture.
1199///
1200/// [`BlockClass::from_node_kind`] classifies the node the walk is standing on,
1201/// and a block image is never a node of its own: [`Builder::media_only`] promotes
1202/// its *wrapper* — a `paragraph`, or the `container` a `<video>`/`<audio>`
1203/// arrives as — so the gap above a picture reported [`BlockClass::Paragraph`] and
1204/// the gap above a movie reported [`BlockClass::Directive`], the class a frontend
1205/// paints a tinted panel for. [`BlockClass::Media`] was unreachable in
1206/// consequence: the vocabulary named a kind no frontend could ever be told about.
1207///
1208/// Done as a pass over the finished rows rather than inside the walk because
1209/// only the rows know. The incremental top-level walk carries no node arena at
1210/// all (`nodes: &[]`) and can classify by kind alone, so teaching the wrapper
1211/// promotion to the whole-arena walk would label the full and incremental builds
1212/// differently — the exact drift that walk's own comment forbids. Both builds
1213/// emit the same [`VRow::media`] marks, so both reach the same answer here. The
1214/// [`media_spans`] / [`code_block_spans`] pattern.
1215///
1216/// One gap can be spelled with several rows — [`Builder::emit_separators_before`]
1217/// draws the row that closes the block above and the row that opens the block
1218/// below, with any extra blank source lines navigable between them — and gives
1219/// every one of them the same [`Boundary`]. So the walk crosses those navigable
1220/// blanks and relabels the whole run, stopping at the first row that is neither.
1221fn label_media_boundaries(rows: &mut [VRow]) {
1222    let spans: Vec<Range<usize>> = rows
1223        .iter()
1224        .enumerate()
1225        .filter_map(|(i, row)| row.media.as_ref().map(|m| i..i + m.rows.max(1)))
1226        .collect();
1227    // A row inside one gap: a drawn boundary to relabel, or one of the navigable
1228    // blank lines sitting between two drawn ones. Anything else ends the run.
1229    fn in_gap(row: &VRow) -> bool {
1230        row.boundary.is_some() || (!row.decoration && row.glyphs.is_empty())
1231    }
1232    for span in spans {
1233        for i in (0..span.start).rev() {
1234            if !in_gap(&rows[i]) {
1235                break;
1236            }
1237            if let Some(b) = rows[i].boundary.as_mut() {
1238                b.below = BlockClass::Media;
1239            }
1240        }
1241        for row in rows.iter_mut().skip(span.end) {
1242            if !in_gap(row) {
1243                break;
1244            }
1245            if let Some(b) = row.boundary.as_mut() {
1246                b.above = BlockClass::Media;
1247            }
1248        }
1249    }
1250}
1251
1252/// Collect one [`DirectiveInfo`] per row carrying a [`VRow::leaf_directive`]
1253/// mark — the block-level view a frontend needs to replace each placeholder row
1254/// with whatever the directive means to it. The peer of [`media_spans`], derived
1255/// from the final rows for the same reason: it survives however [`build_cached`]
1256/// and [`build_spliced`] shuffle rows around.
1257fn directive_spans(rows: &[VRow]) -> Vec<DirectiveInfo> {
1258    rows.iter()
1259        .enumerate()
1260        .filter_map(|(i, row)| {
1261            row.leaf_directive.as_ref().map(|m| DirectiveInfo {
1262                rows_span: i..i + m.rows.max(1),
1263                name: m.name.clone(),
1264                attrs: m.attrs.clone(),
1265                label: m.label.clone(),
1266            })
1267        })
1268        .collect()
1269}
1270
1271/// The source range of a fenced code block's info string — everything on the
1272/// opening line past the fence (`` ```rust `` → the `rust`). `block_start` is the
1273/// code block node's `span.start`. `None` for an indented code block, which
1274/// opens with no fence to carry one. The range is empty for a fence written
1275/// bare (`` ``` `` alone), which is exactly where a language would be inserted.
1276///
1277/// Shared by the WYSIWYG builder (to label the box) and [`crate::Doc`] (to edit
1278/// the label through a prompt), so the two agree on where the language lives.
1279pub fn code_info_span(source: &str, block_start: usize) -> Option<Range<usize>> {
1280    let rest = source.get(block_start..)?;
1281    let line_len = rest.find('\n').unwrap_or(rest.len());
1282    let line = &rest[..line_len];
1283    // A fence may be indented up to three spaces; past that it opens with a run
1284    // of the same fence character.
1285    let indent = line.len() - line.trim_start().len();
1286    if indent > 3 {
1287        return None;
1288    }
1289    let fence = line[indent..].chars().next()?;
1290    if fence != '`' && fence != '~' {
1291        return None; // an indented block, not a fenced one
1292    }
1293    let fence_len = line[indent..].chars().take_while(|&c| c == fence).count();
1294    let info_start = block_start + indent + fence_len;
1295    Some(info_start..block_start + line_len)
1296}
1297
1298/// A fenced code block's language for display: its info string, trimmed, or
1299/// `None` when there's no fence or the fence carries no language. The trimmed
1300/// text is what a frontend labels the box with; [`code_info_span`] is what an
1301/// edit replaces.
1302pub fn code_language(source: &str, block_start: usize) -> Option<String> {
1303    let span = code_info_span(source, block_start)?;
1304    let text = source.get(span)?.trim();
1305    (!text.is_empty()).then(|| text.to_string())
1306}
1307
1308/// A horizontal rule's dash count when the map isn't wrapping to a column grid
1309/// (the GUI, which wraps at pixel width): a fixed, sane width the frontend can
1310/// paint or re-wrap, instead of a runaway count from an unbounded wrap width.
1311const UNWRAPPED_RULE_WIDTH: usize = 40;
1312
1313/// Render the document to a [`VisualMap`]. `wrap` is the column budget for
1314/// word-wrapping (`Some` for the monospace TUI), or `None` to emit one row per
1315/// block — the GUI does its own proportional pixel wrapping over these rows.
1316/// Text and offsets come from the AST (`str` nodes carry the verbatim source
1317/// slice and an exact span), so the original source string isn't needed here.
1318pub fn build(
1319    nodes: &[FlatNode],
1320    source: &str,
1321    wrap: Option<usize>,
1322    preserve_soft: bool,
1323    media_rows: &HashMap<String, usize>,
1324    reveal: Option<Range<usize>>,
1325) -> VisualMap {
1326    let Some(doc) = nodes.iter().position(|n| n.kind == Kind::Doc) else {
1327        return VisualMap::default();
1328    };
1329    let top = top_level(nodes, doc);
1330    let mut b = Builder {
1331        nodes,
1332        source,
1333        wrap: wrap.map(|w| w.max(8)),
1334        rows: Vec::new(),
1335        tables: Vec::new(),
1336        last_off: 0,
1337        stepped_over: 0,
1338        media_rows,
1339        break_glyph: Cell::new(' '),
1340        preserve_soft,
1341        reveal: reveal.clone(),
1342        pending_mark_ends: RefCell::new(Vec::new()),
1343        presentation: Presentation::default(),
1344    };
1345    let last_drawn = b.top_blocks(&top);
1346    // The hidden frontmatter's end is the baseline for both the trailing blank
1347    // rows and the caret floor — see [`hidden_prefix_end`]. `top_level` has
1348    // already dropped every `metadata` child, so read it off the arena.
1349    let hidden_end = hidden_prefix_end(source, metadata_end_of(nodes, doc));
1350    b.emit_trailing_blank_lines(last_drawn.unwrap_or(BlockClass::Paragraph), hidden_end);
1351    let content_start = top.first().map_or(hidden_end, |&i| nodes[i].span.start);
1352    let stops = collect_stops(&b.rows);
1353    let mark_ends = collect_mark_ends(&b.rows);
1354    label_media_boundaries(&mut b.rows);
1355    let code_blocks = code_block_spans(&b.rows);
1356    let media = media_spans(&b.rows);
1357    let directives = directive_spans(&b.rows);
1358    VisualMap {
1359        rows: b.rows,
1360        content_start,
1361        stops,
1362        mark_ends,
1363        tables: b.tables,
1364        code_blocks,
1365        media,
1366        directives,
1367    }
1368}
1369
1370/// Like [`build`], but reuses a persistent [`BlockCache`] so an edit re-renders
1371/// only the top-level blocks whose source bytes changed *and* marshals only
1372/// those blocks from twig instead of the whole arena.
1373///
1374/// `top` is the document's top-level blocks — twig's `child_spans` of the doc
1375/// root: `(node_id, kind, span)` for each, in order. `fetch_subtree(node_id)`
1376/// marshals one block's subtree (local-indexed, root at 0) and is called *only*
1377/// for a block that missed the cache, i.e. one that actually changed. So a
1378/// keystroke marshals one small subtree, not ~20k nodes. The result is
1379/// byte-for-byte identical to [`build`] on the same document (the
1380/// `build_cached_matches_build` test pins this); [`build`] stays the cache-free,
1381/// whole-arena reference. This is the entry point [`crate::Doc`] uses.
1382// One builder, and every one of these is a distinct input to the same layout
1383// pass — a struct of them would be built at the one call site and unpacked
1384// here, which is the same arguments with an extra name in the way.
1385#[allow(clippy::too_many_arguments)]
1386pub fn build_cached(
1387    top: &[QueryMatch],
1388    source: &str,
1389    wrap: Option<usize>,
1390    preserve_soft: bool,
1391    media_rows: &HashMap<String, usize>,
1392    reveal: Option<Range<usize>>,
1393    cache: &mut BlockCache,
1394    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
1395) -> VisualMap {
1396    let wrap = wrap.map(|w| w.max(8));
1397
1398    // Wrapping is a function of the width, so a width change makes every cached
1399    // row's wrap wrong: start the cache over.
1400    if cache.wrap != Some(wrap) {
1401        cache.entries.clear();
1402        cache.wrap = Some(wrap);
1403    }
1404    cache.generation = cache.generation.wrapping_add(1);
1405
1406    // Frontmatter (a leading `metadata` block) is document metadata, not prose:
1407    // hidden in the rich view exactly as [`Builder::blocks`] skips it.
1408    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
1409
1410    // The outer builder only accumulates rows/tables and spells block boundaries
1411    // — both a function of the source and `last_off`, never of a node array — so
1412    // it carries an empty `nodes`. Each changed block is rendered by a *fresh*
1413    // builder over that block's subtree.
1414    let mut b = Builder {
1415        nodes: &[],
1416        source,
1417        wrap,
1418        rows: Vec::new(),
1419        tables: Vec::new(),
1420        last_off: 0,
1421        stepped_over: 0,
1422        media_rows,
1423        break_glyph: Cell::new(' '),
1424        preserve_soft,
1425        reveal: reveal.clone(),
1426        pending_mark_ends: RefCell::new(Vec::new()),
1427        presentation: Presentation::default(),
1428    };
1429
1430    // Record the per-block row decomposition as we go, so a later
1431    // [`build_spliced`] can patch one block without rebuilding the map.
1432    let mut layout_blocks: Vec<BlockLayout> = Vec::with_capacity(blocks.len());
1433    let mut all_shift_safe = true;
1434    // The class of the last block that drew anything: what the next separator
1435    // closes, and what the trailing blank lines close at the end. A hidden block
1436    // (a comment) never becomes it — see [`Builder::block_or_hidden`], whose
1437    // step-over this loop repeats for the incremental walk.
1438    let mut above: Option<BlockClass> = None;
1439    for block in &blocks {
1440        let start = block.span.start;
1441        let before_sep = b.rows.len();
1442        if let Some(above) = above {
1443            // This walker has no node arena at all (see the `nodes: &[]` above),
1444            // but a top-level query match carries its kind — the same string
1445            // `BlockClass::from_node_kind` classifies for the whole-arena walk, so
1446            // the incremental and full builds label a boundary identically.
1447            b.emit_separators_before(
1448                start,
1449                &[],
1450                true,
1451                Boundary {
1452                    above,
1453                    below: BlockClass::from_node_kind(&block.kind),
1454                },
1455            );
1456        }
1457        let after_sep = b.rows.len();
1458        let bytes = block_bytes(source, &block.span);
1459        let hash = block_hash(bytes);
1460        // How this block meets the reveal line, if at all — part of its cache
1461        // key, since the same bytes render differently on the caret's line.
1462        let rkey = reveal_key(&reveal, &block.span);
1463
1464        // Hit: clone the block's rows shifted to its current offset and restore
1465        // the (shifted) `last_off` so the next separator lands right — no marshal.
1466        // Only shift-safe blocks are ever cached, so a hit is safe by construction.
1467        if let Some(hit) = cache.reuse(hash, bytes, &rkey) {
1468            let delta = start as isize - hit.built_start as isize;
1469            for row in &hit.rows {
1470                b.rows.push(shift_row(row, delta));
1471            }
1472            b.last_off = (hit.last_off as isize + delta) as usize;
1473        } else {
1474            // Miss: marshal just this block's subtree and render it. A subtree is
1475            // self-contained with local ids (root at 0) and absolute spans, so a
1476            // fresh builder over it produces the same rows the whole-arena path
1477            // would. An empty subtree (twig couldn't hand it back) renders nothing.
1478            let subtree = fetch_subtree(block.node_id);
1479            if !subtree.is_empty() {
1480                let mut sub = Builder {
1481                    nodes: &subtree,
1482                    source,
1483                    wrap,
1484                    rows: Vec::new(),
1485                    tables: Vec::new(),
1486                    last_off: 0,
1487                    stepped_over: 0,
1488                    media_rows,
1489                    break_glyph: Cell::new(' '),
1490                    preserve_soft,
1491                    reveal: reveal.clone(),
1492                    pending_mark_ends: RefCell::new(Vec::new()),
1493                    presentation: Presentation::default(),
1494                };
1495                sub.block(0, &[], &[]);
1496                // A block that drew nothing is stepped over, not stood on: its
1497                // `last_off` is its own end, so the separator after it counts
1498                // from there. The sub-builder started at 0 and never moved, and
1499                // 0 is where the next separator would otherwise count from —
1500                // every line of the document, as a blank row each.
1501                let last_off = if sub.rows.is_empty() {
1502                    block.span.end
1503                } else {
1504                    sub.last_off
1505                };
1506                // Cache only a block that is table-free AND renders inside its own
1507                // span: those two are the conditions for reuse-by-shift to be
1508                // correct. A block failing either is re-rendered every build (a
1509                // fresh render always matches a fresh whole-document build).
1510                if sub.tables.is_empty() {
1511                    if rows_within(&sub.rows, &block.span) {
1512                        cache.store(hash, bytes, start, sub.rows.clone(), last_off, rkey);
1513                    }
1514                    b.rows.extend(sub.rows);
1515                } else {
1516                    // A table block is never cached; rebase its row-index
1517                    // bookkeeping onto the combined row vector and append.
1518                    let base = b.rows.len();
1519                    for t in &mut sub.tables {
1520                        t.rows_span = (t.rows_span.start + base)..(t.rows_span.end + base);
1521                    }
1522                    b.rows.extend(sub.rows);
1523                    b.tables.extend(sub.tables);
1524                }
1525                b.last_off = last_off;
1526            }
1527        }
1528        let content_rows = b.rows.len() - after_sep;
1529        let sep_rows = if content_rows == 0 {
1530            // Hidden: take back the separator drawn for it, so what stands
1531            // either side meets across one boundary. Its layout entry stays, at
1532            // no rows, so the splice arithmetic still counts one entry per block.
1533            b.rows.truncate(before_sep);
1534            // A cache hit restored the stored `last_off` above; an empty subtree
1535            // (twig couldn't hand it back) restored nothing. Either way the walk
1536            // stands past the block.
1537            b.last_off = b.last_off.max(block.span.end);
1538            b.stepped_over = b.stepped_over.max(block.span.end);
1539            0
1540        } else {
1541            above = Some(BlockClass::from_node_kind(&block.kind));
1542            all_shift_safe &= rows_within(&b.rows[after_sep..], &block.span);
1543            after_sep - before_sep
1544        };
1545        layout_blocks.push(BlockLayout {
1546            span: block.span.clone(),
1547            kind: block.kind.clone(),
1548            sep_rows,
1549            content_rows,
1550        });
1551    }
1552
1553    let before_trailing = b.rows.len();
1554    let hidden_end = hidden_prefix_end(
1555        source,
1556        top.iter()
1557            .filter(|m| m.kind == Kind::Metadata)
1558            .map(|m| m.span.end)
1559            .next_back(),
1560    );
1561    b.emit_trailing_blank_lines(above.unwrap_or(BlockClass::Paragraph), hidden_end);
1562    let trailing_rows = b.rows.len() - before_trailing;
1563
1564    // Evict every entry no block reused this build, so the cache tracks the
1565    // current document instead of growing without bound over a session.
1566    let g = cache.generation;
1567    cache.entries.retain(|_, bucket| {
1568        bucket.retain(|e| e.generation == g);
1569        !bucket.is_empty()
1570    });
1571
1572    cache.layout = Layout {
1573        blocks: layout_blocks,
1574        trailing_rows,
1575        built_len: source.len(),
1576        has_tables: !b.tables.is_empty(),
1577        all_shift_safe,
1578        reveal: reveal.clone(),
1579    };
1580
1581    // The first rendered offset is the first non-metadata block's start — the
1582    // analogue of [`first_content_offset`] for the top-level list. With nothing
1583    // but frontmatter it's the end of that frontmatter, and 0 for an empty
1584    // document ([`hidden_prefix_end`]).
1585    let content_start = blocks.first().map_or(hidden_end, |m| m.span.start);
1586    let stops = collect_stops(&b.rows);
1587    let mark_ends = collect_mark_ends(&b.rows);
1588    label_media_boundaries(&mut b.rows);
1589    let code_blocks = code_block_spans(&b.rows);
1590    let media = media_spans(&b.rows);
1591    let directives = directive_spans(&b.rows);
1592    VisualMap {
1593        rows: b.rows,
1594        content_start,
1595        stops,
1596        mark_ends,
1597        tables: b.tables,
1598        code_blocks,
1599        media,
1600        directives,
1601    }
1602}
1603
1604/// The fast path for a single-block edit: patch the previous [`VisualMap`] in
1605/// place rather than reassembling it. Returns `Some(new_map)` when it applies,
1606/// or `None` to tell the caller to fall back to [`build_cached`] (always
1607/// correct). Consumes `prev` either way — on `None` the caller rebuilds from
1608/// scratch and doesn't need it.
1609///
1610/// It applies only when `dirty` (twig's dirty byte range) falls inside exactly
1611/// one top-level block AND the block structure around it is unchanged — verified
1612/// by matching the new `top` list against the previous [`Layout`] block for
1613/// block: kinds unchanged, spans before the edit identical, spans after it
1614/// shifted by the byte delta, count unchanged. Any deviation — a block split or
1615/// merged, a fence opened to swallow later blocks, a table anywhere, a
1616/// multi-block edit — fails the match and returns `None`. That check is what
1617/// makes the byte-range trustworthy: twig's dirty range is exact about *bytes*
1618/// but silent about *reparse*, and the structural match catches the reparse
1619/// effects it can't see.
1620///
1621/// When it applies, the unchanged prefix rows move verbatim, the suffix rows
1622/// shift by the delta *in place* (integer adds, no glyph copy), and only the one
1623/// dirty block is re-marshalled and re-rendered; stops splice the same way by
1624/// offset. So the cost is O(rows after the edit), and nothing before the edit is
1625/// touched. The hash-keyed entry cache is left alone — a later [`build_cached`]
1626/// will miss on the changed block, re-render it, and evict the stale entry, so
1627/// chained splices neither corrupt nor grow it.
1628// One builder, and every one of these is a distinct input to the same layout
1629// pass — a struct of them would be built at the one call site and unpacked
1630// here, which is the same arguments with an extra name in the way.
1631#[allow(clippy::too_many_arguments)]
1632pub fn build_spliced(
1633    prev: VisualMap,
1634    source: &str,
1635    wrap: Option<usize>,
1636    preserve_soft: bool,
1637    top: &[QueryMatch],
1638    dirty: Range<usize>,
1639    media_rows: &HashMap<String, usize>,
1640    reveal: Option<Range<usize>>,
1641    cache: &mut BlockCache,
1642    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
1643) -> Option<VisualMap> {
1644    let wrap = wrap.map(|w| w.max(8));
1645    // A width change invalidates every cached row — a full rebuild's job.
1646    if cache.wrap != Some(wrap) {
1647        return None;
1648    }
1649    // So does a moved reveal line, and for the same reason: this path reuses
1650    // every row outside the dirty block, and those rows encode which line was
1651    // showing its raw markup when they were built. Typing almost always moves
1652    // the caret, so under `MarkupMode::Full` this bails to `build_cached` on
1653    // most keystrokes — still block-cached, so only the edited block and the
1654    // revealed one actually re-render.
1655    if cache.layout.reveal != reveal {
1656        return None;
1657    }
1658    // Take the previous layout; on any bail below the caller rebuilds it (and the
1659    // map) via `build_cached`, so leaving it empty is fine. A table or a block
1660    // that renders outside its span (a degenerate inline span) makes shifting
1661    // unsound, so those force the full-rebuild path.
1662    let prev_layout = std::mem::take(&mut cache.layout);
1663    if prev_layout.built_len == 0 || prev_layout.has_tables || !prev_layout.all_shift_safe {
1664        return None;
1665    }
1666    // The layout addresses `prev` by row index, so it is only usable against the
1667    // map it was built from. A frontend is free to hold the map it was handed and
1668    // present it differently — leaf-ratatui splices blank filler rows under an
1669    // oversized heading so the raster has somewhere to stand — and if one of those
1670    // comes back here the row arithmetic below lands on the wrong rows: the
1671    // re-rendered block is laid over a filler and the rows it really occupied
1672    // survive into the suffix, stranding a stale copy of the edited line and
1673    // pushing everything after it one row down, once per keystroke. A row count
1674    // that doesn't match what this layout describes is the tell, and the honest
1675    // answer is the full rebuild.
1676    let described_rows = prev_layout
1677        .blocks
1678        .iter()
1679        .map(|pl| pl.sep_rows + pl.content_rows)
1680        .sum::<usize>()
1681        + prev_layout.trailing_rows;
1682    if described_rows != prev.rows.len() {
1683        return None;
1684    }
1685
1686    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
1687    if blocks.is_empty() || blocks.len() != prev_layout.blocks.len() {
1688        return None;
1689    }
1690    let delta = source.len() as isize - prev_layout.built_len as isize;
1691
1692    // The single block whose NEW span contains the whole dirty range. A dirty
1693    // range straddling a block boundary (or a separator) finds none → bail.
1694    let k = blocks
1695        .iter()
1696        .position(|m| m.span.start <= dirty.start && dirty.end <= m.span.end)?;
1697
1698    // Structural match: every OTHER block is unchanged — same kind throughout,
1699    // span identical before the edit and shifted by `delta` after it. A mismatch
1700    // means the reparse reshaped the block structure, which only a full rebuild
1701    // renders correctly.
1702    for (i, (m, pl)) in blocks.iter().zip(&prev_layout.blocks).enumerate() {
1703        if m.kind != pl.kind {
1704            return None;
1705        }
1706        if i == k {
1707            continue;
1708        }
1709        let want = if i < k {
1710            pl.span.clone()
1711        } else {
1712            (pl.span.start as isize + delta) as usize..(pl.span.end as isize + delta) as usize
1713        };
1714        if m.span != want {
1715            return None;
1716        }
1717    }
1718    // The dirty block itself: start unchanged (the edit is inside it, past its
1719    // start), end moved by exactly the delta.
1720    let pk_start = prev_layout.blocks[k].span.start;
1721    let pk_end = prev_layout.blocks[k].span.end;
1722    let pk_sep = prev_layout.blocks[k].sep_rows;
1723    let pk_content = prev_layout.blocks[k].content_rows;
1724    if blocks[k].span.start != pk_start || blocks[k].span.end != (pk_end as isize + delta) as usize
1725    {
1726        return None;
1727    }
1728
1729    // Re-render the dirty block from its subtree. A table makes the splice
1730    // bookkeeping unsafe, so bail if one appears.
1731    let subtree = fetch_subtree(blocks[k].node_id);
1732    if subtree.is_empty() {
1733        return None;
1734    }
1735    let mut sub = Builder {
1736        nodes: &subtree,
1737        source,
1738        wrap,
1739        rows: Vec::new(),
1740        tables: Vec::new(),
1741        last_off: 0,
1742        stepped_over: 0,
1743        media_rows,
1744        break_glyph: Cell::new(' '),
1745        preserve_soft,
1746        reveal: reveal.clone(),
1747        pending_mark_ends: RefCell::new(Vec::new()),
1748        presentation: Presentation::default(),
1749    };
1750    sub.block(0, &[], &[]);
1751    // A table, or content that renders outside the block's span (a degenerate
1752    // inline span), makes the shift bookkeeping unsound — fall back.
1753    if !sub.tables.is_empty() || !rows_within(&sub.rows, &blocks[k].span) {
1754        return None;
1755    }
1756    let new_content = sub.rows;
1757    let new_content_len = new_content.len();
1758    let new_stops = collect_stops(&new_content);
1759    let new_mark_ends = collect_mark_ends(&new_content);
1760
1761    // Row span of the dirty block's CONTENT. Its leading separator stays in the
1762    // prefix: the gap before block k is unchanged, since k's start didn't move.
1763    let content_start_row: usize = prev_layout.blocks[..k]
1764        .iter()
1765        .map(|pl| pl.sep_rows + pl.content_rows)
1766        .sum::<usize>()
1767        + pk_sep;
1768    let content_end_row = content_start_row + pk_content;
1769
1770    // Splice rows: [prefix | new content | suffix + delta]. The prefix moves
1771    // untouched; the suffix shifts in place — integer adds, no glyph copy.
1772    let mut rows = prev.rows;
1773    let mut suffix = rows.split_off(content_end_row);
1774    rows.truncate(content_start_row);
1775    for row in &mut suffix {
1776        shift_row_in_place(row, delta);
1777    }
1778    rows.reserve(new_content_len + suffix.len());
1779    rows.extend(new_content);
1780    rows.extend(suffix);
1781
1782    // Splice stops by offset. The old dirty block covered `[pk_start, pk_end]`:
1783    // prefix stops fall below it, suffix stops above it (shift by delta), the new
1784    // content supplies the middle. The three ranges stay disjoint and ascending,
1785    // so the result needs no re-sort.
1786    let p1 = prev.stops.partition_point(|&s| s < pk_start);
1787    let p2 = prev.stops.partition_point(|&s| s <= pk_end);
1788    let mut stops = Vec::with_capacity(p1 + new_stops.len() + (prev.stops.len() - p2));
1789    stops.extend_from_slice(&prev.stops[..p1]);
1790    stops.extend(new_stops);
1791    for &s in &prev.stops[p2..] {
1792        stops.push((s as isize + delta) as usize);
1793    }
1794    // The mark ends splice the same way: they are offsets in the same
1795    // coordinates, cut at the same block.
1796    let m1 = prev.mark_ends.partition_point(|&s| s < pk_start);
1797    let m2 = prev.mark_ends.partition_point(|&s| s <= pk_end);
1798    let mut mark_ends = Vec::with_capacity(m1 + new_mark_ends.len() + (prev.mark_ends.len() - m2));
1799    mark_ends.extend_from_slice(&prev.mark_ends[..m1]);
1800    mark_ends.extend(new_mark_ends);
1801    for &s in &prev.mark_ends[m2..] {
1802        mark_ends.push((s as isize + delta) as usize);
1803    }
1804
1805    // Record the patched layout for the next splice: spans move to the new
1806    // coordinates, and the dirty block takes its new content-row count.
1807    let mut new_blocks = prev_layout.blocks;
1808    for (pl, m) in new_blocks.iter_mut().zip(&blocks) {
1809        pl.span = m.span.clone();
1810    }
1811    new_blocks[k].content_rows = new_content_len;
1812    cache.layout = Layout {
1813        blocks: new_blocks,
1814        trailing_rows: prev_layout.trailing_rows,
1815        built_len: source.len(),
1816        has_tables: false,
1817        // Every prefix/suffix block was shift-safe last build (we bailed
1818        // otherwise) and the re-rendered block was just checked, so the patched
1819        // document is still entirely shift-safe.
1820        all_shift_safe: true,
1821        reveal,
1822    };
1823
1824    label_media_boundaries(&mut rows);
1825    let code_blocks = code_block_spans(&rows);
1826    let media = media_spans(&rows);
1827    let directives = directive_spans(&rows);
1828    Some(VisualMap {
1829        rows,
1830        content_start: blocks[0].span.start,
1831        stops,
1832        mark_ends,
1833        tables: Vec::new(),
1834        code_blocks,
1835        media,
1836        directives,
1837    })
1838}
1839
1840/// A persistent, content-keyed cache of the rows each top-level block renders
1841/// to — the [`VisualMap`] analogue of the GUI's ShapedLine cache, one level
1842/// down. Held by a [`crate::Doc`] and threaded into [`build_cached`], it is what
1843/// makes a rebuild after a keystroke cost "re-render the edited block + shift
1844/// the rest" instead of re-rendering the whole document.
1845///
1846/// A top-level block's rows are a pure function of its source bytes and the wrap
1847/// width, so an unchanged block's rows are cloned and their source offsets
1848/// shifted by the edit's byte delta rather than rebuilt glyph by glyph. Two
1849/// things make that purity hold: at the top level the render prefix is always
1850/// empty (nesting prefixes — a quote gutter, a list indent — exist only *inside*
1851/// a top-level block, within its cached unit), and a block's output never reads
1852/// the incoming `last_off` (it writes `last_off` from its own content before any
1853/// nested separator reads it). So the only thing that differs between two
1854/// positions of an unchanged block is a uniform offset shift. Keyed by a fast
1855/// hash of the block's bytes with the bytes kept for a verify-on-hit — exactly
1856/// the shape cache's weak-hash-then-compare, so a collision costs a re-render,
1857/// never a wrong row.
1858///
1859/// Tables are never cached (a block that emits any table row is always rebuilt):
1860/// their rows are cross-referenced from the map's `tables` side-table by row
1861/// index, which a blind offset-shift wouldn't fix up, and they are rare enough
1862/// that the simplicity beats the reuse.
1863#[derive(Default)]
1864pub struct BlockCache {
1865    /// The wrap width every entry was built at; a change invalidates all of
1866    /// them. `None` before the first build (distinct from `Some(None)`, the
1867    /// unwrapped GUI width).
1868    wrap: Option<Option<usize>>,
1869    /// Bumped once per [`build_cached`]. An entry reused or inserted this build
1870    /// carries the current value; stale entries are dropped at the end of it.
1871    generation: u64,
1872    /// `hash(bytes)` → the block(s) sharing that hash — a bucket because
1873    /// distinct blocks can collide, while two *identical* blocks share one entry
1874    /// (free dedup).
1875    entries: HashMap<u64, Vec<CachedBlock>>,
1876    /// The row/stop decomposition of the last build, which [`build_spliced`]
1877    /// patches in place for a single-block edit. Kept in step with whatever
1878    /// [`VisualMap`] was last produced; empty before the first build.
1879    layout: Layout,
1880}
1881
1882/// How the last build's [`VisualMap`] decomposes into top-level blocks — the
1883/// bookkeeping [`build_spliced`] needs to splice one block's rows and stops
1884/// without rebuilding the whole map. Every field describes the *previous* build,
1885/// in that build's coordinates.
1886#[derive(Default)]
1887struct Layout {
1888    /// One entry per rendered (metadata-filtered) top-level block, in order.
1889    blocks: Vec<BlockLayout>,
1890    /// Trailing blank rows past the last block (from `emit_trailing_blank_lines`).
1891    trailing_rows: usize,
1892    /// The source length this layout was built at — the reference for the edit's
1893    /// byte delta.
1894    built_len: usize,
1895    /// Whether the last build drew any table. A table's cross-referenced row
1896    /// indices don't survive a blind splice, so their presence makes
1897    /// [`build_spliced`] bail to a full rebuild.
1898    has_tables: bool,
1899    /// Whether every block rendered strictly inside its own span (see
1900    /// [`rows_within`]). A block that doesn't — a malformed Markdown inline node
1901    /// that twig leaves with a degenerate `0..0` span renders at a fixed offset
1902    /// outside its block — can't be shifted correctly, so its presence makes
1903    /// [`build_spliced`] bail to a full rebuild.
1904    all_shift_safe: bool,
1905    /// The reveal line this layout was built under (see [`Builder::reveal`]).
1906    /// A splice reuses every row it isn't re-rendering, so a reveal line that
1907    /// has moved would leave the old line still showing its delimiters and the
1908    /// new one still hiding them — [`build_spliced`] bails when this changes.
1909    reveal: Option<Range<usize>>,
1910}
1911
1912/// One top-level block's contribution to the last build: its span and kind (for
1913/// the structural match that proves only one block changed) and how many
1914/// separator and content rows it emitted (to locate its slice of the row
1915/// vector).
1916struct BlockLayout {
1917    span: Range<usize>,
1918    kind: Kind,
1919    sep_rows: usize,
1920    content_rows: usize,
1921}
1922
1923/// One cached block: the rows it rendered to, plus what a reuse at a new
1924/// position needs to shift them. Offsets are stored absolute (as built) and
1925/// shifted by `new_start - built_start` on reuse.
1926struct CachedBlock {
1927    /// The block's exact source bytes, compared on a hash hit so a collision
1928    /// can never hand back another block's rows.
1929    bytes: Box<[u8]>,
1930    /// The offset the rows were built at (the block's `span.start`).
1931    built_start: usize,
1932    /// The block's rows, offsets absolute as built.
1933    rows: Vec<VRow>,
1934    /// `last_off` after this block was emitted, absolute as built — restored
1935    /// (shifted) on reuse so the following separator lands correctly.
1936    last_off: usize,
1937    /// Where the reveal line fell *within this block* when the rows were built,
1938    /// as a block-relative byte range — see [`reveal_key`]. Compared alongside
1939    /// `bytes` on a hit, because identical source renders to different rows
1940    /// depending on whether the caret's line is inside it: the same `*em*`
1941    /// shows its asterisks on the revealed line and hides them everywhere else.
1942    ///
1943    /// Block-relative rather than absolute so an unaffected block still hits
1944    /// after an edit shifts it, and `None` for the overwhelmingly common
1945    /// no-reveal case — which is why an entry stored under `MarkupMode::None`
1946    /// keeps hitting for every block that isn't the caret's.
1947    reveal: Option<Range<usize>>,
1948    /// The build that last reused or inserted this entry (see `generation`).
1949    generation: u64,
1950}
1951
1952/// Where `reveal` falls inside a block, in block-relative bytes — the extra key
1953/// a cached block is stored and matched under.
1954///
1955/// `None` when the block doesn't meet the reveal line at all, which is every
1956/// block on every build in the two hidden modes, and all but one of them under
1957/// [`crate::MarkupMode::Full`]. So the cache keeps its hit rate as the caret
1958/// moves: only the line the caret leaves and the line it arrives at re-render.
1959fn reveal_key(reveal: &Option<Range<usize>>, span: &Range<usize>) -> Option<Range<usize>> {
1960    let r = reveal.as_ref()?;
1961    // The same generous intersection test `Builder::revealed` uses, so a block
1962    // is keyed as revealed exactly when its glyphs will be built that way.
1963    (span.start <= r.end && r.start <= span.end).then(|| {
1964        let start = r.start.max(span.start) - span.start;
1965        let end = r.end.min(span.end) - span.start;
1966        start..end
1967    })
1968}
1969
1970impl BlockCache {
1971    /// Look up a block by hash, verify its bytes and reveal key, and on a hit
1972    /// stamp it used this build and hand back a borrow to shift-and-clone from.
1973    /// `None` on a miss (unknown hash, a collision whose bytes differ, or the
1974    /// same bytes built under a different reveal).
1975    fn reuse(
1976        &mut self,
1977        hash: u64,
1978        bytes: &[u8],
1979        reveal: &Option<Range<usize>>,
1980    ) -> Option<&CachedBlock> {
1981        let g = self.generation;
1982        let bucket = self.entries.get_mut(&hash)?;
1983        let e = bucket
1984            .iter_mut()
1985            .find(|e| &*e.bytes == bytes && &e.reveal == reveal)?;
1986        e.generation = g;
1987        Some(&*e)
1988    }
1989
1990    /// Cache the rows a freshly-rendered block produced (or refresh an existing
1991    /// entry for the same bytes and reveal — an identical block elsewhere, or a
1992    /// re-render).
1993    fn store(
1994        &mut self,
1995        hash: u64,
1996        bytes: &[u8],
1997        built_start: usize,
1998        rows: Vec<VRow>,
1999        last_off: usize,
2000        reveal: Option<Range<usize>>,
2001    ) {
2002        let g = self.generation;
2003        let bucket = self.entries.entry(hash).or_default();
2004        if let Some(e) = bucket
2005            .iter_mut()
2006            .find(|e| &*e.bytes == bytes && e.reveal == reveal)
2007        {
2008            e.built_start = built_start;
2009            e.rows = rows;
2010            e.last_off = last_off;
2011            e.generation = g;
2012        } else {
2013            bucket.push(CachedBlock {
2014                bytes: bytes.into(),
2015                built_start,
2016                rows,
2017                last_off,
2018                reveal,
2019                generation: g,
2020            });
2021        }
2022    }
2023}
2024
2025/// The source bytes a top-level block covers — the block cache's key material.
2026///
2027/// Clamped to the source rather than sliced by the span as twig gives it,
2028/// because that span can end *past* the last byte: the final block of a document
2029/// with no trailing newline is closed on the virtual newline the parser supplies
2030/// at EOF, so its `span.end` is `source.len() + 1`. Slicing by such a range
2031/// yields `None`, and the obvious `unwrap_or(&[])` reads that as *this block has
2032/// no bytes* — the wrong answer twice over.
2033///
2034/// Two blocks whose spans both overrun then key alike, and the second is served
2035/// the first one's rows. That is not hypothetical: a footnote definition is a
2036/// root beside `doc` merged back into the top level by [`top_blocks`], while the
2037/// `section` above it spans the definition's bytes too, so both end at EOF —
2038/// and a document ending in `[^note]: …` renders that definition as a second
2039/// copy of the heading. Even alone, a block that keeps hashing empty as the user
2040/// types in it is served the stale rows built before the edit.
2041///
2042/// Clamping hands back the bytes the block really covers, which tells both cases
2043/// apart, and costs nothing for a span that was in range to begin with.
2044fn block_bytes<'a>(source: &'a str, span: &Range<usize>) -> &'a [u8] {
2045    let bytes = source.as_bytes();
2046    let start = span.start.min(bytes.len());
2047    &bytes[start..span.end.clamp(start, bytes.len())]
2048}
2049
2050/// A fast, allocation-free content hash (FNV-1a) for a block's bytes. Weak by
2051/// design — the bytes are compared on a hit — so its only job is to spread
2052/// blocks across buckets cheaply. SipHash over every block's bytes on every
2053/// keystroke would cost more than it saves, the same lesson the shape cache
2054/// learned when it stopped hashing through the standard hasher.
2055fn block_hash(bytes: &[u8]) -> u64 {
2056    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
2057    for &x in bytes {
2058        h ^= x as u64;
2059        h = h.wrapping_mul(0x0000_0100_0000_01b3);
2060    }
2061    h
2062}
2063
2064/// Clone a cached row with every source offset advanced by `delta` — the whole
2065/// cost of reusing an unchanged block: integer adds where a rebuild would
2066/// re-shape every glyph.
2067fn shift_row(row: &VRow, delta: isize) -> VRow {
2068    let shift = |off: usize| (off as isize + delta) as usize;
2069    VRow {
2070        glyphs: row
2071            .glyphs
2072            .iter()
2073            .map(|g| Glyph {
2074                ch: g.ch,
2075                style: g.style,
2076                src: shift(g.src),
2077                stop: g.stop,
2078            })
2079            .collect(),
2080        end_src: shift(row.end_src),
2081        decoration: row.decoration,
2082        code: row.code,
2083        code_lang: row.code_lang.clone(),
2084        directive: row.directive,
2085        directive_label: row.directive_label.clone(),
2086        media: row.media.clone(),
2087        // A tick, not an offset — reuse carries it as-is, like `code_lang`.
2088        task: row.task,
2089        leaf_directive: row.leaf_directive.clone(),
2090        heading: row.heading,
2091        // Presentation, not offsets: names the author wrote, which a shifted
2092        // block still wears — like `code_lang`.
2093        align: row.align,
2094        line_height: row.line_height,
2095        // Structure, not offsets: a reused block's rows divide the same blocks
2096        // wherever the edit above moved them to.
2097        boundary: row.boundary,
2098        mark_ends: row.mark_ends.iter().map(|&o| shift(o)).collect(),
2099    }
2100}
2101
2102/// Advance a row's source offsets by `delta` in place — the suffix half of
2103/// [`build_spliced`], where the rows are already owned and only need shifting,
2104/// not copying.
2105fn shift_row_in_place(row: &mut VRow, delta: isize) {
2106    for g in &mut row.glyphs {
2107        g.src = (g.src as isize + delta) as usize;
2108    }
2109    row.end_src = (row.end_src as isize + delta) as usize;
2110    for o in &mut row.mark_ends {
2111        *o = (*o as isize + delta) as usize;
2112    }
2113}
2114
2115/// Whether every source offset a block's rows carry falls inside the block's own
2116/// span — the precondition for reusing the block by a uniform offset shift. It
2117/// holds for well-formed blocks (their glyphs and row ends address bytes within
2118/// the block, synthetic glyphs point at the block start). It fails when a node
2119/// renders *outside* its block, which today means a malformed Markdown inline
2120/// node twig leaves with a degenerate `0..0` span: that content lands at a fixed
2121/// offset that doesn't move with the block. Such a block is re-rendered every
2122/// build instead of shifted, so the incremental map still matches a fresh one —
2123/// see [`build_cached`] and [`build_spliced`].
2124fn rows_within(rows: &[VRow], span: &Range<usize>) -> bool {
2125    rows.iter().all(|r| {
2126        r.end_src >= span.start
2127            && r.end_src <= span.end
2128            && r.glyphs
2129                .iter()
2130                .all(|g| g.src >= span.start && g.src <= span.end)
2131    })
2132}
2133
2134/// Where the rendered document begins when a leading `metadata` block is all
2135/// there is — the end of that hidden frontmatter, past the newline that closes
2136/// its last line so the floor sits at the start of the (empty) body rather than
2137/// on the closing `---`.
2138///
2139/// With a real block after it the frontmatter's end is never needed: the floor
2140/// is that block's start, and the rows begin there. With nothing after it, both
2141/// the caret floor and the trailing-blank-line count would otherwise fall back
2142/// to offset 0 — inside the hidden frontmatter — which put the caret *before*
2143/// the metadata and made typing land ahead of the opening `---`.
2144fn hidden_prefix_end(source: &str, meta_end: Option<usize>) -> usize {
2145    let Some(end) = meta_end else { return 0 };
2146    let end = end.min(source.len());
2147    let rest = &source[end..];
2148    if rest.starts_with("\r\n") {
2149        end + 2
2150    } else if rest.starts_with('\n') {
2151        end + 1
2152    } else {
2153        end
2154    }
2155}
2156
2157/// The end of the document's hidden frontmatter: the last `metadata` child of
2158/// `doc`, which is what [`top_level`] and [`Builder::blocks`] drop. `None` when
2159/// there is none.
2160fn metadata_end_of(nodes: &[FlatNode], doc: usize) -> Option<usize> {
2161    let mut end = None;
2162    let mut child = nodes[doc].first_child;
2163    while let Some(cid) = child {
2164        let n = &nodes[cid.0 as usize];
2165        if n.kind == Kind::Metadata {
2166            end = Some(n.span.end);
2167        }
2168        child = n.next_sibling;
2169    }
2170    end
2171}
2172
2173/// The document's rendered top-level blocks, as node indices in source order.
2174///
2175/// Not simply `doc`'s children, for two reasons. Frontmatter (a leading
2176/// `metadata` block) is document metadata rather than prose and is dropped, the
2177/// way [`Builder::blocks`] drops it. And a **footnote definition** (`[^1]: …`)
2178/// is not a child of `doc` at all: twig parses it as a root of its own, a
2179/// *sibling* of the document node with `parent == None`. A walk that starts at
2180/// `doc` therefore never reaches one, which is why a definition — and every
2181/// byte of its body — used to render as nothing at all. Merging the roots back
2182/// in by `span.start` puts each definition on screen exactly where it was
2183/// written, which is what keeps rows, stops, and offsets monotonic.
2184///
2185/// A **link reference definition** (`[foo]: /url`) is a root of the same kind,
2186/// and is merged for the opposite reason: it draws *nothing*, and the walk has
2187/// to know where it stands to step over it. A definition closing a README —
2188/// the `[links]: …` block under the prose — left no block over its lines, so
2189/// the separator logic read them as blank lines and drew an empty paragraph
2190/// per definition. Merged in, it is a hidden block like a comment, and
2191/// [`Builder::block_or_hidden`] moves the walk past it. One with no span
2192/// (`0..0`, what twig before 3.3.3 reported for every one) has nowhere to be
2193/// merged, and is left out as before.
2194///
2195/// Only those roots are merged. twig also leaves stray orphan `str` nodes
2196/// parented to nothing (the `*` of an emphasis run, for one); those are already
2197/// rendered as part of the subtree that owns their bytes, and re-emitting them
2198/// here would double them.
2199fn top_level(nodes: &[FlatNode], doc: usize) -> Vec<usize> {
2200    let mut out = Vec::new();
2201    let mut child = nodes[doc].first_child;
2202    while let Some(cid) = child {
2203        let n = &nodes[cid.0 as usize];
2204        if n.kind != Kind::Metadata {
2205            out.push(cid.0 as usize);
2206        }
2207        child = n.next_sibling;
2208    }
2209    out.extend(
2210        nodes
2211            .iter()
2212            .enumerate()
2213            .filter(|(_, n)| n.parent.is_none() && is_placed_definition(&n.kind, &n.span))
2214            .map(|(i, _)| i),
2215    );
2216    out.sort_by_key(|&i| nodes[i].span.start);
2217    out
2218}
2219
2220/// Is a parentless node of `kind` at `span` a definition the top-level walk
2221/// merges in — a footnote definition, or a link reference definition that
2222/// knows where it stands? Shared by [`top_level`] and [`top_blocks`] so the
2223/// two walks cannot disagree about what the top-level blocks are.
2224fn is_placed_definition(kind: &Kind, span: &Range<usize>) -> bool {
2225    match *kind {
2226        Kind::Footnote => true,
2227        Kind::Reference => span.end > span.start,
2228        _ => false,
2229    }
2230}
2231
2232/// The top-level blocks to hand [`build_cached`] / [`build_spliced`] — the
2233/// incremental path's twin of [`top_level`], which the two must agree with block
2234/// for block or the render paths diverge.
2235///
2236/// `child_spans(None)` gives `doc`'s children, which is all of them for an
2237/// ordinary document. A **footnote definition** is not one: twig parses `[^1]: …`
2238/// as a root beside `doc` with no parent, and indexes it at no offset either —
2239/// `node_at` inside its bytes answers `doc`, and a `query("footnote")` selector
2240/// finds nothing. Leaf used to discover them by marshalling the whole arena with
2241/// `nodes()` — the very cost the incremental path exists to avoid — behind a
2242/// byte-scan gate that gave documents with no `[^…]:` line a substring search
2243/// instead. twig 3.0's `definitions()` asks the library the question directly,
2244/// so both the marshal and the gate are gone.
2245///
2246/// The link reference definitions `definitions()` also reports are merged on
2247/// the same terms as [`top_level`] merges them — see [`is_placed_definition`].
2248///
2249/// This is the one part of the render that needs an [`Editor`] rather than a
2250/// marshalled node array. The builders themselves stay editor-free; this only
2251/// prepares their input.
2252pub(crate) fn top_blocks(editor: &mut Editor) -> Vec<QueryMatch> {
2253    let mut top = editor.child_spans(None).unwrap_or_default();
2254    let defs: Vec<QueryMatch> = definitions(editor)
2255        .into_iter()
2256        .filter(|m| is_placed_definition(&m.kind, &m.span))
2257        .collect();
2258    if defs.is_empty() {
2259        return top;
2260    }
2261    top.extend(defs);
2262    // Source order — what every offset-keyed thing downstream (rows, stops, the
2263    // splice path's block-for-block match) is built to assume.
2264    top.sort_by_key(|m| m.span.start);
2265    top
2266}
2267
2268/// Every `[^label]: …` definition in the document, in whatever order twig
2269/// reports them.
2270///
2271/// Filtered to [`Kind::Footnote`]: `definitions()` also reports the *link*
2272/// reference definitions (`[foo]: /url`), which are [`top_blocks`]'s business
2273/// and not [`crate::Doc::footnote_at_caret`]'s.
2274///
2275/// Empty when the document can't be walked, which leaves [`top_blocks`] with
2276/// the ordinary top-level children and [`crate::Doc::footnote_at_caret`] with an
2277/// undefined reference — in both cases the same answer as a document that has
2278/// no definitions, which is the right way to degrade.
2279pub(crate) fn footnote_definitions(editor: &mut Editor) -> Vec<QueryMatch> {
2280    definitions(editor)
2281        .into_iter()
2282        .filter(|m| m.kind == Kind::Footnote)
2283        .collect()
2284}
2285
2286/// Every definition twig resolves by label rather than by position — footnote
2287/// and link reference definitions both — or nothing when the document can't be
2288/// walked.
2289fn definitions(editor: &mut Editor) -> Vec<QueryMatch> {
2290    let Ok(mut doc) = editor.document() else {
2291        return Vec::new();
2292    };
2293    doc.definitions().unwrap_or_default()
2294}
2295
2296/// The label of the footnote definition starting at `start` — the `1` in
2297/// `[^1]: …`. twig gives the `footnote` node no label of its own (no `text`, no
2298/// `name`), and the bytes that spell it belong to no child node either — the
2299/// body `para` starts its *content* past them — so the source is the only place
2300/// to read it from. `None` when what's there isn't a definition after all.
2301pub(crate) fn footnote_label(source: &str, start: usize) -> Option<&str> {
2302    let rest = source.get(start..)?.strip_prefix("[^")?;
2303    let end = rest.find("]:")?;
2304    Some(&rest[..end])
2305}
2306
2307/// Where the body of the footnote definition spanning `span` sits in `source` —
2308/// everything past the `[^1]:` marker, which is the part a reader actually wants
2309/// when they follow a reference.
2310///
2311/// Source bytes, verbatim but for the whitespace trimmed off each end: a note
2312/// that says `see *later*` answers with the asterisks in. Rendering that body is
2313/// a frontend's business the same way painting a [`Role`] is, and a caller that
2314/// wants it laid out already has the definition on screen where it was written.
2315///
2316/// The trim is what makes the common case read right — `[^1]: text` has a space
2317/// after the colon that belongs to the marker, not the note, and a definition's
2318/// span runs to the newline ending it.
2319///
2320/// The span is taken at its word, which it has only been safe to do since twig
2321/// 3.1: a djot definition's span used to run *past* its own last line, through
2322/// the blank line separating it from the next block and into that block's first
2323/// byte, so `[^2a]: a note.` came back as `"a note.\n\n["` and the offsets named
2324/// the following note's rows as well as this one's — a reader asking about one
2325/// footnote was shown two. leaf measured the body itself to get around that, and
2326/// paid for it: the scan stopped at the first blank line, so a note with a second
2327/// indented paragraph lost it. Both halves go away with the fix, since a blank
2328/// line *inside* a definition was always interior to the span and still is.
2329///
2330/// A range rather than a slice because "go to note" needs the *position* as much
2331/// as the text, and it needs the position of the body specifically: a
2332/// definition's `[^1]:` marker is decoration the caret can't occupy (the rich
2333/// view draws it as `[1] ` and gives it no stop), so aiming a caret at the
2334/// definition's first byte lands it on the nearest real stop instead — which is
2335/// up in the paragraph *above* the note. The body's first byte is a stop, and is
2336/// where a reader following a reference wants to arrive anyway.
2337pub(crate) fn footnote_body_span(source: &str, span: Range<usize>) -> Option<Range<usize>> {
2338    let rest = source.get(span.clone())?.strip_prefix("[^")?;
2339    let marker = rest.find("]:")?;
2340    // `span.start` + `[^` + the label + `]:`.
2341    let after_marker = span.start + 2 + marker + 2;
2342    let raw = source.get(after_marker..span.end)?;
2343    // Written as a start plus a length so an all-whitespace body lands on an
2344    // empty range at the end rather than an inverted one.
2345    let start = after_marker + (raw.len() - raw.trim_start().len());
2346    Some(start..start + raw.trim().len())
2347}
2348
2349/// The label of the footnote *reference* spanning `span` — the `1` in `[^1]`.
2350///
2351/// The peer of [`footnote_label`] for the other half of the pair, and needed for
2352/// the same reason: a reference whose node carries neither a `content_span` nor
2353/// a `text` still spells its label plainly in the source. `None` when the bytes
2354/// aren't a reference after all.
2355pub(crate) fn footnote_reference_label(source: &str, span: Range<usize>) -> Option<&str> {
2356    let rest = source.get(span)?.strip_prefix("[^")?;
2357    let end = rest.find(']')?;
2358    Some(&rest[..end])
2359}
2360
2361/// Where a heading's *content* starts — past the `#`s and the space the rich
2362/// view hides, for an ATX heading; the block's own start for a setext one (which
2363/// has no leading marker) and for a format that spells headings some other way.
2364///
2365/// Only an empty heading needs asking: with any content at all, the row ends on
2366/// its last glyph. Bounded to the heading's own first line so a marker-less
2367/// heading can't scan into the text under it.
2368fn heading_content_start(source: &str, span: &Range<usize>) -> usize {
2369    let end = span.end.min(source.len());
2370    let Some(line) = source.get(span.start..end) else {
2371        return span.start;
2372    };
2373    let line = line.split('\n').next().unwrap_or("");
2374    let hashes = line.len() - line.trim_start_matches('#').len();
2375    if hashes == 0 {
2376        return span.start;
2377    }
2378    let after = &line[hashes..];
2379    span.start + hashes + (after.len() - after.trim_start_matches([' ', '\t']).len())
2380}
2381
2382struct Builder<'a> {
2383    nodes: &'a [FlatNode],
2384    /// The document source, consulted to place blank-line rows at the source
2385    /// offsets the caret should occupy on them (the AST drops blank lines).
2386    source: &'a str,
2387    /// The word-wrap column budget, or `None` to emit each block as a single
2388    /// unwrapped row (the frontend wraps).
2389    wrap: Option<usize>,
2390    rows: Vec<VRow>,
2391    /// Built alongside `rows`, never instead of them — see [`TableInfo`].
2392    tables: Vec<TableInfo>,
2393    /// The end offset of the last content emitted — the anchor for blank
2394    /// separator rows so the caret never snaps onto one.
2395    last_off: usize,
2396    /// The end of the last block the walk stepped over without drawing — a
2397    /// comment, which the rich view hides. `last_off` moves past it too, for the
2398    /// separators; this is kept apart so the trailing blank lines can be counted
2399    /// from it without also being counted from a code block's closing fence,
2400    /// which `last_off` likewise ends after. `0` until a hidden block is met.
2401    stepped_over: usize,
2402    /// How many rows each block image reserves, keyed by its destination — the
2403    /// frontend's per-image height, threaded in from [`crate::Doc::set_media_rows`]
2404    /// so [`Builder::block_media`] can size the placeholder without core doing any
2405    /// I/O. A destination absent from the map (or a `0`/`1` entry) reserves the
2406    /// bare one-row placeholder, which is the whole-document default and what
2407    /// every existing test — passing an empty map — still gets.
2408    media_rows: &'a HashMap<String, usize>,
2409    /// The glyph a hard break renders as while the current inline run is built:
2410    /// a space in prose (a break folds into the flow the frontend wraps), but a
2411    /// newline (`\n`) inside a table cell, where a row is one source line and the
2412    /// only break it can carry is an explicit one that must show as a line of its
2413    /// own. Set around [`Builder::row_cells`] and otherwise left at `' '`.
2414    break_glyph: Cell<char>,
2415    /// Render a soft break (a bare newline inside a paragraph) as a line break
2416    /// where it was written, rather than folding it into the reflowed paragraph
2417    /// — the `LineFlow::Preserve` behaviour. A soft break emits a `'\n'` glyph
2418    /// (like a hard break in a cell), which [`Builder::emit_wrapped`] turns into
2419    /// a fresh visual row. `false` is the flowing-prose default. Inside a table
2420    /// cell (where `break_glyph` is already `'\n'`) it has no effect: a cell is
2421    /// one line and folds its own soft breaks regardless.
2422    preserve_soft: bool,
2423    /// The source byte range of the one line that should render its markup
2424    /// *raw* — the caret's line under `MarkupMode::Full` (see
2425    /// [`crate::Doc::reveal_line`]). `None` in every other mode and view, which
2426    /// is the delimiters-always-hidden behaviour every build had before the
2427    /// preference existed.
2428    ///
2429    /// Read only by [`Builder::revealed`], which every delimiter-bearing arm of
2430    /// [`Builder::inline`] consults. A range rather than a bare caret offset
2431    /// because the decision is per-*node*, not per-caret: a node is revealed
2432    /// when its span meets this line, so `*em*` shows both its asterisks even
2433    /// with the caret at one end of it.
2434    reveal: Option<Range<usize>>,
2435    /// The content ends of the hidden marks rendered since the last row was
2436    /// pushed — recorded as the inline walk meets each mark, and drained onto
2437    /// the rows as they are emitted (see [`Builder::take_mark_ends`]). A cell
2438    /// rather than a `&mut`, for the reason `break_glyph` is: the inline walk
2439    /// borrows the builder shared.
2440    pending_mark_ends: RefCell<Vec<usize>>,
2441    /// The presentation vocabulary in force at the block being walked — the
2442    /// keys the `div`s around it carry, folded together with the nearest
2443    /// winning, and [`Presentation::default`] at the top level.
2444    ///
2445    /// Saved and restored around each `div` in [`Builder::block`], so a block
2446    /// reads its own attributes over whatever its containers said and nothing
2447    /// leaks sideways to the block after it. It is per-*build* state rather
2448    /// than a parameter because every one of the dozen call sites of `block`
2449    /// would otherwise thread a value none of them care about.
2450    presentation: Presentation,
2451}
2452
2453/// The six presentation keys as the walker carries them down a block tree —
2454/// the two that are the block's ([`Align`], [`LineSpacing`]) and the three that
2455/// are a run's but may be written on the block ([`SizeStep`], [`FontFamily`],
2456/// [`MarkColor`]).
2457///
2458/// `Copy` and five `Option`s, because folding is the whole of what it does:
2459/// [`under`](Presentation::under) reads a container's attributes over an
2460/// existing set and a key the container does not name keeps the value it had.
2461/// That is the "nearest wins" rule stated once, rather than at each of the
2462/// three levels a key can be written at.
2463#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2464struct Presentation {
2465    align: Option<Align>,
2466    line_height: Option<LineSpacing>,
2467    size: Option<SizeStep>,
2468    font: Option<FontFamily>,
2469    color: Option<MarkColor>,
2470}
2471
2472impl Presentation {
2473    /// This set with whatever `attrs` names written over it — the nearer node's
2474    /// answer where it has one, the outer node's where it hasn't.
2475    fn under(self, attrs: &[(String, Option<String>)]) -> Self {
2476        Self {
2477            align: Align::from_attrs(attrs).or(self.align),
2478            line_height: LineSpacing::from_attrs(attrs).or(self.line_height),
2479            size: SizeStep::from_attrs(attrs).or(self.size),
2480            font: FontFamily::from_attrs(attrs).or(self.font),
2481            color: MarkColor::from_attrs(attrs).or(self.color),
2482        }
2483    }
2484
2485    /// `base` carrying the three run-level keys — the style a block's glyphs
2486    /// start from, which an attributed span inside it then writes over.
2487    fn over(self, base: Style) -> Style {
2488        base.size(self.size).font(self.font).color(self.color)
2489    }
2490}
2491
2492impl Builder<'_> {
2493    /// Note that the mark `id` closes with a hidden delimiter, so its content
2494    /// end is a caret home — unless the mark is empty, where the end is the
2495    /// start and there is nothing to extend.
2496    fn note_mark_end(&self, id: usize) {
2497        let node = &self.nodes[id];
2498        if let Some(content) = &node.content_span
2499            && content.end < node.span.end
2500            && !content.is_empty()
2501        {
2502            self.pending_mark_ends.borrow_mut().push(content.end);
2503        }
2504    }
2505
2506    /// The pending mark ends at or before `end_src`, for the row ending there
2507    /// — every mark rendered so far that closes on it. A mark's end never
2508    /// exceeds the end of the row its last glyph is on, so the leftovers are
2509    /// those of rows still to come.
2510    fn take_mark_ends(&self, end_src: usize) -> Vec<usize> {
2511        let mut pending = self.pending_mark_ends.borrow_mut();
2512        let (taken, kept): (Vec<usize>, Vec<usize>) =
2513            pending.drain(..).partition(|&o| o <= end_src);
2514        *pending = kept;
2515        taken
2516    }
2517    /// Whether `span` belongs to the line that is showing its raw markup. True
2518    /// only when a reveal line is set (`MarkupMode::Full`) and the two ranges
2519    /// actually meet.
2520    ///
2521    /// Touching at an endpoint counts: an emphasis ending exactly where the line
2522    /// does is on that line, and a zero-length reveal range (the caret alone on
2523    /// a blank line) still meets a node that starts there. The test is
2524    /// deliberately generous — the failure it avoids is revealing one delimiter
2525    /// of a pair while hiding the other, which looks like corruption rather than
2526    /// like markup.
2527    fn revealed(&self, span: &Range<usize>) -> bool {
2528        self.reveal
2529            .as_ref()
2530            .is_some_and(|r| span.start <= r.end && r.start <= span.end)
2531    }
2532
2533    /// The `(opening, closing)` source byte ranges of a node's delimiters — the
2534    /// bytes its `span` holds that its `content_span` doesn't.
2535    ///
2536    /// This is how *every* inline delimiter is recovered, rather than a table of
2537    /// spellings per kind: twig gives `*em*` a span of `13..17` and a content
2538    /// span of `14..16`, so the gaps at each end are the delimiters, whatever
2539    /// they happen to be. That matters because one kind has many spellings —
2540    /// `*em*` and `_em_` are both emphasis, `` `x` `` and ``` ``x`` ``` both
2541    /// verbatim — and re-deriving the text from the source is the only way to
2542    /// show back what the author actually typed. It also gets a link's
2543    /// asymmetric `[` / `](dest)` right for free.
2544    ///
2545    /// `None` when the node has no content span, or when content and span
2546    /// coincide (nothing was elided, so there is nothing to reveal).
2547    fn delims(&self, id: usize) -> Option<(Range<usize>, Range<usize>)> {
2548        let node = &self.nodes[id];
2549        let content = node.content_span.clone()?;
2550        let span = node.span.clone();
2551        // A content span that escapes its own node's span means the two are
2552        // describing different things; reveal nothing rather than slice wildly.
2553        if content.start < span.start || content.end > span.end {
2554            return None;
2555        }
2556        let (open, close) = (span.start..content.start, content.end..span.end);
2557        // A delimiter that spans a newline isn't this line's to reveal — a setext
2558        // heading's `\n=====` underline is the case that arises in practice. It
2559        // would also inject a `'\n'` glyph, which `emit_wrapped` reads as a hard
2560        // row break, so the row would split where the author wrote no break.
2561        let multiline =
2562            |r: &Range<usize>| self.source.get(r.clone()).is_some_and(|s| s.contains('\n'));
2563        if multiline(&open) || multiline(&close) {
2564            return None;
2565        }
2566        (!open.is_empty() || !close.is_empty()).then_some((open, close))
2567    }
2568
2569    /// Emit the source bytes of `range` as revealed markup — real glyphs, each
2570    /// mapped to its own source byte and each a caret stop, so a delimiter shown
2571    /// is a delimiter that can be selected, edited and deleted like any other
2572    /// text. Styled [`Role::Delimiter`] on top of the run's own style, which is
2573    /// how a frontend tells scaffolding from prose and dims it.
2574    ///
2575    /// Deliberately *not* [`push_escaped_text`]: this is raw source, not parsed
2576    /// text, so there is no escape-driven drift between the two to correct.
2577    fn push_delim(&self, out: &mut Vec<Glyph>, range: &Range<usize>, base: Style) {
2578        let Some(text) = self.source.get(range.clone()) else {
2579            return;
2580        };
2581        push_text(out, text, range.start, base.role(Role::Delimiter));
2582    }
2583
2584    /// Render an inline node's children wrapped in its raw delimiters when the
2585    /// node is on the revealed line, and bare (delimiters resolved away) when it
2586    /// isn't — the shared body of every delimiter-bearing arm of
2587    /// [`inline`](Self::inline).
2588    ///
2589    /// `style` is the resolved styling the content still gets in *both* modes:
2590    /// revealing `*em*` shows the asterisks *and* keeps the text italic, the
2591    /// live-preview behaviour. Showing the markup is not the same as turning the
2592    /// rendering off — that is what [`crate::View::Source`] is for.
2593    fn inline_delimited(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
2594        let show = self
2595            .revealed(&self.nodes[id].span)
2596            .then(|| self.delims(id))
2597            .flatten();
2598        if let Some((open, _)) = &show {
2599            self.push_delim(out, open, style);
2600        }
2601        self.recurse(id, style, out);
2602        match &show {
2603            Some((_, close)) => self.push_delim(out, close, style),
2604            // Hidden, so the content's end has no glyph after it: give the
2605            // caret its home there.
2606            None => self.note_mark_end(id),
2607        }
2608    }
2609
2610    fn children(&self, id: usize) -> Vec<usize> {
2611        let mut out = Vec::new();
2612        let mut c = self.nodes[id].first_child;
2613        while let Some(cid) = c {
2614            out.push(cid.0 as usize);
2615            c = self.nodes[cid.0 as usize].next_sibling;
2616        }
2617        out
2618    }
2619
2620    /// Render a node's block children, a blank separator between each. `tight`
2621    /// suppresses the *fabricated* separator between adjacent children that share
2622    /// a source line boundary — a tight list item and the sub-list nested in it —
2623    /// while a real blank source line between them still opens a gap.
2624    fn blocks(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph], tight: bool) {
2625        // Frontmatter (a leading `metadata` block) is document metadata, not
2626        // prose: hide it entirely in the rich-text view. Skipping it here means
2627        // no phantom blank rows for its lines and no separator before the first
2628        // real block — the document opens straight into its content.
2629        let kids: Vec<usize> = self
2630            .children(id)
2631            .into_iter()
2632            .filter(|&c| self.nodes[c].kind != Kind::Metadata)
2633            .collect();
2634        let mut above: Option<BlockClass> = None;
2635        for child in kids {
2636            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
2637            let before_sep = self.rows.len();
2638            if let Some(above) = above {
2639                self.emit_separators_before(
2640                    self.nodes[child].span.start,
2641                    pc,
2642                    !tight,
2643                    Boundary { above, below },
2644                );
2645            }
2646            // The first *drawn* child wears the first-row prefix (a bullet, a
2647            // footnote label), not the first child: a comment opening a list
2648            // item draws nothing, and the bullet belongs to what follows it.
2649            let first = if above.is_none() { pf } else { pc };
2650            if self.block_or_hidden(child, before_sep, first, pc) {
2651                above = Some(below);
2652            }
2653        }
2654    }
2655
2656    /// Render `child` after the separator [`Builder::emit_separators_before`]
2657    /// spelled for it from row `before_sep` on, and say whether it drew
2658    /// anything.
2659    ///
2660    /// A block that draws no rows — an HTML comment, which the rich view hides
2661    /// the way it hides frontmatter — is still *there* in the source, and the
2662    /// walk has to step over it: `last_off` moves past it so the next separator
2663    /// counts the blank lines from its end, not from wherever the last drawn
2664    /// block stopped. Left where it was, the separator counted every line of the
2665    /// comment as a blank row; and the cached path, whose per-block builder
2666    /// starts at offset 0, handed back a `last_off` of 0 and counted every line
2667    /// of the *document* — one phantom blank row per source line, once per
2668    /// comment. The separator drawn for it is taken back too, so a hidden block
2669    /// leaves no gap of its own: what stands either side of it meets across one
2670    /// boundary, as if the comment were not there.
2671    fn block_or_hidden(
2672        &mut self,
2673        child: usize,
2674        before_sep: usize,
2675        pf: &[Glyph],
2676        pc: &[Glyph],
2677    ) -> bool {
2678        let after_sep = self.rows.len();
2679        self.block(child, pf, pc);
2680        if self.rows.len() > after_sep {
2681            return true;
2682        }
2683        self.rows.truncate(before_sep);
2684        let end = self.nodes[child].span.end;
2685        self.last_off = self.last_off.max(end);
2686        self.stepped_over = self.stepped_over.max(end);
2687        false
2688    }
2689
2690    /// Render an explicit, ordered list of top-level blocks — [`Builder::blocks`]
2691    /// for a walk that isn't "the children of one node". The document's top level
2692    /// no longer is: a footnote definition is a root beside `doc`, not under it,
2693    /// and [`top_level`] merges it into this list by source position.
2694    ///
2695    /// The separator between blocks is spelled by the same
2696    /// [`Builder::emit_separators_before`] the incremental top-level walk in
2697    /// [`build_cached`] uses, so the two paths can't drift on how a boundary
2698    /// looks.
2699    ///
2700    /// Returns the class of the last block that drew anything — what the
2701    /// trailing blank lines close — or `None` when nothing did.
2702    fn top_blocks(&mut self, ids: &[usize]) -> Option<BlockClass> {
2703        let mut above: Option<BlockClass> = None;
2704        for &child in ids {
2705            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
2706            let before_sep = self.rows.len();
2707            if let Some(above) = above {
2708                self.emit_separators_before(
2709                    self.nodes[child].span.start,
2710                    &[],
2711                    true,
2712                    Boundary { above, below },
2713                );
2714            }
2715            if self.block_or_hidden(child, before_sep, &[], &[]) {
2716                above = Some(below);
2717            }
2718        }
2719        above
2720    }
2721
2722    /// Emit the blank separator row(s) that sit between a block ending at the
2723    /// current `last_off` and the next block starting at `next_start`, wearing
2724    /// the continuation prefix `pc`. Shared by [`Builder::blocks`] and the
2725    /// incremental top-level walk so the two can't drift on how a boundary is
2726    /// spelled.
2727    ///
2728    /// The blank line(s) between two blocks are real caret stops, each needing
2729    /// its *own* source offset — one strictly past the previous block's content,
2730    /// else it collides with that block's last row and `pos_of_offset`
2731    /// (first-match-wins) would resolve the caret onto the wrong row, pinning
2732    /// downward motion there.
2733    ///
2734    /// One row *per* blank source line, not a single collapsed separator: an
2735    /// empty paragraph opened between two blocks (Enter in the gap,
2736    /// `…\n\n\n\n…`) must be a navigable empty row, not vanish — else the caret
2737    /// in it snaps onto the *next* block's start and Enter looks like it did
2738    /// nothing.
2739    fn emit_separators_before(
2740        &mut self,
2741        next_start: usize,
2742        pc: &[Glyph],
2743        synthetic: bool,
2744        boundary: Boundary,
2745    ) {
2746        let mut offs = self.blank_rows_between(self.last_off, next_start);
2747        if offs.is_empty() {
2748            if !synthetic {
2749                // A tight list item's own text sits directly above the sub-list
2750                // nested in it — no fabricated gap. The "breathe" row belongs
2751                // between free-standing blocks, not between an item and its
2752                // child list, which the source writes on the very next line. A
2753                // real blank source line (a loose list) still lands a gap below,
2754                // because `blank_rows_between` found it and we never reach here.
2755                return;
2756            }
2757            // A tight gap with no blank line (e.g. a heading directly above its
2758            // text): keep the one conventional separator row so blocks still
2759            // breathe, as they always have.
2760            offs.push(self.blank_line_offset(self.last_off, next_start));
2761        }
2762        let last = offs.len() - 1;
2763        for (k, end_src) in offs.into_iter().enumerate() {
2764            // Only the drawn-only rows carry the boundary: the navigable blank
2765            // lines between them (and every blank line under preserve-soft flow)
2766            // are somewhere text can go, not a gap between blocks, and a frontend
2767            // that shrank one would be shrinking a line the author is typing on.
2768            let drawn = !self.preserve_soft && (k == 0 || k == last);
2769            // The blank line a boundary is *drawn* with isn't a place text can
2770            // go. The first one closes the block above and the last one opens the
2771            // block below — with a single blank line, the usual case, doing both
2772            // at once. Typing on either just continues the paragraph it abuts,
2773            // since the blank line it would need to be a paragraph of its own is
2774            // the very line being typed on. So they're a gap, like a table's
2775            // border: drawn, clickable, never a caret's home.
2776            //
2777            // The lines *between* them are the real ones. That's what Enter
2778            // opens: it inserts a paragraph break (`\n\n`), which leaves a blank
2779            // line spare on each side and the caret on the navigable line
2780            // between them.
2781            //
2782            // Preserve flow is the exception: there a bare `\n` is a visible line
2783            // break the author edits directly, so a lone blank line *is* a caret
2784            // home — typing on it makes the soft break the mode exists to show,
2785            // and Enter at a line's end lands the caret on exactly this row. So no
2786            // separator is drawn-only; every blank line is navigable.
2787            self.rows.push(VRow {
2788                glyphs: pc.to_vec(),
2789                end_src,
2790                decoration: drawn,
2791                code: false,
2792                code_lang: None,
2793                directive: false,
2794                directive_label: None,
2795                media: None,
2796                task: None,
2797                leaf_directive: None,
2798                heading: None,
2799                align: None,
2800                line_height: None,
2801                boundary: drawn.then_some(boundary),
2802                mark_ends: Vec::new(),
2803            });
2804        }
2805    }
2806
2807    /// One block, drawn under whatever presentation the containers around it
2808    /// impose.
2809    ///
2810    /// A container named `div` with `Element` origin is transparent already —
2811    /// its children draw as themselves — and it now also *contributes* its
2812    /// vocabulary keys to every block it holds. That is the reading side of
2813    /// twig's own rule for where a Markdown block's attributes live: there is
2814    /// no attribute syntax to put on the paragraph, so `set_block_attrs` writes
2815    /// a `<div …>` around it, and reading one back has to look through the div.
2816    /// `<div class="center">` around three paragraphs centres all three, which
2817    /// is what the author of that HTML meant, and around one is the sole-child
2818    /// shape twig writes.
2819    ///
2820    /// Saved and restored rather than pushed onto a stack, so a nested div
2821    /// reads its own keys over its parent's and the block *after* the div is
2822    /// unaffected.
2823    fn block(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
2824        if element_tag(&self.nodes[id]) == Some("div") {
2825            let saved = self.presentation;
2826            self.presentation = saved.under(&self.nodes[id].attrs);
2827            self.block_kind(id, pf, pc);
2828            self.presentation = saved;
2829            return;
2830        }
2831        self.block_kind(id, pf, pc);
2832    }
2833
2834    fn block_kind(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
2835        let node = &self.nodes[id];
2836        match node.kind.as_str() {
2837            "doc" | "section" => self.blocks(id, pf, pc, false),
2838            "heading" => {
2839                // A heading whose only visible content is a single image — a
2840                // banner set in an `<h1>` (`<h1><picture><img></picture></h1>`),
2841                // or `# ![](banner.png)` — is a block picture, not text. Render
2842                // it as one; anything with real heading text falls through.
2843                if let Some((m, kind)) = self.media_only(id) {
2844                    self.block_media(m, kind, id, pf);
2845                    return;
2846                }
2847                let level = node.level.unwrap_or(1);
2848                // A `data-size` on a heading scales the *heading's* ramp, not
2849                // the body's — the role and the step compose rather than
2850                // compete, which is the same thing a colour does to a link.
2851                let pres = self.presentation.under(&node.attrs);
2852                let style = pres.over(heading_style(level));
2853                let mut glyphs = Vec::new();
2854                // On the revealed line the `# ` comes back as real, editable
2855                // text in front of the heading. Only the opening marker: a
2856                // closing `#`-run (`## title ##`) is covered by the same
2857                // `delims` pair, and a setext underline is excluded there for
2858                // being on another line entirely.
2859                if let Some((open, close)) =
2860                    self.revealed(&node.span).then(|| self.delims(id)).flatten()
2861                {
2862                    self.push_delim(&mut glyphs, &open, style);
2863                    glyphs.extend(self.inline_children_with_trailing(id, style));
2864                    self.push_delim(&mut glyphs, &close, style);
2865                } else {
2866                    glyphs = self.inline_children_with_trailing(id, style);
2867                }
2868                // An *empty* heading — `# ` with nothing typed after it, which is
2869                // what the toolbar's H1 leaves on a blank line — has no glyph for
2870                // its row to end on, so the fallback below is the row's whole
2871                // extent: its only caret stop, and the offset every row after it
2872                // is measured from. The block's start is the wrong answer for
2873                // both, because it sits *in front of* the `# ` the rich view
2874                // hides: the caret drew (and typed) before the hashes, and the
2875                // rows below inherited an offset short by the marker's length,
2876                // which put the caret on one of them the moment the heading grew
2877                // text. Its content's start is where the caret belongs.
2878                let home = heading_content_start(self.source, &node.span);
2879                let first = self.rows.len();
2880                self.emit_wrapped(glyphs, home, pf, pc);
2881                // Stamp the level on every row the heading just emitted — a
2882                // wrapped heading's continuation rows as much as its first, and
2883                // an empty one's single glyphless row, which is the whole point
2884                // (see [`VRow::heading`]).
2885                for row in &mut self.rows[first..] {
2886                    row.heading = Some(level.min(255) as u8);
2887                    row.align = pres.align;
2888                    row.line_height = pres.line_height;
2889                }
2890            }
2891            "block_quote" => {
2892                let (start, end) = (node.span.start, node.span.end);
2893                let gutter = synth("│ ", Role::QuoteGutter, start);
2894                let f = concat(pf, &gutter);
2895                let c = concat(pc, &gutter);
2896                // A childless quote — a bare `> ` on an otherwise blank line,
2897                // which is what the toolbar's Quote button leaves there — has no
2898                // inner block to carry the gutter or a caret home, so `blocks`
2899                // emitted *nothing at all*: the quote didn't merely draw
2900                // unstyled, it disappeared, and a document that was only `> `
2901                // rendered zero rows with the caret nowhere to stand. Emit the
2902                // gutter row itself, ending just past the marker, exactly as an
2903                // empty `list_item` emits its bare bullet.
2904                if self.children(id).is_empty() {
2905                    self.push_row_at(f, end.min(self.source.len()));
2906                } else {
2907                    self.blocks(id, &f, &c, false);
2908                    self.emit_quote_trailing_lines(&c, end);
2909                }
2910            }
2911            // A generic `:::name{.class}` fenced-div container (twig's
2912            // `directive`, container form). Core is agnostic of `name` — it's
2913            // the host app's vocabulary (diaryx's `vis` for audience
2914            // visibility, say) and isn't available here regardless: twig only
2915            // threads an `element`'s tag name through `FlatNode::name`, not a
2916            // directive's own identifier. Every row gets marked `directive` (a
2917            // frontend draws a tinted panel around each maximal run, the
2918            // `code`/`code_block` recipe) and the first row carries a label —
2919            // the way a code fence's language rides only its first row.
2920            //
2921            // The label reads BOTH attribute conventions diaryx content
2922            // actually uses: twig's own dot-prefixed classes (`{.public
2923            // .family}`, one combined `class` attr) and bare pandoc-style
2924            // words with no leading dot (`{public family}` — the syntax
2925            // `diaryx_core::visibility`'s hand-rolled publish-time filter and
2926            // apps/web's directive serializer both write; twig parses each
2927            // bare word as its own attribute with an empty value, per
2928            // `languages/markdown/attributes.zig`). Reading only `.class`
2929            // would leave every *existing* diaryx `:::vis{...}` block
2930            // unlabeled.
2931            // Only the *container* form is the panel below. A `text` directive
2932            // is inline and never reaches the block walker (see `is_inline`); a
2933            // `leaf` one is a standalone block with no body, drawn as a
2934            // placeholder the way an image is.
2935            "container"
2936                if container_is_directive(node)
2937                    && node.directive_form == Some(DirectiveForm::Leaf) =>
2938            {
2939                self.block_directive(id, pf);
2940            }
2941            // djot has no *leaf* directive form. `insert_directive` spells the
2942            // same document as an empty `::: page-break` fence — a container
2943            // with nothing in it — and the name comes back as the fence's one
2944            // class rather than as the node's name, because djot's div is
2945            // anonymous. Draw it as the placeholder Markdown's `::page-break`
2946            // gets, so a frontend that paginates on a `page-break`
2947            // [`DirectiveMark`] cannot tell which format the file is in.
2948            //
2949            // Narrow on purpose: only an *anonymous* empty fence. A Markdown
2950            // `:::note` with nothing in it keeps the reading it has, because
2951            // its name is its own and nothing about it says "a block with no
2952            // body" the way djot's spelling of a leaf directive does.
2953            "container"
2954                if container_is_directive(node)
2955                    && node.directive_form == Some(DirectiveForm::Container)
2956                    && node.name.as_deref().unwrap_or_default().is_empty()
2957                    && self.children(id).is_empty()
2958                    && !leaf_directive_identity(node).0.is_empty() =>
2959            {
2960                self.block_directive(id, pf);
2961            }
2962            "container" if container_is_directive(node) => {
2963                let label = directive_attr_label(&node.attrs);
2964                let start_row = self.rows.len();
2965                self.blocks(id, pf, pc, false);
2966                for (i, row) in self.rows[start_row..].iter_mut().enumerate() {
2967                    row.directive = true;
2968                    if i == 0 {
2969                        row.directive_label = label.clone();
2970                    }
2971                }
2972                // Anchor the block's end past its closing `:::` fence, exactly as
2973                // the code-block arm anchors past its ```` ``` ````. A container's
2974                // last content row ends at its last *child*, before the fence and
2975                // the blank line under it, so the separator logic counted the
2976                // fence line as a blank row of its own and drew a second boundary
2977                // — one gap's worth of margin twice, under every fenced div.
2978                self.last_off = node.span.end;
2979            }
2980            "bullet_list" | "ordered_list" | "task_list" => {
2981                let ordered = node.kind == Kind::OrderedList;
2982                let mut item_no = 0usize;
2983                let kids = self.children(id);
2984                for (i, child) in kids.iter().copied().enumerate() {
2985                    let kind = &self.nodes[child].kind;
2986                    if *kind == Kind::ListItem || *kind == Kind::TaskListItem {
2987                        let start = self.nodes[child].span.start;
2988                        item_no += 1;
2989                        // A task item's box replaces the bullet rather than
2990                        // joining it. The `[ ] ` that spells it is markup twig
2991                        // has already consumed — the item's paragraph *content*
2992                        // starts past it — so without a drawn box a task item
2993                        // was indistinguishable from a plain bullet, ticked or
2994                        // not. `☐`/`☑` is the marker for the same reason `•` is:
2995                        // it stands where the source's own marker stands. Which
2996                        // way it faces is `checked`, straight off the node.
2997                        let checked = self.nodes[child].checked;
2998                        let marker = match (checked, ordered) {
2999                            (Some(true), _) => "☑ ".to_string(),
3000                            (Some(false), _) => "☐ ".to_string(),
3001                            (None, true) => format!("{item_no}. "),
3002                            (None, false) => "• ".to_string(),
3003                        };
3004                        let bullet = synth(&marker, Role::ListMarker, start);
3005                        let indent = synth(&" ".repeat(text_width(&marker)), Role::Body, start);
3006                        let first_row = self.rows.len();
3007                        self.block(child, &concat(pc, &bullet), &concat(pc, &indent));
3008                        // On the item's first row, the way `code_lang` rides the
3009                        // first row of its block.
3010                        if let (Some(c), Some(row)) = (checked, self.rows.get_mut(first_row)) {
3011                            row.task = Some(c);
3012                        }
3013                    } else {
3014                        // twig can nest a *following* top-level block as a direct
3015                        // child of the list rather than a sibling of it — e.g.
3016                        // `- item\n\n> quote` parses the block quote under the
3017                        // `bullet_list`. It isn't a list item, so render it de-nested:
3018                        // no bullet, at the list's own prefix, with the usual block
3019                        // separator — never `• │ quote`.
3020                        if i > 0 {
3021                            self.emit_separators_before(
3022                                self.nodes[child].span.start,
3023                                pc,
3024                                true,
3025                                Boundary {
3026                                    above: BlockClass::from_node_kind(
3027                                        &self.nodes[kids[i - 1]].kind,
3028                                    ),
3029                                    below: BlockClass::from_node_kind(&self.nodes[child].kind),
3030                                },
3031                            );
3032                        }
3033                        self.block(child, pc, pc);
3034                    }
3035                }
3036            }
3037            "list_item" | "task_list_item" => {
3038                // A childless item — the empty bullet you get the instant you
3039                // press Enter to open a new one — has no inner block to carry the
3040                // marker prefix or a caret home, so `blocks` would emit nothing
3041                // and the new bullet simply wouldn't appear until something was
3042                // typed into it. Emit the prefixed row itself, ending at a caret
3043                // stop just past the marker (the item's `span.end`), the way an
3044                // empty paragraph emits its one prefixed row via `emit_wrapped`.
3045                if self.children(id).is_empty() {
3046                    let home = self.nodes[id].span.end.min(self.source.len());
3047                    self.push_row_at(pf.to_vec(), home);
3048                } else {
3049                    // Tight: an item's text and the list nested under it butt
3050                    // together (`• a` / `  • b`), no fabricated blank row between —
3051                    // a loose item's real blank line still parts them.
3052                    self.blocks(id, pf, pc, true);
3053                }
3054            }
3055            // A footnote *definition* (`[^1]: the note`). It reaches this walker
3056            // only because [`top_level`] merges it back in — twig hangs it off no
3057            // parent at all, so a walk from `doc` never sees one and every byte
3058            // of its body used to render as nothing.
3059            //
3060            // Drawn as a hanging-indent item, the way a list item is: the marker
3061            // reads `[1] `, matching the `[1]` its references render as, so the
3062            // two can be paired by eye, and the body wraps under it. The marker
3063            // is synthetic decoration (one shared offset, never a caret stop) —
3064            // the `[^1]: ` that spells it in the source is markup, hidden like a
3065            // heading's `# `.
3066            "footnote" => {
3067                let (start, end) = (node.span.start, node.span.end);
3068                let source = self.source;
3069                let marker = format!("[{}] ", footnote_label(source, start).unwrap_or(""));
3070                let indent = " ".repeat(text_width(&marker));
3071                let f = concat(pf, &synth(&marker, Role::ListMarker, start));
3072                let c = concat(pc, &synth(&indent, Role::Body, start));
3073                if self.children(id).is_empty() {
3074                    // A definition with no body yet — the instant `[^1]: ` has
3075                    // been typed and nothing after it. `blocks` would emit
3076                    // nothing and the definition simply wouldn't appear, so emit
3077                    // the marker row itself with a caret home just past it,
3078                    // exactly as an empty list item does.
3079                    self.push_row_at(f, end.min(source.len()));
3080                } else {
3081                    self.blocks(id, &f, &c, false);
3082                }
3083            }
3084            // A link reference definition (`[foo]: /url`): resolved by label
3085            // into the links that use it, and drawn nowhere — the rich view has
3086            // no more use for its line than for a comment's. It is walked at all
3087            // (see [`top_level`]) so [`Builder::block_or_hidden`] can step the
3088            // walk past its bytes rather than count them as blank lines.
3089            "reference" => {}
3090            "table" => self.table(id, pf, pc),
3091            "code_block" => {
3092                let style = Style::default().role(Role::Code);
3093                let text = node.text.clone().unwrap_or_default();
3094                // Cut the block's *terminator*, not every trailing newline. A
3095                // block whose last line is empty spells that as a second `\n`,
3096                // and `trim_end_matches` ate it along with the terminator: the
3097                // Return that made the line got no row, so the caret placed on
3098                // it fell through to the paragraph below and typing landed
3099                // outside the block. twig's `content_span` is `text` less
3100                // exactly this one newline, so cutting one and no more is also
3101                // what keeps `code_line_offsets` lined up.
3102                let lines: Vec<&str> = text
3103                    .strip_suffix('\n')
3104                    .unwrap_or(text.as_str())
3105                    .split('\n')
3106                    .collect();
3107                // Each line at its own source offset, so the caret can walk the
3108                // code a character at a time like any other text. Where the
3109                // lines can't be lined up with the source there's no honest
3110                // offset to give, so the block maps coarsely to its start (and
3111                // stays a source-view job, as all of it once was).
3112                let offs = node
3113                    .content_span
3114                    .as_ref()
3115                    .and_then(|c| self.code_line_offsets(c, &lines));
3116                // The fence's info string, carried on the block's first row as
3117                // its language label (`None` for an indented block or a bare
3118                // fence). Kept on the row so it rides the block cache.
3119                let lang = code_language(self.source, node.span.start);
3120                // The block's syntax highlighting, a token per byte range of
3121                // each line — `None` unless the fence names a language the
3122                // grammars know (and unless the `syntax` feature is on). Done
3123                // here, once per build of the block, because the rows it
3124                // colours ride the block cache: an edit elsewhere in the
3125                // document reuses them, tokens and all.
3126                let tokens = lang.as_deref().and_then(|l| code_tokens(l, &lines));
3127                for (i, raw) in lines.iter().enumerate() {
3128                    let at = offs.as_ref().map_or(node.span.start, |o| o[i]);
3129                    // No gutter glyph: the block is set apart by the border and
3130                    // tint a frontend draws around the whole run of `code` rows,
3131                    // not by a per-line mark. Just the block prefix (a list
3132                    // indent, a quote gutter) and the code text.
3133                    let mut glyphs: Vec<Glyph> = pf.to_vec();
3134                    match tokens.as_ref().and_then(|t| t.get(i)) {
3135                        Some(spans) => push_code_text(&mut glyphs, raw, at, style, spans),
3136                        None => push_text(&mut glyphs, raw, at, style),
3137                    }
3138                    // Explicitly past the line's *text*: a blank code line has no
3139                    // glyph, and any prefix's offset would put the row's end
3140                    // inside the next line.
3141                    self.push_row_at(glyphs, at + raw.len());
3142                    if let Some(row) = self.rows.last_mut() {
3143                        row.code = true;
3144                        if i == 0 {
3145                            row.code_lang = lang.clone();
3146                        }
3147                    }
3148                }
3149                // Anchor the block's end past its closing fence. Its last content
3150                // row ends at the last code line, before the ``` and the blank
3151                // line under it; without this the separator logic would count the
3152                // closing-fence line as its own blank row and open a phantom
3153                // second gap below the block.
3154                self.last_off = node.span.end;
3155            }
3156            "thematic_break" => {
3157                let full = self.wrap.unwrap_or(UNWRAPPED_RULE_WIDTH);
3158                let w = full.saturating_sub(prefix_width(pf)).max(4);
3159                let mut glyphs = pf.to_vec();
3160                for _ in 0..w {
3161                    glyphs.push(Glyph {
3162                        ch: '─',
3163                        style: Style::default().role(Role::Rule),
3164                        src: node.span.start,
3165                        // A rule is a block the caret can sit on, as it always
3166                        // has; it maps coarsely to the block's start.
3167                        stop: true,
3168                    });
3169                }
3170                // The dashes share one caret home in front of the atomic block,
3171                // while the row's end is the second home just past its source.
3172                // Without that trailing stop a final rule made the document end
3173                // unreachable: Right could not cross it and a click in the
3174                // empty space below it snapped back before the rule.
3175                let after_line = node.span.end
3176                    + self.source[node.span.end..]
3177                        .strip_prefix("\r\n")
3178                        .map_or_else(
3179                            || usize::from(self.source[node.span.end..].starts_with('\n')),
3180                            |_| 2,
3181                        );
3182                self.push_row_at(glyphs, after_line);
3183            }
3184            // A block-level image node with no wrapping paragraph — a promoted
3185            // top-level HTML `<img>` lands as a direct `doc` child like this
3186            // (a Markdown `![](…)` comes wrapped in a `para`, handled below).
3187            "image" => self.block_media(id, MediaKind::Image, id, pf),
3188            // The same case for a promoted top-level `<video>`/`<audio>`, which
3189            // arrives as a generic `container` rather than a node kind of its
3190            // own. It can't be found by the `media_only` scan below the way a
3191            // wrapped one is: that scan looks at a wrapper's *children*, and here
3192            // the media element is itself the block.
3193            "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
3194                let kind = match element_tag(node) {
3195                    Some("audio") => MediaKind::Audio,
3196                    _ => MediaKind::Video,
3197                };
3198                self.block_media(id, kind, id, pf);
3199            }
3200            _ => {
3201                // A container of blocks, or an inline-bearing paragraph.
3202                let kids = self.children(id);
3203                // A block-level image: a paragraph (or other wrapper — a
3204                // `<picture>`, an `<h1>` banner) whose only visible content is a
3205                // single `image` node. Render it as a placeholder row + record an
3206                // [`MediaInfo`] a capable frontend replaces. An image mixed with
3207                // real text or other images on the line isn't block-level and
3208                // falls through to the inline path below, still as its alt text.
3209                if let Some((m, kind)) = self.media_only(id) {
3210                    self.block_media(m, kind, id, pf);
3211                    return;
3212                }
3213                let inline = !kids.is_empty() && kids.iter().all(|&c| is_inline(&self.nodes[c]));
3214                if inline || kids.is_empty() {
3215                    // The block's own attributes over its containers' — the
3216                    // three run-level keys become the style its glyphs start
3217                    // from, and the two line-level ones ride every row it
3218                    // emits, a wrapped paragraph's continuations included.
3219                    let pres = self.presentation.under(&node.attrs);
3220                    let glyphs =
3221                        self.inline_children_with_trailing(id, pres.over(Style::default()));
3222                    if !glyphs.is_empty() {
3223                        let first = self.rows.len();
3224                        self.emit_wrapped(glyphs, node.span.start, pf, pc);
3225                        for row in &mut self.rows[first..] {
3226                            row.align = pres.align;
3227                            row.line_height = pres.line_height;
3228                        }
3229                    }
3230                } else {
3231                    self.blocks(id, pf, pc, false);
3232                }
3233            }
3234        }
3235    }
3236
3237    /// Render a table as a box-drawn grid: every column as wide as its widest
3238    /// cell, the header bold and ruled off, each cell padded to its column's
3239    /// alignment. This is the *default* monospace rendering (see
3240    /// [`VisualMap::rows`]); the same cells are also published structurally as
3241    /// [`TableInfo`], so a frontend that lays the grid out in its own units draws
3242    /// from there and skips the picture built here.
3243    ///
3244    /// The alignment comes from twig's `cell.alignment` — the delimiter row
3245    /// (`|:--|--:|`) that spells it out is consumed by the parser and leaves no
3246    /// node, so the snapshot is the only source for it.
3247    ///
3248    /// Borders and padding are *decoration*: they carry the source offset of the
3249    /// text they surround, so a click lands in that cell, but they're never
3250    /// caret stops — the caret steps cell-to-cell instead of into the box art.
3251    fn table(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
3252        let node_end = self.nodes[id].span.end;
3253        // twig's shape is `[caption, row, row, …]`: the caption is always
3254        // present (usually empty in Markdown) and is not part of the grid.
3255        let row_ids: Vec<usize> = self
3256            .children(id)
3257            .into_iter()
3258            .filter(|&c| self.nodes[c].kind == Kind::Row)
3259            .collect();
3260        if row_ids.is_empty() {
3261            return;
3262        }
3263        // Lay every cell out first — the column widths depend on all of them.
3264        let grid: Vec<Vec<TableCell>> = row_ids.iter().map(|&r| self.row_cells(r)).collect();
3265        let heads: Vec<bool> = row_ids
3266            .iter()
3267            .map(|&r| self.nodes[r].head.unwrap_or(false))
3268            .collect();
3269        let cols = grid.iter().map(|r| r.len()).max().unwrap_or(0);
3270        if cols == 0 {
3271            return;
3272        }
3273        let mut widths = vec![0usize; cols];
3274        for row in &grid {
3275            for (c, cell) in row.iter().enumerate() {
3276                widths[c] = widths[c].max(cell_width(&cell.glyphs));
3277            }
3278        }
3279        // Every column at its widest cell is only the *wish*; a grid wider than
3280        // the surface has its far side hanging off the edge where no amount of
3281        // caret motion can reach it. Cut it down to what's actually there, and
3282        // let the cells wrap into the space they're given.
3283        if let Some(w) = self.wrap {
3284            fit_widths(&mut widths, w.saturating_sub(prefix_width(pc)));
3285        }
3286
3287        // Where the picture starts, so a frontend drawing its own grid knows
3288        // which rows to skip. Recorded before the first border goes down.
3289        let rows_start = self.rows.len();
3290
3291        let anchor = grid[0].first().map(|c| c.start).unwrap_or(node_end);
3292        self.push_rule(&rule_text(&widths, '┌', '┬', '┐'), anchor, pf);
3293        for (ri, row) in grid.iter().enumerate() {
3294            self.push_table_row(row, &widths, pc);
3295            // The rule under the header: only where the head actually ends.
3296            let ends_head = heads[ri] && heads.get(ri + 1) == Some(&false);
3297            if ends_head {
3298                let next = grid[ri + 1].first().map(|c| c.start).unwrap_or(node_end);
3299                self.push_rule(&rule_text(&widths, '├', '┼', '┤'), next, pc);
3300            }
3301        }
3302        // The bottom border is the one rule the caret can rest on: its end is
3303        // the table's trailing stop, the caret home just past the block — the
3304        // peer of a block picture's second stop, and of a rule's row end. Without
3305        // it a document ending in a table ended *inside* it: nothing after the
3306        // last cell was a stop, so Right could not leave the table, and a click
3307        // in the blank space under it snapped back into the last cell — or, on a
3308        // surface that resolved the click onto the border row, to the table's
3309        // first cell, since a decoration row's only stop is the nearest one.
3310        // Typing at the stop opens a paragraph first, as at a picture's — see
3311        // `Doc::open_paragraph_at_block_edge`. The glyphs stay non-stops at
3312        // `node_end`, so a click anywhere on the border lands past the table.
3313        self.push_rule_with_home(&rule_text(&widths, '└', '┴', '┘'), node_end, pc);
3314
3315        // The same cells the picture above was drawn from, published unwrapped
3316        // and unpadded for a frontend that lays them out in pixels.
3317        self.tables.push(TableInfo {
3318            rows_span: rows_start..self.rows.len(),
3319            end_src: node_end,
3320            // The *continuation* prefix: `pf` opens the block and only its first
3321            // row wears it, but every row of a grid is a continuation of the
3322            // block the table sits in.
3323            prefix: pc.to_vec(),
3324            grid: grid
3325                .into_iter()
3326                .zip(heads)
3327                .map(|(cells, head)| TableRow { head, cells })
3328                .collect(),
3329        });
3330        // The table's own end anchors whatever separator follows it; the border
3331        // rows deliberately don't move `last_off` (they hold no content).
3332        self.last_off = node_end;
3333    }
3334
3335    /// One row of laid-out cells, in column order.
3336    fn row_cells(&self, row: usize) -> Vec<TableCell> {
3337        // A cell is one source line, so a break within it is an explicit line
3338        // break (an inline `<br>`) that must render as a line of its own — not the
3339        // flow-folding space a break is in prose.
3340        self.break_glyph.set('\n');
3341        let cells = self
3342            .children(row)
3343            .into_iter()
3344            .filter(|&c| self.nodes[c].kind == Kind::Cell)
3345            .enumerate()
3346            .map(|(col, c)| {
3347                let n = &self.nodes[c];
3348                let style = if n.head.unwrap_or(false) {
3349                    Style::default().bold()
3350                } else {
3351                    Style::default()
3352                };
3353                // Only `content_span` bounds a cell's text, and an EMPTY cell
3354                // has none at all — twig records no interior for it — so both
3355                // offsets would fall back to the cell's `span.start`: on the
3356                // pipe that opens it, or (under a twig that gave every cell
3357                // the whole row's span) the row's start, where every empty
3358                // cell collapses onto one spot before the first `│` and a
3359                // caret there types *before* the table. Derive the interior
3360                // from the span's own pipes and this cell's column instead,
3361                // so each empty cell has a distinct, editable caret home.
3362                let span = n.content_span.clone().unwrap_or_else(|| {
3363                    let off = empty_cell_offset(
3364                        &self.source[n.span.start.min(self.source.len())
3365                            ..n.span.end.min(self.source.len())],
3366                        n.span.start,
3367                        col,
3368                    );
3369                    off..off
3370                });
3371                TableCell {
3372                    glyphs: self.inline_children(c, style),
3373                    start: span.start,
3374                    end: span.end,
3375                    align: n.alignment.unwrap_or(Alignment::Default),
3376                }
3377            })
3378            .collect();
3379        self.break_glyph.set(' ');
3380        cells
3381    }
3382
3383    /// A horizontal rule between/around rows — entirely decoration.
3384    fn push_rule(&mut self, text: &str, src: usize, prefix: &[Glyph]) {
3385        self.push_rule_row(text, src, prefix, true);
3386    }
3387
3388    /// A table's bottom border: drawn like the other rules, but a row the caret
3389    /// can rest on, its end (`src`) being the table's trailing stop.
3390    fn push_rule_with_home(&mut self, text: &str, src: usize, prefix: &[Glyph]) {
3391        self.push_rule_row(text, src, prefix, false);
3392    }
3393
3394    fn push_rule_row(&mut self, text: &str, src: usize, prefix: &[Glyph], decoration: bool) {
3395        let glyphs = concat(prefix, &synth(text, Role::Rule, src));
3396        self.rows.push(VRow {
3397            glyphs,
3398            end_src: src,
3399            decoration,
3400            code: false,
3401            code_lang: None,
3402            directive: false,
3403            directive_label: None,
3404            media: None,
3405            task: None,
3406            leaf_directive: None,
3407            heading: None,
3408            align: None,
3409            line_height: None,
3410            boundary: None,
3411            mark_ends: Vec::new(),
3412        });
3413    }
3414
3415    /// One `│ a │ b │` row of the grid: real cell text between decoration.
3416    ///
3417    /// A row of cells is not a row of the screen — a cell wrapped to its column
3418    /// spans several, each one `│`-divided across the full width so the grid
3419    /// stays square. Cells in the same row are laid out independently and run
3420    /// out at their own heights; a column that has run dry pads out as
3421    /// decoration while its neighbours keep going.
3422    fn push_table_row(&mut self, cells: &[TableCell], widths: &[usize], prefix: &[Glyph]) {
3423        let fallback = cells.last().map(|c| c.end).unwrap_or(0);
3424        let laid: Vec<Vec<Vec<Glyph>>> = cells
3425            .iter()
3426            .enumerate()
3427            .map(|(ci, c)| wrap_glyphs(&c.glyphs, widths.get(ci).copied().unwrap_or(0)))
3428            .collect();
3429        let height = laid.iter().map(|l| l.len()).max().unwrap_or(1).max(1);
3430
3431        for j in 0..height {
3432            let mut glyphs = prefix.to_vec();
3433            for (ci, &w) in widths.iter().enumerate() {
3434                let cell = cells.get(ci);
3435                let line = laid.get(ci).and_then(|l| l.get(j));
3436                // The divider before this column belongs to the cell it
3437                // introduces, so clicking it lands in that cell — on this line
3438                // of it, which is what's next to the divider being clicked.
3439                let at = line
3440                    .and_then(|l| l.first().map(|g| g.src))
3441                    .or_else(|| cell.map(|c| c.start))
3442                    .unwrap_or(fallback);
3443                glyphs.extend(synth("│", Role::Rule, at));
3444                match (cell, line) {
3445                    (Some(cell), Some(line)) => {
3446                        let pad = w.saturating_sub(glyphs_width(line));
3447                        let (lead, trail) = match cell.align {
3448                            Alignment::Right => (pad, 0),
3449                            Alignment::Center => (pad / 2, pad - pad / 2),
3450                            Alignment::Left | Alignment::Default => (0, pad),
3451                        };
3452                        // Every line renders at least one space after its text
3453                        // (the gutter before `│`), so there is always somewhere
3454                        // to put the "after the last character" caret a line
3455                        // needs. It's the one padding glyph that is a stop: on
3456                        // the cell's last line that's the cell's end, and on any
3457                        // other it's the space the wrap consumed.
3458                        let last = laid[ci].len() == j + 1;
3459                        let end = match last {
3460                            true => cell.end,
3461                            false => line
3462                                .last()
3463                                .map(|g| g.src + g.ch.len_utf8())
3464                                .unwrap_or(cell.end),
3465                        };
3466                        glyphs.extend(synth(&" ".repeat(lead + 1), Role::Body, at));
3467                        glyphs.extend(line.iter().cloned());
3468                        glyphs.push(Glyph {
3469                            ch: ' ',
3470                            style: Style::default(),
3471                            src: end,
3472                            stop: true,
3473                        });
3474                        glyphs.extend(synth(&" ".repeat(trail), Role::Body, end));
3475                    }
3476                    // A ragged row, or a column whose cell ended higher up: pad
3477                    // it out so the grid stays square.
3478                    _ => {
3479                        let at = cell.map(|c| c.end).unwrap_or(fallback);
3480                        glyphs.extend(synth(&" ".repeat(w + 2), Role::Body, at));
3481                    }
3482                }
3483            }
3484            glyphs.extend(synth("│", Role::Rule, fallback));
3485            // The row ends where its last stop does. A table row has no gap
3486            // between its final cell and the border, so inventing an end past
3487            // that would be a stop with nothing under it.
3488            let end_src = glyphs
3489                .iter()
3490                .rev()
3491                .find(|g| g.stop)
3492                .map_or(fallback, |g| g.src);
3493            let mark_ends = self.take_mark_ends(end_src);
3494            self.rows.push(VRow {
3495                glyphs,
3496                end_src,
3497                decoration: false,
3498                code: false,
3499                code_lang: None,
3500                directive: false,
3501                directive_label: None,
3502                media: None,
3503                task: None,
3504                leaf_directive: None,
3505                heading: None,
3506                align: None,
3507                line_height: None,
3508                boundary: None,
3509                mark_ends,
3510            });
3511        }
3512    }
3513
3514    /// Render a block-level image, video, or audio as one placeholder row: the
3515    /// `🖼 alt` / `🎬 alt` / `🔊 alt` label styled [`Role::Image`], every glyph
3516    /// mapped to the media's start offset and a caret stop there (they share the
3517    /// offset, so the stop table dedups them to a single home in front of it, as
3518    /// a rule's dashes do), and the row's end stop set past it so the caret can
3519    /// also rest after it. The row carries a [`MediaMark`] so [`media_spans`]
3520    /// publishes it as a [`MediaInfo`] a capable frontend replaces with the real
3521    /// picture or player; a plain surface paints the label as-is. `pf` is the
3522    /// block prefix (a list indent, a quote gutter) the row opens with, exactly
3523    /// as every other block honours it.
3524    fn block_media(&mut self, img: usize, kind: MediaKind, wrapper: usize, pf: &[Glyph]) {
3525        let node = &self.nodes[img];
3526        let start = node.span.start;
3527        let end = node.span.end;
3528        // An `image`'s URL is twig's `destination`; a `<video>`/`<audio>` is a
3529        // generic element, so its URL is the `src` attribute — and may be absent
3530        // entirely, the element naming its candidates in child `<source>`s.
3531        let destination = match kind {
3532            MediaKind::Image => node.destination.clone().unwrap_or_default(),
3533            MediaKind::Video | MediaKind::Audio => attr_of(node, "src").unwrap_or_default(),
3534        };
3535        let poster = match kind {
3536            MediaKind::Video => attr_of(node, "poster").unwrap_or_default(),
3537            MediaKind::Image | MediaKind::Audio => String::new(),
3538        };
3539        // The `<source>`s under the media element itself, not under `wrapper`: a
3540        // `<video>` is its own container, unlike an `<img>`, whose `<picture>`
3541        // alternatives are its *siblings* and so only reachable from the wrapper.
3542        let sources = match kind {
3543            MediaKind::Image => self.media_sources(wrapper),
3544            MediaKind::Video | MediaKind::Audio => self.media_sources(img),
3545        };
3546        let alt = self.image_alt(img);
3547        let sigil = kind.sigil();
3548        let label = if alt.is_empty() {
3549            // With no alt, name the file — but a `<video>` with neither `src` nor
3550            // alt has only its `<source>`s to be named by, so fall back to the
3551            // first candidate rather than labelling the row a bare sigil.
3552            let named = if destination.is_empty() {
3553                sources
3554                    .first()
3555                    .map(|s| s.srcset.as_str())
3556                    .unwrap_or_default()
3557            } else {
3558                &destination
3559            };
3560            format!("{sigil} {}", media_label(named))
3561        } else {
3562            format!("{sigil} {alt}")
3563        };
3564        let style = Style::default().role(Role::Image);
3565        let mut glyphs = pf.to_vec();
3566        for ch in label.chars() {
3567            glyphs.push(Glyph {
3568                ch,
3569                style,
3570                src: start,
3571                stop: true,
3572            });
3573        }
3574        // How many rows the frontend wants for this picture: the label row plus
3575        // the blank fillers below it. Absent (a GUI that lays images out in
3576        // pixels, an image that didn't resolve, or a plain surface) means the
3577        // bare one-row placeholder.
3578        let rows = self
3579            .media_rows
3580            .get(&destination)
3581            .copied()
3582            .unwrap_or(1)
3583            .max(1);
3584        // End past the image so the caret has a stop after it: the last glyph's
3585        // offset is the image *start*, not its extent, so `push_row`'s
3586        // last-glyph rule would strand the end stop inside the markup.
3587        self.push_row_at(glyphs, end);
3588        if let Some(row) = self.rows.last_mut() {
3589            row.media = Some(MediaMark {
3590                kind,
3591                destination,
3592                sources,
3593                alt,
3594                poster,
3595                rows,
3596            });
3597        }
3598        // Reserve the picture's remaining height as blank `decoration` rows: drawn
3599        // (so the frontend has the vertical room to paint the raster over them),
3600        // but holding no caret and contributing no stops — vertical motion steps
3601        // over them and the caret's only homes stay the stop in front of the image
3602        // and the one just past it, both on the label row above. They anchor at the
3603        // image's end offset so a click on the picture's lower half lands after it,
3604        // the nearest caret home. Mirrors how a table's box-rule rows reserve space
3605        // without ever holding the caret.
3606        for _ in 1..rows {
3607            self.rows.push(VRow {
3608                glyphs: Vec::new(),
3609                end_src: end,
3610                decoration: true,
3611                code: false,
3612                code_lang: None,
3613                directive: false,
3614                directive_label: None,
3615                media: None,
3616                task: None,
3617                leaf_directive: None,
3618                heading: None,
3619                align: None,
3620                line_height: None,
3621                boundary: None,
3622                mark_ends: Vec::new(),
3623            });
3624        }
3625        self.last_off = end;
3626    }
3627
3628    /// The `<picture>` alternatives inside block-image `wrapper`, in document
3629    /// order — every `<source>` element in its subtree. Empty when there's no
3630    /// `<picture>`. Each is a `<source>`'s `media` + `srcset`; core keeps them
3631    /// verbatim and picks none (see [`MediaSource`]). A `<source>` with no
3632    /// `srcset` is dropped (nothing to load); its `media` may be empty (an
3633    /// unconditional override), which a frontend treats as always-matching.
3634    ///
3635    /// It scans the wrapper's whole subtree (via the forward `first_child` /
3636    /// `next_sibling` links, the reliable ones) rather than the `<img>`'s parent,
3637    /// for two reasons. A `<picture>` reaches core in two shapes: twig promotes a
3638    /// block `<picture>` to an `element(picture)` wrapping `[source, img]`, but
3639    /// leaves an inline one's tags as raw siblings — `[raw "<picture>", source,
3640    /// img, raw "</picture>"]` — so the `<source>`s sit at different depths in
3641    /// the two. And the editor's flat arena leaves a promoted inline node's
3642    /// `parent` back-pointer dangling on a phantom root, so only the wrapper
3643    /// (known at the call site) is a trustworthy anchor. A block image is the
3644    /// sole visible content of its wrapper, so every `<source>` under it is its
3645    /// picture's.
3646    fn media_sources(&self, wrapper: usize) -> Vec<MediaSource> {
3647        let mut out = Vec::new();
3648        self.collect_sources(wrapper, &mut out);
3649        out
3650    }
3651
3652    fn collect_sources(&self, id: usize, out: &mut Vec<MediaSource>) {
3653        for c in self.children(id) {
3654            let node = &self.nodes[c];
3655            if node.name.as_deref() == Some("source") {
3656                // `<picture>` spells its candidate `srcset`, `<video>`/`<audio>`
3657                // spell it `src`. Both mean "the URL to load", so they normalise
3658                // onto one field; `srcset` wins where (illegally) both appear.
3659                let url = attr_of(node, "srcset").or_else(|| attr_of(node, "src"));
3660                if let Some(srcset) = url {
3661                    out.push(MediaSource {
3662                        media: attr_of(node, "media").unwrap_or_default(),
3663                        srcset,
3664                        mime: attr_of(node, "type").unwrap_or_default(),
3665                    });
3666                }
3667            }
3668            self.collect_sources(c, out);
3669        }
3670    }
3671
3672    /// The single block-level media `id`'s subtree resolves to, or `None`.
3673    ///
3674    /// A wrapper is a block picture when the only *visible* thing under it is one
3675    /// image: whitespace-only text and structure-only elements (a `<picture>`'s
3676    /// `<source>`, which declares an alternate but paints nothing) don't count,
3677    /// and the search descends through wrapping elements (`<picture>`, a linking
3678    /// `<a>`). This is what makes `<p><img></p>`, a bare `<img>`, and
3679    /// `<h1><picture>…<img></picture></h1>` all render as one framed picture.
3680    /// Any real text, or a second image, means it isn't image-only — it falls
3681    /// back to inline rendering, where the image still shows as its alt text.
3682    ///
3683    /// [`FlatNode`]'s snapshot doesn't carry an element's tag name, so a
3684    /// `<source>` can't be skipped by name — but it needs no special case:
3685    /// contributing no image and no text, it's simply invisible to the scan.
3686    fn media_only(&self, id: usize) -> Option<(usize, MediaKind)> {
3687        let mut found = None;
3688        let mut count = 0usize;
3689        let mut has_text = false;
3690        self.scan_visual(id, &mut found, &mut count, &mut has_text);
3691        (count == 1 && !has_text).then(|| found.unwrap())
3692    }
3693
3694    /// Walk `id`'s subtree tallying visible leaves for [`media_only`]: each
3695    /// image, `<video>`, or `<audio>` (remembering the last, counting the total)
3696    /// and whether any non-whitespace text appears. Media isn't descended into —
3697    /// an image's inline children are alt text, and a `<video>`'s are its
3698    /// no-support fallback and its `<source>` declarations, none of which is
3699    /// document content.
3700    ///
3701    /// [`media_only`]: Self::media_only
3702    fn scan_visual(
3703        &self,
3704        id: usize,
3705        found: &mut Option<(usize, MediaKind)>,
3706        count: &mut usize,
3707        has_text: &mut bool,
3708    ) {
3709        for c in self.children(id) {
3710            let node = &self.nodes[c];
3711            match node.kind.as_str() {
3712                "image" => {
3713                    *found = Some((c, MediaKind::Image));
3714                    *count += 1;
3715                }
3716                // A `<video>`/`<audio>` reaches core as a generic `container`
3717                // (twig gives neither a semantic node, so `html_elements`
3718                // promotion leaves the tag name on `name`). Counted as media and
3719                // *not* descended into, so its `<source>` children and its
3720                // "your browser does not support…" fallback text neither add a
3721                // second count nor make the block look like text.
3722                "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
3723                    let kind = match element_tag(node) {
3724                        Some("audio") => MediaKind::Audio,
3725                        _ => MediaKind::Video,
3726                    };
3727                    *found = Some((c, kind));
3728                    *count += 1;
3729                }
3730                // Text leaves: only non-whitespace counts as visible content.
3731                // (Twig keeps the whitespace `str`s between HTML tags — the
3732                // newlines and indentation inside a `<picture>` — as real nodes.)
3733                "str" | "smart_punctuation" | "verbatim" | "inline_math" => {
3734                    if node.text.as_deref().is_some_and(|t| !t.trim().is_empty()) {
3735                        *has_text = true;
3736                    }
3737                }
3738                // Structural breaks carry no visible glyph of their own.
3739                "soft_break" | "hard_break" | "non_breaking_space" => {}
3740                // Any other wrapper (emphasis, a link, a `<picture>`) is
3741                // transparent to the scan — descend into it.
3742                _ => self.scan_visual(c, found, count, has_text),
3743            }
3744        }
3745    }
3746
3747    /// A leaf directive (`::name{…}`) as one placeholder row — the
3748    /// [`block_media`](Self::block_media) recipe, for the same reason: it is a
3749    /// block that renders as *a thing*, not as text, and the frontend paints
3750    /// whatever the host app's vocabulary makes of it.
3751    ///
3752    /// The row's glyphs are a `⧉ label` (or `⧉ name`) stand-in a plain surface
3753    /// paints as-is, every glyph anchored at the directive's start with a caret
3754    /// stop there, and the row ending past it so the caret can also rest after
3755    /// it. It carries a [`DirectiveMark`] for [`directive_spans`], and is marked
3756    /// [`directive`](VRow::directive) so a frontend already drawing the
3757    /// container form's panel frames this one identically for free.
3758    ///
3759    /// Before this, a leaf directive emitted no rows at all: it was invisible,
3760    /// held no caret, and vertical motion crossed a void where it stood.
3761    fn block_directive(&mut self, id: usize, pf: &[Glyph]) {
3762        let node = &self.nodes[id];
3763        let (start, end) = (node.span.start, node.span.end);
3764        let (name, attrs) = leaf_directive_identity(node);
3765        let label = self.image_alt(id); // its `[label]` children, flattened
3766        let shown = if label.is_empty() { &name } else { &label };
3767        let style = Style::default().role(Role::Image);
3768        let mut glyphs = pf.to_vec();
3769        for ch in format!("⧉ {shown}").chars() {
3770            glyphs.push(Glyph {
3771                ch,
3772                style,
3773                src: start,
3774                stop: true,
3775            });
3776        }
3777        // End past the directive so the caret has a stop after it — the same
3778        // reason `block_media` anchors its row at the image's end.
3779        self.push_row_at(glyphs, end);
3780        if let Some(row) = self.rows.last_mut() {
3781            row.directive = true;
3782            row.leaf_directive = Some(DirectiveMark {
3783                name,
3784                attrs,
3785                label,
3786                rows: 1,
3787            });
3788        }
3789        self.last_off = end;
3790    }
3791
3792    /// An image's alt text: the flattened text of its inline descendants (an
3793    /// image's children *are* its alt content), empty when it has none. Also a
3794    /// leaf directive's `[label]`, which is the same shape — inline children
3795    /// standing for the block.
3796    fn image_alt(&self, id: usize) -> String {
3797        let mut out = String::new();
3798        self.collect_text(id, &mut out);
3799        out
3800    }
3801
3802    /// Append every descendant's `text` to `out`, in document order. Inline text
3803    /// (`str`) nodes are leaves, so a node never contributes both its own text and
3804    /// a child's — no double counting.
3805    fn collect_text(&self, id: usize, out: &mut String) {
3806        for c in self.children(id) {
3807            if let Some(t) = &self.nodes[c].text {
3808                out.push_str(t);
3809            }
3810            self.collect_text(c, out);
3811        }
3812    }
3813
3814    fn inline_children(&self, id: usize, base: Style) -> Vec<Glyph> {
3815        let mut out = Vec::new();
3816        for c in self.children(id) {
3817            self.inline(c, base, &mut out);
3818        }
3819        out
3820    }
3821
3822    /// [`inline_children`](Self::inline_children) plus any trailing whitespace the
3823    /// block carries past its inline content (see [`trailing_ws_glyphs`]). Used
3824    /// for the leaf inline blocks — paragraphs and headings — whose own `span`
3825    /// bounds exactly one line of text, so the trailing gap is theirs. *Not* for
3826    /// a table cell, whose `span` is the whole row and would swallow the
3827    /// delimiters and neighbours between it and the row's end.
3828    ///
3829    /// [`trailing_ws_glyphs`]: Self::trailing_ws_glyphs
3830    fn inline_children_with_trailing(&self, id: usize, base: Style) -> Vec<Glyph> {
3831        let mut out = self.inline_children(id, base);
3832        out.extend(self.trailing_ws_glyphs(id, base));
3833        out
3834    }
3835
3836    /// Glyphs for whatever trailing whitespace a block's source carries past its
3837    /// last inline node — the space(s) at the end of `hello ` that Markdown and
3838    /// Djot drop from the `str` node as insignificant. twig still records them:
3839    /// a block's `content_span` ends at its last meaningful character while its
3840    /// `span` runs to the end of the line's text (before the terminating
3841    /// newline), so the gap between the two *is* that trailing whitespace.
3842    ///
3843    /// Emitting it as real caret-stop glyphs is what lets the caret be drawn
3844    /// past the last visible character. Without it, typing a space at the end of
3845    /// a paragraph moved the caret in the source but not on screen — the caret
3846    /// stuck on the last glyph until the next visible character reparsed the
3847    /// space into an interior `str` node that finally carried it.
3848    ///
3849    /// Restricted to spaces: only they are safe to synthesize one-cell-per-byte,
3850    /// and only they are what the parser silently strips. Anything else in the
3851    /// gap means the span accounting isn't what this assumes, so it's left alone.
3852    fn trailing_ws_glyphs(&self, id: usize, style: Style) -> Vec<Glyph> {
3853        let node = &self.nodes[id];
3854        let Some(content) = &node.content_span else {
3855            return Vec::new();
3856        };
3857        let (from, to) = (content.end, node.span.end);
3858        let Some(slice) = (from < to).then(|| self.source.get(from..to)).flatten() else {
3859            return Vec::new();
3860        };
3861        if slice.is_empty() || slice.bytes().any(|b| b != b' ') {
3862            return Vec::new();
3863        }
3864        slice
3865            .bytes()
3866            .enumerate()
3867            .map(|(i, _)| Glyph {
3868                ch: ' ',
3869                style,
3870                src: from + i,
3871                stop: true,
3872            })
3873            .collect()
3874    }
3875
3876    fn inline(&self, id: usize, base: Style, out: &mut Vec<Glyph>) {
3877        let node = &self.nodes[id];
3878        match node.kind.as_str() {
3879            "str" | "smart_punctuation" => push_escaped_text(
3880                out,
3881                node.text.as_deref().unwrap_or(""),
3882                node.span.clone(),
3883                self.source,
3884                base,
3885            ),
3886            "soft_break" | "hard_break" | "non_breaking_space" => {
3887                // A break renders as a real, caret-navigable glyph — but twig
3888                // gives it no span of its own (`0..0`), so the offset comes from
3889                // the text in front of it: one *past* the last glyph, which is
3890                // the newline the break stands for. Past, not on: sharing the
3891                // previous glyph's offset would put two stops on one byte, and a
3892                // caret that can't change offset can't move.
3893                let src = if node.span.start != 0 {
3894                    node.span.start
3895                } else {
3896                    out.last().map(|g| g.src + g.ch.len_utf8()).unwrap_or(0)
3897                };
3898                // A *hard* break renders as this run's break glyph — a newline
3899                // inside a table cell (its own line), the same space in prose the
3900                // frontend re-wraps. A soft break normally folds into a space;
3901                // under `LineFlow::Preserve` it renders as a `'\n'` too, so the
3902                // author's line break shows where it was written. Never inside a
3903                // cell (`break_glyph` is `'\n'` there): a cell is one line and
3904                // folds its own soft breaks regardless.
3905                let ch = if node.kind == Kind::HardBreak {
3906                    self.break_glyph.get()
3907                } else if node.kind == Kind::SoftBreak
3908                    && self.preserve_soft
3909                    && self.break_glyph.get() == ' '
3910                {
3911                    '\n'
3912                } else {
3913                    ' '
3914                };
3915                out.push(Glyph {
3916                    ch,
3917                    style: base,
3918                    src,
3919                    stop: true,
3920                });
3921            }
3922            // A cell's only spelling for an in-line break is a raw `<br>`; read it
3923            // back as one (outside a cell it stays the literal text it falls to
3924            // below). The tag's bytes carry no stop of their own — the line it
3925            // ends stops just before it, the next just after.
3926            "raw_inline" if self.break_glyph.get() == '\n' && is_br(node.text.as_deref()) => {
3927                out.push(Glyph {
3928                    ch: '\n',
3929                    style: base,
3930                    src: node.span.start,
3931                    stop: true,
3932                });
3933            }
3934            "emph" => self.inline_delimited(id, base.italic(), out),
3935            "strong" => self.inline_delimited(id, base.bold(), out),
3936            // A coloured highlight's emoji is spelling, not content: twig strips
3937            // it and records the colour on the node, so the glyphs are the
3938            // author's words and the colour rides the role. Revealed markup
3939            // still shows the emoji, because `delims` reads the source bytes
3940            // between the span and the content span — which is exactly the
3941            // `==🔴 ` the author typed.
3942            "mark" => {
3943                let color = MarkColor::from_attrs(&node.attrs);
3944                self.inline_delimited(id, base.role(Role::Mark(color)), out)
3945            }
3946            "insert" => self.inline_delimited(id, base.underline(), out),
3947            "delete" => self.inline_delimited(id, base.strikethrough(), out),
3948            // The one pair whose whole meaning is *where the glyphs sit*. Drawn
3949            // in the surrounding style otherwise, so `^**2**^` stays bold and a
3950            // superscript inside a heading keeps the heading's role — which is
3951            // exactly why this is a `Baseline` and not a `Role`.
3952            "superscript" => self.inline_delimited(id, base.baseline(Baseline::Super), out),
3953            "subscript" => self.inline_delimited(id, base.baseline(Baseline::Sub), out),
3954            "verbatim" | "inline_math" => {
3955                // The interior begins at `content_span.start` — past however many
3956                // backticks the fence used, which `span.start + 1` only guessed
3957                // right for a single one. Fall back to that guess if it's absent.
3958                let at = node
3959                    .content_span
3960                    .as_ref()
3961                    .map_or(node.span.start + 1, |c| c.start);
3962                let style = base.role(Role::Code);
3963                // Not `inline_delimited`: verbatim has no child nodes to recurse
3964                // into — its content is its own `text` — so the fences bracket a
3965                // `push_text` instead. The fences themselves keep `Role::Code`'s
3966                // sibling treatment via `push_delim`'s role override.
3967                let show = self.revealed(&node.span).then(|| self.delims(id)).flatten();
3968                if let Some((open, _)) = &show {
3969                    self.push_delim(out, open, style);
3970                }
3971                push_text(out, node.text.as_deref().unwrap_or(""), at, style);
3972                match &show {
3973                    Some((_, close)) => self.push_delim(out, close, style),
3974                    None => self.note_mark_end(id),
3975                }
3976            }
3977            // An attributed span — the run-level half of the presentation
3978            // vocabulary. djot's `[text]{…}`, AsciiDoc's `[.a]#text#`, HTML's
3979            // and Markdown's `<span …>`: one node with a name twig hands back
3980            // for two of the four (see [`is_run_span`]), all four carrying the
3981            // author's `data-size`, `data-font` and `data-color` on the run
3982            // they cover.
3983            //
3984            // The keys are written over the surrounding style rather than
3985            // replacing it, so a span inside a block that names its own size
3986            // wins on size and keeps the block's face — the nearest-wins rule
3987            // the block walker applies through a `div`. A key the span does not
3988            // name is one the block still says.
3989            //
3990            // A `data-color` here is the text's *foreground*, where the same key
3991            // on a `mark` is a highlight's background: same vocabulary, same
3992            // enum, and no collision, because a `mark` is a `mark` and a span is
3993            // a span.
3994            //
3995            // Otherwise this is the plain `recurse` an anonymous container has
3996            // always had — no delimiters, because the `{…}` is markup and the
3997            // span's text is the author's words.
3998            "container" if is_run_span(node) && !self.children(id).is_empty() => {
3999                self.recurse(id, run_style(node, base), out)
4000            }
4001            // A text directive (`:name[label]{…}`) — the inline form of a generic
4002            // directive. Its `[label]` children are the visible text; the name and
4003            // the `{…}` attributes are the host app's vocabulary (diaryx's
4004            // `:vis[…]`) and stay hidden markup, exactly as a link's `](dest)` is.
4005            // Drawn in the surrounding style: a role of its own would need one
4006            // every frontend maps, and the bug this fixes is that the text was
4007            // invisible, not that it was unstyled.
4008            "container" if container_is_directive(node) && !self.children(id).is_empty() => {
4009                self.recurse(id, base, out)
4010            }
4011            // No `[label]`, so there are no children to render and recursing
4012            // emitted *nothing*: the directive's bytes vanished from the document
4013            // and left no caret stop behind. What to draw instead turns on
4014            // whether the syntax looks deliberate.
4015            //
4016            // Bare `:word` almost never is. twig matches a colon followed by any
4017            // letter-led word (`scanTextDirective`, deliberately matching remark),
4018            // so ordinary prose is full of them — `:see below`, a `:smile:`
4019            // shortcode, a stray colon before a word. Those are prose, and prose
4020            // renders as itself: every byte visible, every byte a caret stop, so a
4021            // colon typed by accident can be seen and deleted. Hiding them behind
4022            // a placeholder would be the invisible-and-unreachable failure this
4023            // arm exists to fix, just wearing a nicer glyph.
4024            "container" if container_is_directive(node) && node.attrs.is_empty() => {
4025                let span = node.span.clone();
4026                push_text(
4027                    out,
4028                    self.source.get(span.clone()).unwrap_or(""),
4029                    span.start,
4030                    base,
4031                );
4032            }
4033            // `{…}` attributes, though, are unmistakably deliberate — nobody
4034            // types `:vis{.family}` by accident, and diaryx writes exactly that
4035            // inline. So an attribute-bearing directive with no label draws as a
4036            // chip on `block_directive`'s recipe (`⧉ name attrs`, `Role::Image`),
4037            // the inline peer of the leaf form's placeholder row.
4038            //
4039            // Only the first glyph is a caret stop, and the whole chip shares the
4040            // directive's start offset: the caret treats it as one atomic thing
4041            // rather than walking hidden markup a byte at a time, and a paragraph
4042            // holding nothing but a chip still has a stop to be navigated to.
4043            "container" if container_is_directive(node) => {
4044                let start = node.span.start;
4045                let name = node.name.clone().unwrap_or_default();
4046                let shown = match directive_attr_label(&node.attrs) {
4047                    Some(attrs) if !name.is_empty() => format!("⧉ {name} {attrs}"),
4048                    Some(attrs) => format!("⧉ {attrs}"),
4049                    None => format!("⧉ {name}"),
4050                };
4051                let style = base.role(Role::Image);
4052                for (i, ch) in shown.chars().enumerate() {
4053                    out.push(Glyph {
4054                        ch,
4055                        style,
4056                        src: start,
4057                        stop: i == 0,
4058                    });
4059                }
4060            }
4061            // A footnote reference (`[^1]`). The label bracketed is what a reader
4062            // needs — bare, `note1` reads as a typo rather than a reference — so
4063            // the `^` is hidden as the spelling artefact it is (a link's
4064            // `](dest)` goes the same way) and the brackets are kept as
4065            // decoration: one shared offset, never a caret stop, like a table's
4066            // borders, so the caret walks the label alone.
4067            //
4068            // Styled `Role::Link`: a reference *is* a link to its definition, and
4069            // every frontend already paints that role. A role of its own would
4070            // need one in each of them, and what a frontend needs to tell the two
4071            // apart is not a paint colour but an answer to "what does clicking
4072            // here do" — which is [`Doc::footnote_at_caret`]'s job, not a glyph's.
4073            //
4074            // Raised, though, because that a reference is *set* differently from
4075            // the prose it interrupts is exactly what makes it read as a
4076            // reference. `[1]` at body size reads as bracketed text.
4077            "footnote_reference" => {
4078                let style = base.role(Role::Link);
4079                // Revealed, the reference is just its source bytes: the `^` that
4080                // is normally elided comes back and every byte becomes a real
4081                // stop, so the brackets stop being decoration and start being
4082                // text. That's the whole point of the mode, and it replaces the
4083                // hand-built chip below rather than decorating it — including the
4084                // raised baseline, since what's on screen there is source, and
4085                // source is set as prose.
4086                if self.revealed(&node.span) {
4087                    self.push_delim(out, &node.span, style);
4088                    return;
4089                }
4090                let style = style.baseline(Baseline::Super);
4091                // The label's own span, so its glyphs map to their true bytes.
4092                // Absent one, it starts past the `[^` that opens the reference.
4093                let (label, at) = match &node.content_span {
4094                    Some(c) => (self.source.get(c.clone()).unwrap_or(""), c.start),
4095                    None => (node.text.as_deref().unwrap_or(""), node.span.start + 2),
4096                };
4097                out.push(Glyph {
4098                    ch: '[',
4099                    style,
4100                    src: node.span.start,
4101                    stop: false,
4102                });
4103                push_text(out, label, at, style);
4104                out.push(Glyph {
4105                    ch: ']',
4106                    style,
4107                    src: node.span.end.saturating_sub(1),
4108                    stop: false,
4109                });
4110            }
4111            "link" | "url" | "email" => {
4112                let style = base.role(Role::Link);
4113                if self.children(id).is_empty() {
4114                    // A bare autolink (`<a@b.c>`, a naked URL): the destination
4115                    // *is* the visible text, so there is nothing elided to
4116                    // reveal and both modes draw the same thing.
4117                    push_text(
4118                        out,
4119                        node.destination
4120                            .as_deref()
4121                            .or(node.text.as_deref())
4122                            .unwrap_or("link"),
4123                        node.span.start,
4124                        style,
4125                    );
4126                } else {
4127                    // An inline link reveals asymmetrically — `[` before the
4128                    // label, `](dest)` after it — which the generic
4129                    // span-minus-content derivation already produces.
4130                    self.inline_delimited(id, style, out);
4131                }
4132            }
4133            _ => {
4134                if self.children(id).is_empty() {
4135                    if let Some(t) = &node.text {
4136                        push_text(out, t, node.span.start, base);
4137                    }
4138                } else {
4139                    self.recurse(id, base, out);
4140                }
4141            }
4142        }
4143    }
4144
4145    fn recurse(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
4146        for c in self.children(id) {
4147            self.inline(c, style, out);
4148        }
4149    }
4150
4151    /// Lay a block's inline `glyphs` into visual rows, prefixing the first with
4152    /// `pf` and the rest with `pc`. A preserved soft break arrives as a `'\n'`
4153    /// glyph (see the `soft_break` arm): a hard row boundary that splits the
4154    /// glyphs so each run lays out on its own and the author's line structure
4155    /// shows on screen. The `'\n'` is dropped from the row it closes and its
4156    /// source offset becomes that row's end stop — exactly how a table cell's
4157    /// in-line `<br>` is handled — so the caret can rest at the line's end
4158    /// without a zero-width control char leaking into what the frontends render.
4159    /// With no `'\n'` present (the folding default, and every build that isn't
4160    /// `LineFlow::Preserve`) there is one run and this is byte-identical to
4161    /// laying the glyphs out directly.
4162    fn emit_wrapped(&mut self, glyphs: Vec<Glyph>, block_start: usize, pf: &[Glyph], pc: &[Glyph]) {
4163        if !glyphs.iter().any(|g| g.ch == '\n') {
4164            self.emit_line(glyphs, block_start, pf, pc, None);
4165            return;
4166        }
4167        // Each run up to a '\n' is a line of its own: the first wears the block's
4168        // opening prefix, every later one the continuation prefix, and the break's
4169        // own offset ends the run's last row. The break glyph is dropped. A
4170        // trailing '\n' flushes its run and leaves nothing behind, so no spurious
4171        // blank row follows it.
4172        let mut run: Vec<Glyph> = Vec::new();
4173        let mut first = true;
4174        for g in glyphs {
4175            if g.ch == '\n' {
4176                let lead = if first { pf } else { pc };
4177                self.emit_line(std::mem::take(&mut run), block_start, lead, pc, Some(g.src));
4178                first = false;
4179            } else {
4180                run.push(g);
4181            }
4182        }
4183        if !run.is_empty() {
4184            let lead = if first { pf } else { pc };
4185            self.emit_line(run, block_start, lead, pc, None);
4186        }
4187    }
4188
4189    /// Word-wrap a single line of `glyphs` (no interior line breaks) to the
4190    /// available width and push the visual rows, prefixing the first with `pf`
4191    /// and the rest with `pc`. `end`, when set, is the source offset that ends
4192    /// the line's final row — the offset of the break that terminated it, which
4193    /// the caller has already stripped from `glyphs`; when `None` the row ends
4194    /// just past its last glyph, as an unbroken block's does.
4195    fn emit_line(
4196        &mut self,
4197        glyphs: Vec<Glyph>,
4198        block_start: usize,
4199        pf: &[Glyph],
4200        pc: &[Glyph],
4201        end: Option<usize>,
4202    ) {
4203        // The line's final row ends at `end` when a break gave one, else just
4204        // past its last glyph (`push_row`'s default).
4205        let push_last = |b: &mut Self, row: Vec<Glyph>| match end {
4206            Some(e) => b.push_row_at(row, e),
4207            None => b.push_row(row, block_start),
4208        };
4209
4210        // No column budget: emit the whole line as one row and let the frontend
4211        // wrap it at its own (pixel) width.
4212        let Some(width) = self.wrap else {
4213            let row = if glyphs.is_empty() {
4214                pf.to_vec()
4215            } else {
4216                concat(pf, &glyphs)
4217            };
4218            push_last(self, row);
4219            return;
4220        };
4221
4222        // Split into words (maximal non-space runs), each carrying the space
4223        // glyph that followed it (so its source offset is preserved).
4224        let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
4225        let mut word: Vec<Glyph> = Vec::new();
4226        for g in glyphs {
4227            if g.ch == ' ' {
4228                words.push((std::mem::take(&mut word), Some(g)));
4229            } else {
4230                word.push(g);
4231            }
4232        }
4233        if !word.is_empty() {
4234            words.push((word, None));
4235        }
4236        if words.is_empty() {
4237            // An empty block (or an empty preserved line) still occupies one
4238            // (prefixed) row.
4239            push_last(self, pf.to_vec());
4240            return;
4241        }
4242
4243        let mut line: Vec<Glyph> = Vec::new();
4244        let mut used = 0usize;
4245        let mut first = true;
4246        for (w, space) in words {
4247            let avail = width
4248                .saturating_sub(prefix_width(if first { pf } else { pc }))
4249                .max(1);
4250            let cells = glyphs_width(&w);
4251            if used > 0 && used + cells > avail {
4252                let row = concat(if first { pf } else { pc }, &line);
4253                self.push_row(row, block_start);
4254                line = Vec::new();
4255                used = 0;
4256                first = false;
4257            }
4258            used += cells;
4259            line.extend(w);
4260            if let Some(sp) = space {
4261                used += 1;
4262                line.push(sp);
4263            }
4264        }
4265        let row = concat(if first { pf } else { pc }, &line);
4266        push_last(self, row);
4267    }
4268
4269    /// The source offset of each line of a code block's `text`.
4270    ///
4271    /// `content` is the block's `content_span` — where twig says the body lives
4272    /// in the source, fences already excluded. Its lines run 1:1 with the
4273    /// rendered `text` lines, so no search is needed; each is anchored at the
4274    /// *end* of its source line, which places it past whatever indent `text` had
4275    /// stripped (a fenced block's fences, an indented one's leading spaces)
4276    /// without having to know how much there was.
4277    ///
4278    /// `None` when the body and the rendered lines don't line up — a coarse
4279    /// fallback the caller turns into the block's start offset.
4280    fn code_line_offsets(&self, content: &Range<usize>, lines: &[&str]) -> Option<Vec<usize>> {
4281        let mut src_lines: Vec<(usize, &str)> = Vec::new();
4282        let mut at = content.start;
4283        for l in self.source.get(content.start..content.end)?.split('\n') {
4284            src_lines.push((at, l));
4285            at += l.len() + 1;
4286        }
4287        if src_lines.len() != lines.len() {
4288            return None;
4289        }
4290        Some(
4291            lines
4292                .iter()
4293                .zip(&src_lines)
4294                .map(|(l, (start, sl))| start + sl.len().saturating_sub(l.len()))
4295                .collect(),
4296        )
4297    }
4298
4299    fn push_row(&mut self, glyphs: Vec<Glyph>, fallback: usize) {
4300        // Step past the character the *source* holds at the last glyph's offset,
4301        // not past the glyph's own `ch`. The two agree for ordinary text, but a
4302        // glyph is not always the character it stands on: `synth` decoration and
4303        // a substituted run (an image's `⧉ label`) share one offset by design.
4304        // Trusting `ch` there yields an offset inside a multi-byte character,
4305        // which every later slice of `source` panics on.
4306        let end_src = glyphs
4307            .last()
4308            .map(|g| {
4309                let at = g.src.min(self.source.len());
4310                at + self.source[at..].chars().next().map_or(0, char::len_utf8)
4311            })
4312            .unwrap_or(fallback);
4313        self.push_row_at(glyphs, end_src);
4314    }
4315
4316    /// Push a row with an explicit end stop, for content that knows its own
4317    /// extent better than its last glyph does.
4318    fn push_row_at(&mut self, glyphs: Vec<Glyph>, end_src: usize) {
4319        self.last_off = end_src;
4320        let mark_ends = self.take_mark_ends(end_src);
4321        self.rows.push(VRow {
4322            glyphs,
4323            end_src,
4324            decoration: false,
4325            code: false,
4326            code_lang: None,
4327            directive: false,
4328            directive_label: None,
4329            media: None,
4330            task: None,
4331            leaf_directive: None,
4332            heading: None,
4333            align: None,
4334            line_height: None,
4335            boundary: None,
4336            mark_ends,
4337        });
4338    }
4339
4340    /// The quote's own trailing marker lines: the `>` / `> ` lines that lie past
4341    /// its last child but inside its span, one gutter row each.
4342    ///
4343    /// Pressing Enter at the end of `> a` writes `> a\n>\n> \n` — twig's
4344    /// spelling, and the right one. Those last two lines hold no block (a
4345    /// `block_quote`'s `content_span` still stops at its last child) so the
4346    /// children walk never reaches them, and they used to fall all the way to
4347    /// the document-level [`Builder::emit_trailing_blank_lines`], which knows no
4348    /// prefix: the gutter simply stopped, and a writer adding a line to a quote
4349    /// watched it draw as plain prose.
4350    ///
4351    /// This is only answerable since twig 3.2.0, where a Markdown `block_quote`'s
4352    /// span covers its own trailing marker lines (it reported `0..3` for that
4353    /// source and now reports `0..8`). Before that the lines belonged to no node
4354    /// at any level, and the only way to draw them was to sniff `>` off the raw
4355    /// source and re-derive the nesting depth by counting markers — format
4356    /// inference this crate exists to keep out of the render path.
4357    ///
4358    /// Each row is a real caret home rather than a decoration gap: the writer
4359    /// spelled every one of these lines with a marker of its own, so each is a
4360    /// line of the quote to stand on, not the spacing between two blocks (which
4361    /// is [`Builder::emit_separators_before`]'s, and falls *between* children
4362    /// where this never looks).
4363    fn emit_quote_trailing_lines(&mut self, pc: &[Glyph], end: usize) {
4364        let end = end.min(self.source.len());
4365        let mut at = self.rows.last().map_or(0, |r| r.end_src);
4366        // Walk line by line from the last child's end to the quote's, taking each
4367        // line's *end* as the row's offset — the caret home at the end of a line
4368        // is where one on an empty quoted line belongs, and it keeps every row's
4369        // offset distinct from its neighbours'.
4370        while at < end {
4371            let Some(k) = self.source[at..end].find('\n') else {
4372                break;
4373            };
4374            let line_start = at + k + 1;
4375            let line_end = self.source[line_start..end]
4376                .find('\n')
4377                .map_or(end, |i| line_start + i);
4378            self.push_row_at(pc.to_vec(), line_end);
4379            at = line_end;
4380        }
4381    }
4382
4383    /// The source offset the caret rests at on the blank line separating a block
4384    /// that ends at `prev_end` from the next block starting at `next_start`:
4385    /// just past the newline that terminates the previous block, but kept
4386    /// strictly before the next block so the offset is unique to this row.
4387    fn blank_line_offset(&self, prev_end: usize, next_start: usize) -> usize {
4388        let after_nl = self.source[prev_end..]
4389            .find('\n')
4390            .map_or(prev_end, |p| prev_end + p + 1);
4391        after_nl.min(next_start.saturating_sub(1)).max(prev_end)
4392    }
4393
4394    /// The source offset of each blank row between a block ending at `prev_end`
4395    /// and content starting at `next_start` — one per blank source line. The
4396    /// first newline terminates the previous block's line; every line it opens up
4397    /// to (but not including) the line that holds `next_start` is a blank row the
4398    /// caret can occupy. Offsets are unique and ascending so `pos_of_offset`
4399    /// resolves each to its own row. Empty when the two blocks are tight (no
4400    /// blank line between them).
4401    fn blank_rows_between(&self, prev_end: usize, next_start: usize) -> Vec<usize> {
4402        // Spans aren't always in tidy source order (e.g. a block after
4403        // frontmatter can start *before* the previous block's rendered content
4404        // ends). There's no blank line to place then — fall back to the clamped
4405        // single separator (an empty return) rather than slicing an inverted
4406        // range.
4407        if next_start <= prev_end {
4408            return Vec::new();
4409        }
4410        let gap = &self.source[prev_end..next_start];
4411        let Some(nl) = gap.find('\n') else {
4412            return Vec::new();
4413        };
4414        // The line holding `next_start` belongs to the next block; blank rows
4415        // stop before it.
4416        let next_line_start = self.source[..next_start].rfind('\n').map_or(0, |p| p + 1);
4417        let mut offs = Vec::new();
4418        let mut start = prev_end + nl + 1;
4419        while start < next_line_start {
4420            offs.push(start);
4421            match self.source[start..next_start].find('\n') {
4422                Some(k) => start += k + 1,
4423                None => break,
4424            }
4425        }
4426        offs
4427    }
4428
4429    /// Blank lines the user typed past the end of the last block (e.g. two
4430    /// `Enter`s to open a fresh paragraph) leave no AST node, so nothing renders
4431    /// and the caret appears stuck on the old line. Reconstruct one empty row
4432    /// per extra trailing newline from the source, each at its own offset, so
4433    /// the caret rides down onto the new line the moment it's created.
4434    ///
4435    /// `above` is the class of the last block in the document — the one this gap
4436    /// closes. A document with no blocks at all has nothing above these rows, and
4437    /// [`BlockClass::Paragraph`] is the honest answer there too: what they are is
4438    /// empty paragraphs, on both sides of the gap.
4439    fn emit_trailing_blank_lines(&mut self, above: BlockClass, hidden_end: usize) {
4440        // With no rows at all the count starts past any hidden frontmatter, not
4441        // at 0: its newlines are not trailing blank lines, and counting them
4442        // opened phantom rows *inside* the metadata for a frontmatter-only file.
4443        //
4444        // Or past the last hidden block, if that is later: a closing comment
4445        // draws no row, and its lines are not blank lines the author opened.
4446        let last_end = self
4447            .rows
4448            .last()
4449            .map_or(hidden_end, |r| r.end_src)
4450            .max(self.stepped_over);
4451        if last_end >= self.source.len() {
4452            return;
4453        }
4454        // The first newline after the last content just terminates that line, so
4455        // a lone trailing `\n` (an ordinary file ending) opens no blank row. A
4456        // *second* newline opens an empty paragraph: render it the way a block
4457        // boundary is rendered — a blank spacer row, then the empty paragraph row
4458        // the caret rests on — so the just-pressed-Enter view already shows the
4459        // gap it will keep once text is typed, and typing doesn't shift the line
4460        // down. One row per trailing newline (each its own caret offset), the
4461        // last landing at the document end where the caret sits.
4462        let extra = self.source[last_end..].matches('\n').count();
4463        if extra < 2 {
4464            return;
4465        }
4466        for k in 1..=extra {
4467            self.rows.push(VRow {
4468                glyphs: Vec::new(),
4469                end_src: last_end + k,
4470                // As between two blocks: the first blank row is the gap that
4471                // closes the block above, not somewhere to type. Nothing follows
4472                // to need a gap of its own, though, so every row after it is a
4473                // real empty paragraph — the end of the document bounds the last
4474                // one the way a following block would. Preserve flow makes even
4475                // that first row navigable, as it does every blank line.
4476                decoration: !self.preserve_soft && k == 1,
4477                code: false,
4478                code_lang: None,
4479                directive: false,
4480                directive_label: None,
4481                media: None,
4482                task: None,
4483                leaf_directive: None,
4484                heading: None,
4485                align: None,
4486                line_height: None,
4487                // The one drawn row here is a block boundary like any other —
4488                // "rendered the way a block boundary is rendered" is the whole
4489                // point of it — so it says so, and a frontend spacing boundaries
4490                // spaces this one the same. The rows below it are navigable empty
4491                // paragraphs, not gaps.
4492                boundary: (!self.preserve_soft && k == 1).then_some(Boundary {
4493                    above,
4494                    below: BlockClass::Paragraph,
4495                }),
4496                mark_ends: Vec::new(),
4497            });
4498        }
4499    }
4500}
4501
4502// ── display width ────────────────────────────────────────────────────────────
4503//
4504// Two things a row can be counted in, and they are not the same number:
4505//
4506//   *glyphs*, one per codepoint — how the text is stored here, and what an
4507//   index into `VRow::glyphs` means; and
4508//   *columns*, one per terminal cell — where the text is drawn, and what every
4509//   `col` in this crate means.
4510//
4511// `你` is one glyph in two columns. Counting columns with `glyphs.len()` (or,
4512// in the source view, `chars().count()`) is the same number only for the ASCII
4513// that most fixtures are written in, and drifts one cell per wide character
4514// everywhere else — the caret drawn a column short of the text it types into.
4515// Everything below converts between the two; nothing else should have to.
4516
4517/// The display width of `s` in terminal cells.
4518///
4519/// Measured per grapheme cluster, because that is the unit a surface advances
4520/// by: `👨‍👩‍👧` is five codepoints measuring 2 + 0 + 2 + 0 + 2 cells one at a
4521/// time, but the character they spell is drawn in 2. Both frontends already
4522/// measure it that way — ratatui asks `unicode-width` per cluster, and the GUI
4523/// asks its own text system — so the caret only lands where the text is if this
4524/// agrees with them.
4525pub fn text_width(s: &str) -> usize {
4526    UnicodeWidthStr::width(s)
4527}
4528
4529/// One grapheme cluster of a laid-out row: the glyphs that spell it, and the
4530/// cells it is drawn in.
4531///
4532/// The cluster, not the glyph, is what has a width. A row's glyphs are one per
4533/// codepoint, so an accented letter or an emoji is several of them drawn in one
4534/// character's worth of cells — the glyph that opens the cluster claims those
4535/// cells, and the ones continuing it are drawn *inside* them rather than beside
4536/// them. It's the same cluster the stop table is built on: the opening glyph is
4537/// the one a caret can rest on, and so the only one whose column it can be
4538/// drawn at.
4539struct Cluster {
4540    /// Index of the glyph that opens it.
4541    glyph: usize,
4542    /// The display column it starts at.
4543    col: usize,
4544    /// How many cells it is drawn in. Zero for a cluster with no width of its
4545    /// own (a lone joiner), which therefore sits at no column at all.
4546    cells: usize,
4547}
4548
4549/// Walk a row's glyphs as the clusters they spell, in column order.
4550fn clusters(glyphs: &[Glyph]) -> Vec<Cluster> {
4551    let text: String = glyphs.iter().map(|g| g.ch).collect();
4552    let mut out = Vec::new();
4553    let (mut glyph, mut col) = (0, 0);
4554    for cluster in text.graphemes(true) {
4555        let cells = text_width(cluster);
4556        out.push(Cluster { glyph, col, cells });
4557        // One glyph per codepoint, so a cluster spans exactly its own.
4558        glyph += cluster.chars().count();
4559        col += cells;
4560    }
4561    out
4562}
4563
4564/// The display width of a run of glyphs.
4565fn glyphs_width(glyphs: &[Glyph]) -> usize {
4566    clusters(glyphs).last().map_or(0, |c| c.col + c.cells)
4567}
4568
4569/// A cell's display width — the widest of its lines, since an in-cell `\n` break
4570/// splits it into several. Sizes the column that must hold every line.
4571fn cell_width(glyphs: &[Glyph]) -> usize {
4572    glyphs
4573        .split(|g| g.ch == '\n')
4574        .map(glyphs_width)
4575        .max()
4576        .unwrap_or(0)
4577}
4578
4579/// Whether a raw inline HTML tag is a line break (`<br>`, `<br/>`, `<br />`,
4580/// case-insensitively) — the one tag a table cell reads as an in-cell break.
4581fn is_br(text: Option<&str>) -> bool {
4582    let Some(t) = text else { return false };
4583    matches!(
4584        t.trim().to_ascii_lowercase().replace(' ', "").as_str(),
4585        "<br>" | "<br/>"
4586    )
4587}
4588
4589impl VRow {
4590    /// The row's width in display columns — and so the column of the caret
4591    /// placed past its last glyph, which is the rightmost column it can occupy.
4592    fn width(&self) -> usize {
4593        glyphs_width(&self.glyphs)
4594    }
4595
4596    /// The display column glyph `i` is drawn at. Glyphs continuing a cluster
4597    /// report the column of the glyph that opened it, since that is where they
4598    /// are drawn; none of them is ever a stop, so no caret is placed by it.
4599    fn col_of_glyph(&self, i: usize) -> usize {
4600        clusters(&self.glyphs)
4601            .iter()
4602            .rev()
4603            .find(|c| c.glyph <= i)
4604            .map_or(0, |c| c.col)
4605    }
4606
4607    /// The glyph drawn at display column `col`, or `None` past the row's last
4608    /// cell.
4609    ///
4610    /// A column landing on the *second* cell of a wide glyph resolves to that
4611    /// glyph: half a character is not a place to be, so clicking either cell of
4612    /// `你` means `你`, and the caret comes to rest at its start — the column it
4613    /// would be drawn at anyway. That rule is what makes the mapping invertible:
4614    /// every offset has one column, and every column has one offset.
4615    fn glyph_at_col(&self, col: usize) -> Option<usize> {
4616        clusters(&self.glyphs)
4617            .into_iter()
4618            .find(|c| col < c.col + c.cells)
4619            .map(|c| c.glyph)
4620    }
4621}
4622
4623// ── helpers ──────────────────────────────────────────────────────────────────
4624
4625/// The caret home inside an *empty* table cell (`col`, 0-based) whose node
4626/// `span` is `src` starting at byte `start`. twig gives an empty cell no
4627/// `content_span`, so its interior is read from the pipes: the home is one
4628/// space past the pipe that opens the cell — mimicking the `| ` padding a
4629/// filled cell has — and never at or past the pipe that closes it. So
4630/// `|  |  |` gives the two cells distinct, editable homes instead of both
4631/// collapsing onto the row's start.
4632///
4633/// Two shapes of span are read. A twig from 3.3.3 gave every cell of a row
4634/// the *row's* span, so the cell's own pipes are the `col`-th and
4635/// `col+1`-th unescaped `|` in it; a later twig spans a cell from the pipe
4636/// that opens it to the one that closes it, exclusive, so the span holds at
4637/// most that one pipe, at its start, and the closing one is the byte past
4638/// its end. The two are told apart by the pipes the span holds — a row's
4639/// span has several, or one that is not at its start.
4640fn empty_cell_offset(src: &str, start: usize, col: usize) -> usize {
4641    let bytes = src.as_bytes();
4642    let mut pipes = Vec::new();
4643    for (i, &b) in bytes.iter().enumerate() {
4644        if b == b'|' && (i == 0 || bytes[i - 1] != b'\\') {
4645            pipes.push(i);
4646        }
4647    }
4648    let whole_row = pipes.len() > 1 || pipes.first().is_some_and(|&i| i != 0);
4649    let (open, close) = if whole_row {
4650        (pipes.get(col).copied(), pipes.get(col + 1).copied())
4651    } else {
4652        (pipes.first().copied(), Some(src.len()))
4653    };
4654    match (open, close) {
4655        (Some(open), Some(close)) => {
4656            let lo = open + 1; // just inside the opening pipe
4657            let hi = close.saturating_sub(1); // just inside the closing pipe
4658            let inside = if hi < lo {
4659                lo
4660            } else {
4661                (open + 2).clamp(lo, hi)
4662            };
4663            start + inside
4664        }
4665        (Some(open), None) => start + open + 1,
4666        _ => start,
4667    }
4668}
4669
4670/// One laid-out table cell: its rendered text, the source range that text
4671/// occupies (`start`/`end` are the caret anchors decoration points at), and the
4672/// column alignment its padding honours.
4673///
4674/// `glyphs` is the cell's inline content *unwrapped* — the box-drawn rows wrap
4675/// it to a column width, but a frontend laying the grid out itself needs the
4676/// text before that decision was made.
4677#[derive(Clone)]
4678pub struct TableCell {
4679    pub glyphs: Vec<Glyph>,
4680    pub start: usize,
4681    pub end: usize,
4682    pub align: Alignment,
4683}
4684
4685/// One row of a table's grid, as the document spells it — not as it's drawn.
4686#[derive(Clone)]
4687pub struct TableRow {
4688    /// A header row: drawn bold, and ruled off from the body below it.
4689    pub head: bool,
4690    pub cells: Vec<TableCell>,
4691}
4692
4693/// A table's structure, published alongside the box-drawn rows that spell it.
4694///
4695/// The rows in [`VisualMap::rows`] are the *default monospace* picture of a
4696/// table: every border a `│`, every column a whole number of character cells.
4697/// That picture is exactly right on any monospace surface, and unfixable off one
4698/// — in a proportional font the `│`s of two rows land at different x and the grid
4699/// shears. So a frontend that draws its own geometry reads this instead: the
4700/// cells, their alignment, and which rows are the head, with no opinion about
4701/// how wide a column is or what a border looks like.
4702///
4703/// Both are always built. The TUI paints `rows` and ignores this; the GUI skips
4704/// `rows` for the span in `rows_span` and draws from here. They describe the
4705/// same cells, so the caret lands on the same offsets either way.
4706#[derive(Clone)]
4707pub struct TableInfo {
4708    /// The `VisualMap::rows` this table's picture occupies, borders included —
4709    /// what a frontend drawing its own table skips over.
4710    pub rows_span: Range<usize>,
4711    /// The end of the table node's source span, and the offset its trailing
4712    /// caret stop sits at — the one caret home past the last cell, held by the
4713    /// bottom border row's end. Typing there opens a paragraph under the table
4714    /// rather than joining the block; see `Doc::open_paragraph_at_block_edge`.
4715    pub end_src: usize,
4716    /// The block prefix every row of this table carries — a blockquote's `│ `
4717    /// gutter, a list item's indent. Empty for a table at the top level.
4718    ///
4719    /// A frontend drawing its own grid has to render this and start the table
4720    /// past it, exactly as the picture does; a table nested in a quote that
4721    /// draws flush at the left margin has left the quote.
4722    pub prefix: Vec<Glyph>,
4723    pub grid: Vec<TableRow>,
4724}
4725
4726/// A fenced or indented code block, named by the [`VisualMap::rows`] it occupies.
4727///
4728/// Unlike a table, the rows *are* the block's content — a frontend still paints
4729/// them, it just draws a border and a tinted background around the whole span
4730/// and lets the code inside scroll horizontally instead of wrapping. So this
4731/// carries only the row range; there's no structural alternative to the picture
4732/// the way [`TableInfo`] is one. Derived from [`VRow::code`] — see
4733/// [`code_block_spans`].
4734#[derive(Clone, Debug, PartialEq, Eq)]
4735pub struct CodeBlockInfo {
4736    /// The contiguous run of [`VisualMap::rows`] this code block spans, blank
4737    /// code lines included.
4738    pub rows_span: Range<usize>,
4739    /// The block's language, from a fenced block's info string — what a frontend
4740    /// paints as a small label on the box (`` ```rust `` → `Some("rust")`).
4741    /// `None` for a fence written without one, or an indented block. Editing it
4742    /// goes through [`crate::Doc::set_code_language`], which re-finds the fence
4743    /// in the AST, so this stays a display string.
4744    pub lang: Option<String>,
4745}
4746
4747/// A block-level image (`![alt](url)` on its own line), named by the single
4748/// [`VisualMap::rows`] row it occupies.
4749///
4750/// Like [`CodeBlockInfo`], the row *is* the block's default rendering — a plain
4751/// surface paints the `🖼 alt` placeholder glyphs as-is. An image-capable
4752/// frontend instead **skips the row in `rows_span`** and paints the resolved
4753/// picture there, exactly as it skips a [`TableInfo`]'s box-drawn rows. Derived
4754/// from [`VRow::media`] by [`media_spans`], so it survives the row reuse of
4755/// [`BlockCache`] and [`build_spliced`].
4756#[derive(Clone, Debug, PartialEq, Eq)]
4757pub struct MediaInfo {
4758    /// The [`VisualMap::rows`] rows this media's placeholder occupies — what a
4759    /// capable frontend replaces with the picture or player.
4760    pub rows_span: Range<usize>,
4761    /// Whether this is a picture, a movie, or a sound — which widget the
4762    /// frontend builds over [`rows_span`](MediaInfo::rows_span). A frontend that
4763    /// handles only some kinds leaves the rest as core's placeholder rows, which
4764    /// already read sensibly on their own.
4765    pub kind: MediaKind,
4766    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
4767    /// the AST. A frontend resolves a relative path against the document's own
4768    /// directory; core does no I/O. For a `<picture>` this is the `<img>`
4769    /// fallback — the source used when no [`sources`](MediaInfo::sources) media
4770    /// query matches (or the frontend has no theme). Empty when a `<video>`/
4771    /// `<audio>` carries no `src` and names its candidates in `<source>`s
4772    /// instead; [`resolve`](MediaInfo::resolve) already accounts for that.
4773    pub destination: String,
4774    /// The `<source>` alternatives in document order, or empty for a plain
4775    /// image. See [`MediaSource`]; a theme- or codec-aware frontend picks one and
4776    /// otherwise loads [`destination`](MediaInfo::destination).
4777    pub sources: Vec<MediaSource>,
4778    /// The media's alt text, flattened from its inline children (empty when it
4779    /// has none).
4780    pub alt: String,
4781    /// A `<video poster="…">`'s still frame, or empty when there is none — an
4782    /// image destination, resolved exactly as [`destination`] is.
4783    ///
4784    /// [`destination`]: MediaInfo::destination
4785    pub poster: String,
4786}
4787
4788/// One leaf directive (`::name{…}`) as a frontend sees it: which rows its
4789/// placeholder occupies, its type, and its attributes. A plain surface paints
4790/// the `⧉ name` placeholder glyphs as-is; a frontend that knows the host app's
4791/// vocabulary **skips the rows in `rows_span`** and paints the real thing there,
4792/// exactly as an image-capable one does with [`MediaInfo`]. Derived from
4793/// [`VRow::leaf_directive`] by [`directive_spans`].
4794///
4795/// Core resolves nothing here — it has no idea what an `embed` or a `toc` is,
4796/// and deliberately so: the directive vocabulary belongs to the app on top.
4797#[derive(Clone, Debug, PartialEq, Eq)]
4798pub struct DirectiveInfo {
4799    /// The [`VisualMap::rows`] rows this directive's placeholder occupies — the
4800    /// label row plus any blank fillers under it.
4801    pub rows_span: Range<usize>,
4802    /// The directive's type (`embed`, `toc`, `vis`), no leading colons.
4803    pub name: String,
4804    /// Its `{…}` attributes in source order; a bare one has a `None` value.
4805    pub attrs: Vec<(String, Option<String>)>,
4806    /// Its `[label]` text, flattened from its inline children (empty when it has
4807    /// none) — what the placeholder row shows.
4808    pub label: String,
4809}
4810
4811impl DirectiveInfo {
4812    /// The value of attribute `key`, if it has one with a value. The convenience
4813    /// a frontend reaches for first (`info.attr("src")`), since almost every
4814    /// directive that draws as something real is pointed at by one attribute.
4815    pub fn attr(&self, key: &str) -> Option<&str> {
4816        self.attrs
4817            .iter()
4818            .find(|(k, _)| k == key)
4819            .and_then(|(_, v)| v.as_deref())
4820    }
4821}
4822
4823impl MediaInfo {
4824    /// The image URL to load under `scheme`: the first [`sources`] `<source>`
4825    /// whose media query matches, else the [`destination`] `<img>` fallback. The
4826    /// pick is a `<source>`'s first `srcset` URL or the destination — a frontend
4827    /// resolves whichever it gets against the document directory exactly as it
4828    /// resolves `destination`, and reserves/keys the picture under `destination`
4829    /// regardless, so a theme switch just re-picks without disturbing the layout.
4830    ///
4831    /// Only `prefers-color-scheme` is understood (that's what a light/dark banner
4832    /// uses); a `<source>` with any other media query is skipped, and one with no
4833    /// media at all always matches (an unconditional override). With no matching
4834    /// source — including every frontend that can't/doesn't theme and passes
4835    /// [`ColorScheme::Light`] to a dark-only picture — it's the plain `<img>`.
4836    ///
4837    /// [`sources`]: MediaInfo::sources
4838    /// [`destination`]: MediaInfo::destination
4839    pub fn resolve(&self, scheme: ColorScheme) -> &str {
4840        if let Some(url) = self
4841            .sources
4842            .iter()
4843            .find(|s| media_matches(&s.media, scheme))
4844            .and_then(|s| first_srcset_url(&s.srcset))
4845        {
4846            return url;
4847        }
4848        // A `<video>`/`<audio>` may carry no `src` of its own, naming its
4849        // candidates only in child `<source>`s — none of which matched above,
4850        // because a codec-typed `<source>` has no media query and core judges no
4851        // MIME types. Falling through to an empty destination would hand the
4852        // frontend nothing to load, so take the first candidate URL instead and
4853        // let the frontend reject it if it can't decode it. An `<img>` never
4854        // reaches this: its `src` is the picture.
4855        if self.destination.is_empty()
4856            && let Some(url) = self
4857                .sources
4858                .iter()
4859                .find_map(|s| first_srcset_url(&s.srcset))
4860        {
4861            return url;
4862        }
4863        &self.destination
4864    }
4865
4866    /// The **still picture** that stands for this media under `scheme`, for a
4867    /// frontend that can rasterize an image but not play a movie — a terminal, or
4868    /// a GUI still growing its player. `None` when there is no picture to draw,
4869    /// which is the honest answer for audio and for a poster-less video: the
4870    /// caller leaves core's labelled placeholder row, which already reads as
4871    /// *a thing that isn't text*.
4872    ///
4873    /// This exists so those frontends never hand a `.mp4` to an image decoder.
4874    /// That fails harmlessly today (a failed decode falls back to the same
4875    /// placeholder), but it spends a file read and a decode attempt per frame to
4876    /// arrive where this gets in one match.
4877    pub fn still(&self, scheme: ColorScheme) -> Option<&str> {
4878        match self.kind {
4879            MediaKind::Image => Some(self.resolve(scheme)),
4880            // A `poster` is an image destination, so it resolves the same way —
4881            // but it is named directly and has no `<source>` alternatives of its
4882            // own, so it needs no theme matching.
4883            MediaKind::Video if !self.poster.is_empty() => Some(&self.poster),
4884            MediaKind::Video | MediaKind::Audio => None,
4885        }
4886    }
4887}
4888
4889/// A frontend's active color scheme — what a `<picture>`'s `prefers-color-scheme`
4890/// `<source>`s are matched against by [`MediaInfo::resolve`]. A frontend with no
4891/// notion of theme passes [`Light`](ColorScheme::Light), the web's own default.
4892#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4893pub enum ColorScheme {
4894    Light,
4895    Dark,
4896}
4897
4898/// Whether a `<source media="…">` query applies under `scheme`. Empty media is
4899/// an unconditional `<source>` (always matches); otherwise only a
4900/// `prefers-color-scheme: dark|light` feature is understood — anything else
4901/// (a width query, `print`, …) doesn't match, so resolution falls through to the
4902/// next source or the `<img>`. Deliberately lax about the surrounding syntax
4903/// (`(prefers-color-scheme: dark)`, `screen and (prefers-color-scheme:dark)`):
4904/// it keys off the feature and its value, which is all the theme case needs.
4905fn media_matches(media: &str, scheme: ColorScheme) -> bool {
4906    let media = media.trim();
4907    if media.is_empty() {
4908        return true;
4909    }
4910    let lower = media.to_ascii_lowercase();
4911    let Some(after) = lower
4912        .split_once("prefers-color-scheme")
4913        .map(|(_, rest)| rest)
4914    else {
4915        return false;
4916    };
4917    // Skip the `:` and any spaces to reach the value word.
4918    let value = after.trim_start_matches([':', ' ', '\t']);
4919    let wanted = match scheme {
4920        ColorScheme::Light => "light",
4921        ColorScheme::Dark => "dark",
4922    };
4923    value.starts_with(wanted)
4924}
4925
4926/// The first URL in a `srcset`: its first comma-separated candidate, before any
4927/// `1x`/`2x`/width descriptor. The theme case only ever puts one URL per
4928/// `<source>`, so the first candidate is the picture.
4929fn first_srcset_url(srcset: &str) -> Option<&str> {
4930    let first = srcset.split(',').next()?.trim();
4931    first.split_whitespace().next().filter(|u| !u.is_empty())
4932}
4933
4934/// The narrowest a column may be squeezed. Below a few characters a column
4935/// stops carrying text and just shreds it one letter per line, which is worse
4936/// than letting the grid run wide.
4937const MIN_COL_WIDTH: usize = 3;
4938
4939/// Shrink `widths` until the grid fits `avail` screen columns, taking from the
4940/// widest column each time so the loss is shared out rather than falling on
4941/// whichever column happens to be last. No column goes below
4942/// [`MIN_COL_WIDTH`]; a table with more columns than the surface has room for
4943/// still overflows, which is the honest outcome — there's nothing left to give.
4944fn fit_widths(widths: &mut [usize], avail: usize) {
4945    // Chrome: each column is its content plus a gutter either side, and every
4946    // column is closed by a `│` — with one more opening the row.
4947    let budget = avail.saturating_sub(3 * widths.len() + 1);
4948    while widths.iter().sum::<usize>() > budget {
4949        let Some(w) = widths.iter_mut().filter(|w| **w > MIN_COL_WIDTH).max() else {
4950            return;
4951        };
4952        *w -= 1;
4953    }
4954}
4955
4956/// Word-wrap `glyphs` into lines of at most `width` columns, hard-breaking any
4957/// single word too long to fit.
4958///
4959/// Unlike a paragraph — where an overlong word just trails off the end of the
4960/// line — a table column is a hard boundary: a glyph past it lands on top of
4961/// the border, or on the next cell. So the width here is a promise, and a word
4962/// that won't keep it is broken.
4963///
4964/// The space at a break is dropped rather than hung past the edge. Its offset
4965/// isn't lost: the caller gives every line an end stop just past its last
4966/// glyph, which is exactly where that space was.
4967///
4968/// `width` is in display columns, and a break only ever falls between grapheme
4969/// clusters. Both matter to more than the picture: the caller anchors each
4970/// line's end stop just past its last glyph, so a line cut mid-cluster would
4971/// put a caret stop inside a character — reachable by Down or a click, and the
4972/// next Backspace would take the cluster apart from the middle.
4973///
4974/// An explicit in-cell break (a `\n` glyph, from a `<br>`) is a hard boundary:
4975/// each run between the breaks wraps on its own and the results stack. The break
4976/// glyphs are dropped — the caller's per-line end stop already sits exactly where
4977/// each break was, so no offset is lost.
4978fn wrap_glyphs(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
4979    if glyphs.iter().any(|g| g.ch == '\n') {
4980        return glyphs
4981            .split(|g| g.ch == '\n')
4982            .flat_map(|seg| wrap_segment(seg, width))
4983            .collect();
4984    }
4985    wrap_segment(glyphs, width)
4986}
4987
4988/// [`wrap_glyphs`] for a run with no explicit breaks — the word-wrap proper.
4989fn wrap_segment(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
4990    let width = width.max(1);
4991    // Words are maximal non-space runs, each carrying the space that followed it
4992    // — which survives only if the next word joins it on this line.
4993    let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
4994    let mut word: Vec<Glyph> = Vec::new();
4995    for g in glyphs {
4996        if g.ch == ' ' {
4997            words.push((std::mem::take(&mut word), Some(g.clone())));
4998        } else {
4999            word.push(g.clone());
5000        }
5001    }
5002    if !word.is_empty() {
5003        words.push((word, None));
5004    }
5005
5006    let mut lines: Vec<Vec<Glyph>> = Vec::new();
5007    let mut line: Vec<Glyph> = Vec::new();
5008    let mut used = 0usize;
5009    let mut gap: Option<Glyph> = None;
5010    for (word, space) in words {
5011        for chunk in hard_break(&word, width) {
5012            let sep = gap.is_some() as usize;
5013            let cells = glyphs_width(chunk);
5014            if !line.is_empty() && used + sep + cells > width {
5015                lines.push(std::mem::take(&mut line));
5016                used = 0;
5017                gap = None; // the break swallows the space
5018            }
5019            if let Some(sp) = gap.take() {
5020                line.push(sp);
5021                used += 1;
5022            }
5023            line.extend_from_slice(chunk);
5024            used += cells;
5025        }
5026        gap = space;
5027    }
5028    // An empty cell is still one (empty) line — it has an end the caret can
5029    // sit at, which is how you type into it.
5030    if !line.is_empty() || lines.is_empty() {
5031        lines.push(line);
5032    }
5033    lines
5034}
5035
5036/// Break a single word into pieces of at most `width` columns, cutting only
5037/// between grapheme clusters — the replacement for slicing it into fixed runs
5038/// of glyphs, which measures a wide character as one column and can cut an
5039/// emoji in half.
5040///
5041/// A cluster wider than the whole column still gets a piece to itself: there is
5042/// nowhere legal to cut it, and overflowing by a cell is better than splitting a
5043/// character. An empty word yields no pieces at all, which is what keeps a
5044/// double space from opening a line of its own.
5045fn hard_break(word: &[Glyph], width: usize) -> Vec<&[Glyph]> {
5046    let mut out = Vec::new();
5047    if word.is_empty() {
5048        return out;
5049    }
5050    let (mut start, mut used) = (0usize, 0usize);
5051    for c in clusters(word) {
5052        if used > 0 && used + c.cells > width {
5053            out.push(&word[start..c.glyph]);
5054            start = c.glyph;
5055            used = 0;
5056        }
5057        used += c.cells;
5058    }
5059    out.push(&word[start..]);
5060    out
5061}
5062
5063/// A table rule spanning `widths`, e.g. `┌──────┬─────┐`. Each column is its
5064/// content width plus the one-space gutter on either side.
5065fn rule_text(widths: &[usize], left: char, mid: char, right: char) -> String {
5066    let mut s = String::new();
5067    s.push(left);
5068    for (i, w) in widths.iter().enumerate() {
5069        if i > 0 {
5070            s.push(mid);
5071        }
5072        for _ in 0..w + 2 {
5073            s.push('─');
5074        }
5075    }
5076    s.push(right);
5077    s
5078}
5079
5080/// Push real document text: each glyph maps to its own source byte, and the one
5081/// that opens a grapheme cluster is the caret stop for the whole cluster.
5082///
5083/// Per cluster rather than per codepoint because a cluster is the character the
5084/// user sees, and it's the unit backspace and delete already step by. A stop
5085/// inside 👨‍👩‍👧 — five codepoints strung together with joiners — is a caret
5086/// parked in the middle of a character: one press of Right lands there, and the
5087/// next Backspace severs a joiner from what it joined, leaving a dangling ZWJ in
5088/// the source. The rest of the cluster still gets its glyph (it has to be
5089/// drawn); it just isn't somewhere to stand.
5090fn push_text(out: &mut Vec<Glyph>, text: &str, base_src: usize, style: Style) {
5091    for (gi, cluster) in text.grapheme_indices(true) {
5092        for (ci, ch) in cluster.char_indices() {
5093            out.push(Glyph {
5094                ch,
5095                style,
5096                src: base_src + gi + ci,
5097                stop: ci == 0,
5098            });
5099        }
5100    }
5101}
5102
5103/// [`push_text`] for one line of a highlighted code block: the same glyphs at
5104/// the same offsets, each additionally carrying the [`Token`] of the span it
5105/// falls in — `spans` being the line's entry from [`code_tokens`], ascending
5106/// byte ranges *into `text`*. A byte between spans keeps `style` as it is.
5107///
5108/// Offsets are what matters here: a token changes how a glyph is painted and
5109/// nothing about where it is or which source byte it stands on, so a caret
5110/// walks a highlighted block exactly as it walks an unhighlighted one.
5111fn push_code_text(
5112    out: &mut Vec<Glyph>,
5113    text: &str,
5114    base_src: usize,
5115    style: Style,
5116    spans: &[(Range<usize>, Token)],
5117) {
5118    let mut spans = spans.iter().peekable();
5119    for (gi, cluster) in text.grapheme_indices(true) {
5120        // Spans are ascending, so the one covering this cluster's first byte
5121        // is at or after the one that covered the last; step past those ended.
5122        while spans.peek().is_some_and(|(r, _)| r.end <= gi) {
5123            spans.next();
5124        }
5125        let token = spans
5126            .peek()
5127            .filter(|(r, _)| r.contains(&gi))
5128            .map(|(_, t)| *t);
5129        // A cluster is classed whole, by its first byte: a grammar that split
5130        // an emoji's scalars between two tokens would otherwise split the
5131        // glyph, and no grammar means to.
5132        let style = style.token(token);
5133        for (ci, ch) in cluster.char_indices() {
5134            out.push(Glyph {
5135                ch,
5136                style,
5137                src: base_src + gi + ci,
5138                stop: ci == 0,
5139            });
5140        }
5141    }
5142}
5143
5144/// One line's highlighting — `crate::syntax::LineTokens`, spelled here so the
5145/// shape exists whether or not the feature that fills it does.
5146type LineTokens = Vec<(Range<usize>, Token)>;
5147
5148/// The syntax highlighting for a code block's lines, or `None` when the fence's
5149/// language is not one the grammars know. Without the `syntax` feature nothing
5150/// is known, and every code glyph draws in the plain code colour.
5151#[cfg(feature = "syntax")]
5152fn code_tokens(lang: &str, lines: &[&str]) -> Option<Vec<LineTokens>> {
5153    crate::syntax::highlight(lang, lines)
5154}
5155
5156#[cfg(not(feature = "syntax"))]
5157fn code_tokens(_lang: &str, _lines: &[&str]) -> Option<Vec<LineTokens>> {
5158    None
5159}
5160
5161/// Emit an inline `str`/`smart_punctuation` run, mapping every visible char back
5162/// to its *true* source byte even when the source carries backslash escapes the
5163/// parsed `text` dropped (`\*` → `*`). The naive `span.start + text_offset`
5164/// mapping [`push_text`] uses drifts by one byte after each escape, so a caret or
5165/// click past an escaped `*` would land on the wrong character; walking the text
5166/// against its source keeps them aligned, and the hidden escape backslash gets no
5167/// glyph of its own (it is a spelling artefact, not something the caret lands on).
5168fn push_escaped_text(
5169    out: &mut Vec<Glyph>,
5170    text: &str,
5171    span: Range<usize>,
5172    source: &str,
5173    style: Style,
5174) {
5175    let end = span.end.min(source.len());
5176    let src = source.get(span.start..end).unwrap_or("");
5177    // Fast path — no dropped bytes, so text and source align 1:1 (the common
5178    // case: prose with no escapes). Byte lengths equal ⇒ no backslash was eaten.
5179    if src.len() == text.len() {
5180        push_text(out, text, span.start, style);
5181        return;
5182    }
5183    // Slow path: some `\` was consumed. Walk char-by-char, skipping a backslash
5184    // in the source exactly when it escapes the next visible char (a real escape),
5185    // never when it is a literal backslash the parse kept (that case has equal
5186    // lengths and takes the fast path above).
5187    let sb = src.as_bytes();
5188    let mut si = 0usize;
5189    'text: for (_, cluster) in text.grapheme_indices(true) {
5190        for (ci, ch) in cluster.char_indices() {
5191            // The text outlasted the source it is being mapped onto. In a
5192            // consistent document that cannot happen on this path: the slow path
5193            // is only entered when the two lengths differ, and everything that
5194            // makes them differ makes the *source* the longer one — an escape
5195            // backslash the parse ate, or source folded into a neighbouring node.
5196            // A `smart_punctuation` node reports its canonical ASCII spelling
5197            // (`--`, `...`, `"`), which is never longer than what was written.
5198            //
5199            // So reaching here means `span` was measured against a document that
5200            // `source` is no longer, and there is no honest offset left to give
5201            // the remaining characters. Stop: the row comes out short, which is
5202            // a wrong picture of a document that is already inconsistent. The
5203            // alternative was `si` stepping past the end and the slice below
5204            // panicking — which is what it did, in a paint loop.
5205            if si >= sb.len() {
5206                break 'text;
5207            }
5208            // Advance to the source character this one came from, stepping over
5209            // whatever the parse dropped on the way. An escape backslash is the
5210            // common case, but not the only one: a span can cover source that
5211            // was folded into a neighbouring node (smart punctuation next to a
5212            // bracket gives `text: "]"` over a source span of `"…]"`). Advancing
5213            // by the *text* character's length assumed escapes were the only
5214            // divergence, so one dropped multi-byte character desynchronized
5215            // every glyph after it — placing `]` inside the `…` before it.
5216            while si < sb.len() && !src[si..].starts_with(ch) {
5217                si += src[si..].chars().next().map_or(1, char::len_utf8);
5218            }
5219            out.push(Glyph {
5220                ch,
5221                style,
5222                src: span.start + si.min(src.len()),
5223                stop: ci == 0,
5224            });
5225            si += src[si..]
5226                .chars()
5227                .next()
5228                .map_or(ch.len_utf8(), char::len_utf8);
5229        }
5230    }
5231}
5232
5233/// Build synthetic decoration glyphs (a bullet, a gutter) all pointing at `src`,
5234/// each carrying `role` so the frontend can style it (`Role::Body` for plain
5235/// padding). Synthetic glyphs are never caret stops — they share one offset, so
5236/// the caret steps over them (a click still lands at `src`).
5237fn synth(text: &str, role: Role, src: usize) -> Vec<Glyph> {
5238    let style = Style::default().role(role);
5239    text.chars()
5240        .map(|ch| Glyph {
5241            ch,
5242            style,
5243            src,
5244            stop: false,
5245        })
5246        .collect()
5247}
5248
5249fn concat(a: &[Glyph], b: &[Glyph]) -> Vec<Glyph> {
5250    let mut v = a.to_vec();
5251    v.extend_from_slice(b);
5252    v
5253}
5254
5255/// The columns a row's prefix (a bullet, a quote gutter, an indent) takes up
5256/// before the text it introduces — what the wrap budget has left to spend.
5257fn prefix_width(prefix: &[Glyph]) -> usize {
5258    glyphs_width(prefix)
5259}
5260
5261/// The label shown for an image with no alt text: the final path segment of its
5262/// destination (`img/cat.png` → `cat.png`), the whole destination when it has no
5263/// separator, and `"image"` when it's empty. A `data:` URI (which has no useful
5264/// tail) shows its scheme so the placeholder isn't a wall of base64.
5265fn media_label(dest: &str) -> String {
5266    if dest.is_empty() {
5267        return "image".to_string();
5268    }
5269    if dest.starts_with("data:") {
5270        return "data:…".to_string();
5271    }
5272    // Trim a query/fragment so a URL's `?v=2#frag` doesn't ride along.
5273    let clean = dest.split(['?', '#']).next().unwrap_or(dest);
5274    let tail = clean
5275        .trim_end_matches('/')
5276        .rsplit(['/', '\\'])
5277        .next()
5278        .unwrap_or(clean);
5279    if tail.is_empty() {
5280        dest.to_string()
5281    } else {
5282        tail.to_string()
5283    }
5284}
5285
5286/// A directive's attributes read as a human label — what a frontend puts on a
5287/// container's tinted panel, and what an attribute-bearing inline directive
5288/// shows in its chip.
5289///
5290/// Reads BOTH conventions diaryx content actually uses: twig's own dot-prefixed
5291/// classes (`{.public .family}`, arriving as one combined `class` attr) and bare
5292/// pandoc-style words with no leading dot (`{public family}` — what
5293/// `diaryx_core::visibility`'s publish-time filter and apps/web's directive
5294/// serializer both write, and which twig parses as one valueless attribute
5295/// each). Reading only `.class` would leave every *existing* diaryx `:::vis{…}`
5296/// block unlabeled. A `key=value` attr is configuration rather than a name, so
5297/// it contributes nothing. `None` when nothing readable is left.
5298fn directive_attr_label(attrs: &[(String, Option<String>)]) -> Option<String> {
5299    let mut parts: Vec<String> = Vec::new();
5300    for (k, v) in attrs {
5301        if k == "class" {
5302            if let Some(v) = v
5303                && !v.is_empty()
5304            {
5305                parts.push(v.clone());
5306            }
5307        } else if v.as_deref().unwrap_or("").is_empty() {
5308            parts.push(k.clone());
5309        }
5310    }
5311    (!parts.is_empty()).then(|| parts.join(" "))
5312}
5313
5314fn heading_style(level: u32) -> Style {
5315    // Just the role — a frontend decides how a heading of this level *looks*
5316    // (the terminal cycles a color and bolds it, the GUI scales the font). The
5317    // author wrote no emphasis here, so core records none. `level as u8` is safe:
5318    // Markdown/Djot cap headings at 6.
5319    Style::default().role(Role::Heading(level.min(255) as u8))
5320}
5321
5322/// Is this `container` node a *directive* (`:::note{…}`, `::embed{…}`,
5323/// `:vis[…]`) rather than an HTML element (`<video>`, `<picture>`, `<div>`)?
5324///
5325/// twig 2.8 folded `div`/`span`/`directive`/`element` into one `container` kind,
5326/// and left nothing that separated them: `kind`, `name` and `directive_form` all
5327/// agree, field for field, on an HTML `<div>` and a Markdown `:::div`. Leaf
5328/// answered it by sniffing the span for whichever of `:` or `<` came first.
5329/// twig 3.0 records the answer at parse time as [`ContainerOrigin`], so this is
5330/// now the parser's own knowledge rather than a guess rebuilt from the bytes it
5331/// consumed.
5332pub(crate) fn container_is_directive(node: &FlatNode) -> bool {
5333    node.origin == Some(ContainerOrigin::Directive)
5334}
5335
5336/// The tag a `container` node carries when it is an HTML element rather than a
5337/// directive — `Some("video")` for a promoted `<video>`, `None` for a `:::note`
5338/// or for any node that is not a container at all.
5339pub(crate) fn element_tag(node: &FlatNode) -> Option<&str> {
5340    (node.origin == Some(ContainerOrigin::Element))
5341        .then_some(node.name.as_deref())
5342        .flatten()
5343}
5344
5345/// A leaf directive's name and whatever attributes are not part of spelling
5346/// it — the two things a [`DirectiveMark`] carries, which twig hands back
5347/// differently per format and which a frontend must not be able to tell apart.
5348///
5349/// Markdown's `::page-break` is a `Leaf`-form directive *named* `page-break`
5350/// with no attributes, and this returns it verbatim. Djot has no leaf form:
5351/// `insert_directive` writes the same document as an empty `::: page-break`
5352/// fence, whose container is anonymous (a djot div carries no name) and whose
5353/// name arrives as the fence's one class. So where the node has no name of its
5354/// own the first `class` token *is* the name, and whatever else the class said
5355/// — an author's `::: page-break {.wide}` — stays an attribute.
5356fn leaf_directive_identity(node: &FlatNode) -> (String, Vec<(String, Option<String>)>) {
5357    let named = node.name.clone().unwrap_or_default();
5358    if !named.is_empty() {
5359        return (named, node.attrs.clone());
5360    }
5361    let class = node
5362        .attrs
5363        .iter()
5364        .find(|(k, _)| k == "class")
5365        .and_then(|(_, v)| v.as_deref())
5366        .unwrap_or_default();
5367    let mut tokens = class.split_whitespace();
5368    let Some(name) = tokens.next().map(str::to_string) else {
5369        return (named, node.attrs.clone());
5370    };
5371    let rest = tokens.collect::<Vec<_>>().join(" ");
5372    let attrs = node
5373        .attrs
5374        .iter()
5375        .filter_map(|(k, v)| {
5376            if k != "class" {
5377                return Some((k.clone(), v.clone()));
5378            }
5379            (!rest.is_empty()).then(|| (k.clone(), Some(rest.clone())))
5380        })
5381        .collect();
5382    (name, attrs)
5383}
5384
5385/// Is this inline `container` an **attributed span** — the node leaf's run-level
5386/// vocabulary rides — rather than a named directive?
5387///
5388/// The four formats spell one span four ways and twig hands the name back for
5389/// two of them: HTML's and Markdown's `<span …>` arrive named `span` with
5390/// `Element` origin, while djot's `[text]{…}` and AsciiDoc's `[.a]#text#`
5391/// arrive anonymous (an empty name) with `Directive` origin. All four are the
5392/// same node to `wrap_range_attrs`, which is what writes them, so they are the
5393/// same node here.
5394///
5395/// A *named* directive is not one, whatever its name: a Markdown `:span[…]{…}`
5396/// is a directive the parser read as a directive, twig's own
5397/// `wrap_range_attrs` says so, and it keeps the handling it has.
5398///
5399/// **Anonymous is not enough**, and the form is what finishes the question:
5400/// a djot fenced div (`{.center}` / `:::` / … / `:::`) is anonymous too, with
5401/// the same `Directive` origin, and is a *block* — `Container` form against the
5402/// span's `Text`. Reading one as a span made every gesture and every query lie
5403/// about it: `set_text_color` over a word inside such a div copied the whole
5404/// div's attribute set — its `id` along with the rest — onto the new span, and
5405/// `alignment_at_caret` reported the div's `.center` as a *run's* answer while
5406/// the walker drew none. So the anonymous arm asks the form [`is_inline`] asks.
5407pub(crate) fn is_run_span(node: &FlatNode) -> bool {
5408    if node.kind != Kind::Container {
5409        return false;
5410    }
5411    match node.name.as_deref() {
5412        None | Some("") => node.directive_form == Some(DirectiveForm::Text),
5413        Some("span") => node.origin == Some(ContainerOrigin::Element),
5414        Some(_) => false,
5415    }
5416}
5417
5418/// `base` with an attributed span's three run-level keys written over it — the
5419/// nearest-wins fold [`is_run_span`] describes, for one span.
5420fn run_style(node: &FlatNode, base: Style) -> Style {
5421    Style {
5422        size: SizeStep::from_attrs(&node.attrs).or(base.size),
5423        font: FontFamily::from_attrs(&node.attrs).or(base.font),
5424        color: MarkColor::from_attrs(&node.attrs).or(base.color),
5425        ..base
5426    }
5427}
5428
5429pub(crate) fn is_inline(node: &FlatNode) -> bool {
5430    // A directive is inline only in its `text` form (`:name[label]{…}`); the
5431    // `leaf` and `container` forms are blocks. All three report the same `kind`,
5432    // so the form is the only thing telling them apart — and getting it wrong
5433    // costs a whole paragraph: a text directive misread as a block makes its
5434    // paragraph fail the "all children inline" test in `block`, and the line is
5435    // then walked as a container of blocks, rendering as empty rows with no
5436    // caret home at all.
5437    //
5438    // An HTML element shares the `container` kind, and twig sets the same form
5439    // on the two tags the lightweight formats have a generic spelling for: a
5440    // `<span>` is `Text` and a `<div>` is `Container`, while a `<video>` or a
5441    // `<picture>` has no form at all. So the form answers for an element as it
5442    // answers for a directive, and the origin is not consulted — which is what
5443    // makes a `<span …>` inside a paragraph an inline node.
5444    //
5445    // It has to. `wrap_range_attrs` spells an attributed run as exactly that
5446    // span in Markdown and HTML, and a paragraph holding one whose kids were
5447    // not all inline failed the test below and was walked as a container of
5448    // blocks: the text either side of the span rendered as nothing at all.
5449    if node.kind == Kind::Container {
5450        return node.directive_form == Some(DirectiveForm::Text);
5451    }
5452    is_inline_kind(&node.kind)
5453}
5454
5455/// [`is_inline`] by kind alone — for the ancestor walks, whose `QueryMatch`es
5456/// carry no `directive_form`. It answers `false` for every directive, which its
5457/// callers must (and do) reconcile: they pair it with `is_block_container`,
5458/// which claims every directive, so the pair's verdict is the same one a form
5459/// would have given. Anything looking at a *directive itself* wants [`is_inline`]
5460/// and a real node.
5461pub(crate) fn is_inline_kind(kind: &Kind) -> bool {
5462    matches!(
5463        kind,
5464        Kind::Str
5465            | Kind::SoftBreak
5466            | Kind::HardBreak
5467            | Kind::NonBreakingSpace
5468            | Kind::Emph
5469            | Kind::Strong
5470            | Kind::Mark
5471            | Kind::Insert
5472            | Kind::Delete
5473            | Kind::Verbatim
5474            | Kind::InlineMath
5475            | Kind::DisplayMath
5476            | Kind::Url
5477            | Kind::Email
5478            | Kind::Link
5479            | Kind::Image
5480            | Kind::SmartPunctuation
5481            | Kind::Superscript
5482            | Kind::Subscript
5483            | Kind::FootnoteReference
5484    )
5485}
5486
5487/// Assert two maps are identical down to every glyph, stop, and table span — the
5488/// contract `build_cached` and `build_spliced` must hold against `build`. Lives
5489/// at module scope (not in `mod tests`) so the Doc-driven differential test in
5490/// `doc.rs` can reach it and the private `stops` field it compares.
5491#[cfg(test)]
5492pub(crate) fn assert_maps_eq(a: &VisualMap, b: &VisualMap, ctx: &str) {
5493    assert_eq!(a.rows.len(), b.rows.len(), "row count ({ctx})");
5494    for (i, (ra, rb)) in a.rows.iter().zip(&b.rows).enumerate() {
5495        assert_eq!(ra.end_src, rb.end_src, "row {i} end_src ({ctx})");
5496        assert_eq!(ra.decoration, rb.decoration, "row {i} decoration ({ctx})");
5497        // The incremental walk labels a boundary from a query match's kind
5498        // string and the whole-arena walk from a `FlatNode`'s; this is what says
5499        // the two doors reach the same answer.
5500        assert_eq!(ra.boundary, rb.boundary, "row {i} boundary ({ctx})");
5501        assert_eq!(ra.code, rb.code, "row {i} code ({ctx})");
5502        assert_eq!(ra.code_lang, rb.code_lang, "row {i} code_lang ({ctx})");
5503        assert_eq!(ra.align, rb.align, "row {i} align ({ctx})");
5504        assert_eq!(
5505            ra.line_height, rb.line_height,
5506            "row {i} line_height ({ctx})"
5507        );
5508        assert_eq!(
5509            ra.glyphs.len(),
5510            rb.glyphs.len(),
5511            "row {i} glyph count ({ctx})"
5512        );
5513        for (j, (ga, gb)) in ra.glyphs.iter().zip(&rb.glyphs).enumerate() {
5514            assert_eq!(
5515                (ga.ch, ga.src, ga.stop, ga.style),
5516                (gb.ch, gb.src, gb.stop, gb.style),
5517                "row {i} glyph {j} ({ctx})"
5518            );
5519        }
5520    }
5521    assert_eq!(a.content_start, b.content_start, "content_start ({ctx})");
5522    assert_eq!(a.stops, b.stops, "stops ({ctx})");
5523    assert_eq!(a.mark_ends, b.mark_ends, "mark_ends ({ctx})");
5524    assert_eq!(a.tables.len(), b.tables.len(), "table count ({ctx})");
5525    for (i, (ta, tb)) in a.tables.iter().zip(&b.tables).enumerate() {
5526        assert_eq!(ta.rows_span, tb.rows_span, "table {i} rows_span ({ctx})");
5527        assert_eq!(ta.end_src, tb.end_src, "table {i} end_src ({ctx})");
5528    }
5529    assert_eq!(a.code_blocks, b.code_blocks, "code_blocks ({ctx})");
5530    assert_eq!(a.media, b.media, "images ({ctx})");
5531}
5532
5533#[cfg(test)]
5534mod tests {
5535    use super::*;
5536    use twig::{Editor, Format, NodeId};
5537
5538    fn map(src: &str) -> VisualMap {
5539        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
5540        build_t(&ed.nodes().unwrap(), src, Some(80))
5541    }
5542
5543    /// [`map`] over a Djot source. Djot is the format that spells superscript
5544    /// and subscript at all — Markdown has no syntax for either.
5545    fn map_djot(src: &str) -> VisualMap {
5546        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
5547        build_t(&ed.nodes().unwrap(), src, Some(80))
5548    }
5549
5550    /// The baseline every glyph spelling `ch` was built with, in row order —
5551    /// how a test reads a raised or lowered run off the map without caring
5552    /// which row it landed on.
5553    fn baselines_of(m: &VisualMap, ch: char) -> Vec<Baseline> {
5554        m.rows
5555            .iter()
5556            .flat_map(|r| r.glyphs.iter())
5557            .filter(|g| g.ch == ch)
5558            .map(|g| g.style.baseline)
5559            .collect()
5560    }
5561
5562    /// [`map`] at a chosen wrap width.
5563    fn map_at(src: &str, wrap: Option<usize>) -> VisualMap {
5564        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
5565        build_t(&ed.nodes().unwrap(), src, wrap)
5566    }
5567
5568    /// [`map`], but with twig's `directives` extension on (off by twig's own
5569    /// default) — the `:::name{.class}` fenced-div containers leaf-core's
5570    /// `"directive"` wysiwyg arm renders.
5571    fn map_directives(src: &str) -> VisualMap {
5572        let mut ed = Editor::new_ext(
5573            src.as_bytes(),
5574            Format::Markdown,
5575            twig::MarkdownExtensions {
5576                directives: true,
5577                ..Default::default()
5578            },
5579        )
5580        .unwrap();
5581        build_t(&ed.nodes().unwrap(), src, Some(80))
5582    }
5583
5584    /// [`map`] in `format`, parsed the way every leaf document is — the
5585    /// extensions [`crate::doc::parse_extensions`] turns on, which is what
5586    /// pairs a Markdown `<div …>` with its `</div>` into a container and makes
5587    /// `::page-break` a directive rather than a paragraph of colons.
5588    fn map_leaf(src: &str, format: Format) -> VisualMap {
5589        let mut ed =
5590            Editor::new_ext(src.as_bytes(), format, crate::doc::parse_extensions()).unwrap();
5591        build_t(&ed.nodes().unwrap(), src, Some(80))
5592    }
5593
5594    /// The alignment and line spacing of every row that draws text, in order —
5595    /// how a test reads a block property off the map.
5596    fn line_facts(m: &VisualMap) -> Vec<(Option<Align>, Option<LineSpacing>)> {
5597        m.rows
5598            .iter()
5599            .filter(|r| r.glyphs.iter().any(|g| !g.ch.is_whitespace()))
5600            .map(|r| (r.align, r.line_height))
5601            .collect()
5602    }
5603
5604    /// The style of the glyph spelling `ch`, first occurrence — how a test reads
5605    /// a run property off the map.
5606    fn style_of(m: &VisualMap, ch: char) -> Style {
5607        m.rows
5608            .iter()
5609            .flat_map(|r| r.glyphs.iter())
5610            .find(|g| g.ch == ch)
5611            .unwrap_or_else(|| panic!("no glyph {ch:?} in the map"))
5612            .style
5613    }
5614
5615    /// [`map`] with soft breaks preserved (`LineFlow::Preserve`).
5616    fn map_preserve(src: &str, wrap: Option<usize>) -> VisualMap {
5617        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
5618        build(&ed.nodes().unwrap(), src, wrap, true, &HashMap::new(), None)
5619    }
5620
5621    /// The cache-free reference [`build`], with no per-image height overrides —
5622    /// every block image stays its default one-row placeholder. The tests that
5623    /// need a taller image drive it through [`crate::Doc::set_media_rows`] instead.
5624    fn build_t(nodes: &[FlatNode], src: &str, wrap: Option<usize>) -> VisualMap {
5625        build(nodes, src, wrap, false, &HashMap::new(), None)
5626    }
5627
5628    /// An arena and a string that disagree — spans reaching past the source they
5629    /// are built against.
5630    ///
5631    /// [`crate::Doc`] keeps the two in step, so this is a "cannot happen" that
5632    /// nonetheless *did*: `examples/bench` timed a loop of `edit_range` and then
5633    /// went on handing the grown editor's spans to a builder holding the string
5634    /// from before it, and every run ended in a slice panic rather than a
5635    /// number. `push_escaped_text` was already written to survive the mismatch —
5636    /// it clamps the span's end and falls back to an empty slice — and this is
5637    /// the half of that intent it did not carry through.
5638    ///
5639    /// Rendering the wrong thing is the acceptable answer here; panicking in a
5640    /// paint loop is not.
5641    #[test]
5642    fn a_source_shorter_than_the_arena_built_over_it_renders_rather_than_panicking() {
5643        // An escape puts the run on `push_escaped_text`'s slow path — the fast
5644        // path is a length comparison that a truncated source fails anyway.
5645        let src = "alpha \\*beta\\* gamma delta epsilon\n";
5646        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
5647        let nodes = ed.nodes().unwrap();
5648
5649        // Every truncation of it, so the cut lands before, inside and after the
5650        // escaped run rather than only where one hand-picked index put it.
5651        for cut in 0..=src.len() {
5652            if !src.is_char_boundary(cut) {
5653                continue;
5654            }
5655            let map = build_t(&nodes, &src[..cut], Some(80));
5656            for row in &map.rows {
5657                for g in &row.glyphs {
5658                    assert!(
5659                        g.src <= src.len(),
5660                        "cut {cut}: glyph {:?} points past the source at {}",
5661                        g.ch,
5662                        g.src
5663                    );
5664                }
5665            }
5666        }
5667    }
5668
5669    fn rendered(m: &VisualMap) -> String {
5670        m.rows
5671            .iter()
5672            .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
5673            .collect::<Vec<_>>()
5674            .join("\n")
5675    }
5676
5677    /// Render a source both ways: `build` over the whole marshalled arena (the
5678    /// reference), and `build_cached` driven the way [`crate::Doc`] drives it —
5679    /// top-level blocks from `child_spans`, per-block subtrees on a miss.
5680    fn render_both(
5681        ed: &mut Editor,
5682        src: &str,
5683        wrap: Option<usize>,
5684        cache: &mut BlockCache,
5685    ) -> (VisualMap, VisualMap) {
5686        let all = ed.nodes().unwrap();
5687        let media_rows = HashMap::new();
5688        let plain = build(&all, src, wrap, false, &media_rows, None);
5689        let top = top_blocks(ed);
5690        let cached = build_cached(&top, src, wrap, false, &media_rows, None, cache, |id| {
5691            ed.subtree(NodeId(id)).unwrap_or_default()
5692        });
5693        (plain, cached)
5694    }
5695
5696    /// The whole correctness claim of the block cache: `build_cached` produces a
5697    /// byte-identical map to `build`, on a fresh cache *and* — the case that
5698    /// actually exercises reuse-and-shift plus per-block subtree marshalling — on
5699    /// a warm cache after the source has been edited underneath it.
5700    /// **Every glyph must stand on the character it claims.** A row's source
5701    /// extent is computed from its last glyph's offset, so a glyph carrying an
5702    /// offset that is not its own character's start yields a row end inside a
5703    /// multi-byte character — and every later slice of the source panics on it.
5704    ///
5705    /// Reproduces a real crash from a journal entry: a bracketed elision inside
5706    /// a blockquote (`[…]`) gave the closing bracket a `text` of `"]"` over a
5707    /// source span covering `"…]"`, because the parse folded the ellipsis into a
5708    /// neighbouring node. `push_escaped_text` walked that span assuming a
5709    /// dropped backslash was the only way text and source could diverge, so the
5710    /// `]` landed on the `…`'s first byte:
5711    /// `byte index 1236 is not a char boundary; it is inside '…'`.
5712    #[test]
5713    fn a_glyph_never_lands_inside_the_character_before_it() {
5714        let src = "> engage with it rather than look away. […]\n>\n> The through-line\n";
5715        let vmap = map(src);
5716        for (r, row) in vmap.rows.iter().enumerate() {
5717            assert!(
5718                src.is_char_boundary(row.end_src.min(src.len())),
5719                "row {r} ends at {} — inside a character",
5720                row.end_src
5721            );
5722            for g in &row.glyphs {
5723                assert!(
5724                    src.is_char_boundary(g.src.min(src.len())),
5725                    "row {r} has {:?} at {}, which is inside a character",
5726                    g.ch,
5727                    g.src
5728                );
5729            }
5730        }
5731        // The elision survives, and its bracket sits on the real `]`.
5732        let text: String = vmap
5733            .rows
5734            .iter()
5735            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
5736            .collect();
5737        assert!(text.contains("[…]"), "the elision should render: {text:?}");
5738        let close = vmap
5739            .rows
5740            .iter()
5741            .flat_map(|r| r.glyphs.iter())
5742            .find(|g| g.ch == ']')
5743            .expect("a closing bracket");
5744        assert_eq!(
5745            src[close.src..].chars().next(),
5746            Some(']'),
5747            "the bracket glyph should stand on the source's own `]`"
5748        );
5749    }
5750
5751    #[test]
5752    fn build_cached_matches_build() {
5753        let docs = [
5754            "# Title\n\nThe quick brown fox.\n\nAnother paragraph here.\n",
5755            "## H\n\n- one\n- two\n- three\n\n> a quote\n> continued\n",
5756            "para one\n\n```\ncode\nlines\n```\n\nafter code\n",
5757            "| a | b |\n|---|---|\n| 1 | 2 |\n\ntext after a table\n",
5758            "line\n- \nsetext?\n\nreal para\n\n\n\ntrailing blanks\n",
5759            "> quote with **bold** and a [link](https://x.dev)\n>\n> - item\n> - item2\n\ntail\n",
5760            "intro\n\n![a cat](img/cat.png)\n\nbetween\n\n![](https://x.dev/logo.svg)\n\nend\n",
5761            "- text item\n- ![alt](pic.png)\n- more text\n",
5762            // Footnotes: twig parses each definition as a root beside `doc`, so
5763            // these are the docs where the reference build and the incremental
5764            // one could disagree about what the top-level blocks even are.
5765            "A claim[^1] and another[^src].\n\n[^1]: First note.\n\n[^src]: Second.\n\ntail\n",
5766            "note[^a]\n\n[^a]: body **bold**\n    wrapped on\n    three lines\n\nafter\n",
5767            // No trailing newline. twig closes the document's last block on the
5768            // virtual newline it supplies at EOF, so that block's `span.end` is
5769            // `source.len() + 1` — a range that slices no bytes at all. Keying
5770            // the block cache off such a slice made every last block hash alike;
5771            // see [`block_bytes`].
5772            "# Title\n\nThe quick brown fox.\n\nA tail with no newline",
5773            "A claim[^1] and another[^src].\n\n[^1]: First note.\n[^src]: Second, ending the file.",
5774            // Comments draw nothing. The per-block builder the cached path
5775            // renders one with starts at offset 0 and, drawing nothing, never
5776            // moved — so the walk went on from 0 and spelled every line of the
5777            // document as a blank row. One at the start, one between blocks,
5778            // one at the end, so each position is covered.
5779            "<!-- lead -->\n\npara\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n\n<!-- trail -->\n",
5780            // Link reference definitions: roots beside `doc` like footnotes,
5781            // but drawing nothing. Alone between blocks, glued under a
5782            // paragraph, and closing the file under a comment — the README
5783            // shape.
5784            "see [a] and [b]\n\n[a]: /a\n\nmid\n[b]: /b \"bee\"\n\nend [c]\n\n<!-- links -->\n[c]: /c\n",
5785        ];
5786        for wrap in [None, Some(80usize), Some(20)] {
5787            for src in docs {
5788                let ctx = format!("wrap={wrap:?} src={src:?}");
5789                let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
5790                let mut cache = BlockCache::default();
5791
5792                // 1) Fresh cache equals the cache-free build.
5793                let (plain, cached) = render_both(&mut ed, src, wrap, &mut cache);
5794                assert_maps_eq(&plain, &cached, &format!("fresh {ctx}"));
5795
5796                // 2) Type a char mid-document, reparse, rebuild with the now-warm
5797                //    cache: the edited block is re-marshalled and re-rendered,
5798                //    every block below it is reused shifted, and the result must
5799                //    still match a from-scratch build.
5800                let at = (src.len() / 2..=src.len())
5801                    .find(|&i| src.is_char_boundary(i))
5802                    .unwrap();
5803                ed.edit_range(at, at, "Z").unwrap();
5804                let src2 = ed.source_str().unwrap();
5805                let (plain2, cached2) = render_both(&mut ed, &src2, wrap, &mut cache);
5806                assert_maps_eq(&plain2, &cached2, &format!("after insert {ctx}"));
5807
5808                // 3) Delete it again: offsets shift back the other way, and the
5809                //    warm cache must not hand back stale shifted rows.
5810                ed.edit_range(at, at + 1, "").unwrap();
5811                let src3 = ed.source_str().unwrap();
5812                let (plain3, cached3) = render_both(&mut ed, &src3, wrap, &mut cache);
5813                assert_maps_eq(&plain3, &cached3, &format!("after delete {ctx}"));
5814            }
5815        }
5816    }
5817
5818    /// A document that does not end in a newline is the one place twig hands
5819    /// leaf a top-level span that addresses no source: the last block is closed
5820    /// on the virtual newline the parser supplies at EOF, so its `span.end` is
5821    /// `source.len() + 1`. The block cache keys on the bytes under that span, and
5822    /// reading the out-of-range slice as *no bytes* broke it two ways at once —
5823    /// [`block_bytes`] has the full account. Both ways are checked here, because
5824    /// they fail independently.
5825    #[test]
5826    fn a_block_running_past_the_last_byte_still_keys_the_cache_by_its_own_bytes() {
5827        // One: two overrunning blocks collide. A footnote definition is a root
5828        // beside `doc` that [`top_blocks`] merges into the top level, while the
5829        // `section` above it spans the definition's bytes too — so when the
5830        // definition ends the file, both blocks end past it. The second was
5831        // served the first's rows, and the definition rendered as a copy of the
5832        // heading.
5833        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.";
5834        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
5835        let (plain, cached) = render_both(&mut ed, src, Some(80), &mut BlockCache::default());
5836        assert_maps_eq(&plain, &cached, "a definition ending the file");
5837        let text = rendered(&cached);
5838        assert!(
5839            text.ends_with("[note] A note with a word for a label."),
5840            "the last definition should render itself: {text:?}"
5841        );
5842        assert_eq!(
5843            text.matches("A heading with a reference").count(),
5844            1,
5845            "the heading should render exactly once: {text:?}"
5846        );
5847
5848        // Two: one overrunning block goes stale. Its bytes are its cache key, so
5849        // a block that keeps hashing the same however it is edited is served the
5850        // rows built before the edit — the whole last line frozen as the user
5851        // types in it.
5852        let mut cache = BlockCache::default();
5853        let first = "first para\n\n# A heading\n\nlast para with no newline";
5854        let mut ed = Editor::new_str(first, Format::Djot).unwrap();
5855        let (_, warm) = render_both(&mut ed, first, Some(80), &mut cache);
5856        assert!(rendered(&warm).ends_with("last para with no newline"));
5857
5858        let second = "first para\n\n# A heading\n\nDIFFERENT text without a newline";
5859        let mut ed = Editor::new_str(second, Format::Djot).unwrap();
5860        let (plain, cached) = render_both(&mut ed, second, Some(80), &mut cache);
5861        assert_maps_eq(&plain, &cached, "edited last block, warm cache");
5862        let text = rendered(&cached);
5863        assert!(
5864            text.ends_with("DIFFERENT text without a newline"),
5865            "the warm cache served the pre-edit rows: {text:?}"
5866        );
5867    }
5868
5869    #[test]
5870    fn resolves_markup_to_plain_text() {
5871        let text = rendered(&map("# Title\n\na **bold** word\n"));
5872        assert!(!text.contains('#'), "heading marker shown: {text:?}");
5873        assert!(!text.contains("**"), "strong delimiters shown: {text:?}");
5874        assert!(text.contains("Title") && text.contains("bold word"));
5875    }
5876
5877    #[test]
5878    fn every_glyph_points_at_its_source_byte() {
5879        let src = "a **bold** c\n";
5880        let m = map(src);
5881        for row in &m.rows {
5882            for g in &row.glyphs {
5883                // A real (non-synthetic) glyph's source byte is the glyph's char.
5884                if g.src < src.len()
5885                    && src.is_char_boundary(g.src)
5886                    && let Some(sc) = src[g.src..].chars().next()
5887                    && sc == g.ch
5888                {
5889                    continue;
5890                }
5891                // Synthetic prefixes (none here) would be the only exceptions.
5892                panic!("glyph {:?} at src {} doesn't match source", g.ch, g.src);
5893            }
5894        }
5895    }
5896
5897    #[test]
5898    fn offset_and_position_round_trip_on_visible_text() {
5899        let m = map("hello world\n");
5900        let (r, c) = m.pos_of_offset(6); // the 'w'
5901        assert_eq!(m.offset_of_pos(r, c), 6);
5902    }
5903
5904    #[test]
5905    fn visible_utf16_indices_count_the_text_the_system_sees() {
5906        // Hidden delimiters, a two-unit emoji, and a block gap — every way the
5907        // visible text's UTF-16 length parts company with a source byte count.
5908        let src = "a **b\u{1F600}** c\n\nd\n";
5909        let m = map(src);
5910        let end = m.snap_to_stop(src.len());
5911        let text = m.visible_text(0, end);
5912        assert_eq!(text, "a b\u{1F600} c\nd");
5913
5914        // Forward: the index of each offset is where that character sits in
5915        // the visible string, in UTF-16 units.
5916        for (i, (src_off, _)) in m.visible_items(0, end).iter().enumerate() {
5917            let expect: usize = text.chars().take(i).map(char::len_utf16).sum();
5918            assert_eq!(
5919                m.visible_utf16_len(0, *src_off),
5920                expect,
5921                "utf16 index of source offset {src_off}"
5922            );
5923            // And back: the index resolves to the offset it came from.
5924            assert_eq!(m.offset_at_visible_utf16(end, expect), Some(*src_off));
5925        }
5926        // Inside the emoji's surrogate pair resolves to the emoji.
5927        let emoji_src = src.find('\u{1F600}').unwrap();
5928        let emoji_idx = m.visible_utf16_len(0, emoji_src);
5929        assert_eq!(
5930            m.offset_at_visible_utf16(end, emoji_idx + 1),
5931            Some(emoji_src)
5932        );
5933        // At or past the end is nobody's character.
5934        let total = m.visible_utf16_len(0, end);
5935        assert_eq!(total, text.encode_utf16().count());
5936        assert_eq!(m.offset_at_visible_utf16(end, total), None);
5937    }
5938
5939    #[test]
5940    fn visible_text_spends_exactly_one_character_on_every_stop() {
5941        // A list (whose items' ends no gap row follows), a table (whose cells'
5942        // ends draw a gutter space), and a code block (one row per line):
5943        // every place the text used to part company with the stop count, in
5944        // both directions. `UITextInput`'s tokenizer indexes this text by
5945        // that count, so the two must agree exactly between any two stops.
5946        let src = "- one\n- two\n\n| a | b |\n| - | - |\n| c | d |\n\n```\nx\ny\n```\n\nend\n";
5947        let m = map(src);
5948        let end = m.snap_to_stop(src.len());
5949        // The table's trailing stop draws no glyph, so it is spelled as a line
5950        // end too: to the system the table ends on a blank line, which is
5951        // where the caret past it stands.
5952        assert_eq!(m.visible_text(0, end), "one\ntwo\na\nb\nc\nd\n\nx\ny\nend");
5953        // Between any two stops, one character per hop.
5954        let first = m.snap_to_glyph_stop(0);
5955        let stops: Vec<usize> = std::iter::successors(Some(first), |&o| m.stop_after(o)).collect();
5956        for (i, &a) in stops.iter().enumerate() {
5957            for (j, &b) in stops.iter().enumerate().skip(i) {
5958                assert_eq!(
5959                    m.visible_text(a, b).chars().count(),
5960                    j - i,
5961                    "text between stops {a} and {b}"
5962                );
5963            }
5964        }
5965        // A cell's end is spelled as a line end, not the space it draws, so a
5966        // tap landing past `a`'s last letter has nothing to step over into `b`.
5967        let a_end = src.find("a |").unwrap() + 1;
5968        assert_eq!(m.visible_text(a_end, a_end + 1), "\n");
5969    }
5970
5971    #[test]
5972    fn unwrapped_mode_emits_one_row_per_paragraph() {
5973        // A long paragraph that would wrap under a column budget stays a single
5974        // row when wrap is None (the GUI wraps it at pixel width instead).
5975        let long = "one two three four five six seven eight nine ten eleven twelve\n";
5976        let mut ed = Editor::new_str(long, Format::Markdown).unwrap();
5977        let wrapped = build_t(&ed.nodes().unwrap(), long, Some(12));
5978        let unwrapped = build_t(&ed.nodes().unwrap(), long, None);
5979        assert!(wrapped.num_rows() > 1, "narrow column should wrap");
5980        assert_eq!(unwrapped.num_rows(), 1, "no budget should keep it one row");
5981        // Every glyph's source byte is preserved in the single row.
5982        let text: String = unwrapped.rows[0].glyphs.iter().map(|g| g.ch).collect();
5983        assert_eq!(text.trim_end(), long.trim_end());
5984    }
5985
5986    fn line_texts(m: &VisualMap) -> Vec<String> {
5987        m.rows
5988            .iter()
5989            .map(|r| {
5990                // Trim the trailing whitespace a row may carry — the zero-width
5991                // '\n' that closes a preserved line, and any space glyph left at
5992                // a wrap boundary (both real caret stops, neither visible text).
5993                r.glyphs
5994                    .iter()
5995                    .map(|g| g.ch)
5996                    .collect::<String>()
5997                    .trim_end()
5998                    .to_string()
5999            })
6000            .collect()
6001    }
6002
6003    #[test]
6004    fn preserve_lays_each_soft_break_on_its_own_row() {
6005        // A soft break (a bare newline inside a paragraph) folds into a space by
6006        // default — the whole paragraph is one reflowed row...
6007        let src = "one two\nthree four\n";
6008        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6009        let folded = build_t(&ed.nodes().unwrap(), src, None);
6010        assert_eq!(folded.num_rows(), 1, "fold: one reflowed row");
6011        assert_eq!(
6012            line_texts(&folded),
6013            vec!["one two three four"],
6014            "break folded to a space"
6015        );
6016
6017        // ...and under Preserve it renders where it was written, a row per line.
6018        let kept = map_preserve(src, None);
6019        assert_eq!(
6020            line_texts(&kept),
6021            vec!["one two", "three four"],
6022            "preserve: a row per line"
6023        );
6024    }
6025
6026    #[test]
6027    fn a_preserved_break_keeps_the_newline_offset_as_a_caret_stop() {
6028        // The break must leave a caret stop at the newline byte, or the caret
6029        // could not rest at the end of the first line. The '\n' glyph is dropped
6030        // from the row (so nothing stray renders); its offset (7 here) becomes the
6031        // row's end stop instead — the same offset the folded space would carry.
6032        let src = "one two\nthree four\n";
6033        let m = map_preserve(src, None);
6034        assert!(
6035            !m.rows[0].glyphs.iter().any(|g| g.ch == '\n'),
6036            "the break glyph is dropped"
6037        );
6038        assert_eq!(
6039            m.rows[0].end_src, 7,
6040            "the first row ends at the newline byte"
6041        );
6042        assert!(m.is_stop(7), "the newline offset is a caret stop");
6043        // Row end offsets stay strictly ascending — no two rows pin one offset.
6044        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
6045        assert!(
6046            offs.windows(2).all(|w| w[0] < w[1]),
6047            "offsets not unique: {offs:?}"
6048        );
6049    }
6050
6051    #[test]
6052    fn preserved_lines_wrap_independently() {
6053        // Each preserved line wraps to the column on its own; the break between
6054        // them is hard, so a word never crosses it — "gamma" and "delta" could
6055        // share a row on width alone but the soft break keeps them apart.
6056        let src = "alpha beta gamma\ndelta epsilon\n";
6057        let m = map_preserve(src, Some(12));
6058        assert_eq!(
6059            line_texts(&m),
6060            vec!["alpha beta", "gamma", "delta", "epsilon"],
6061            "each source line wraps on its own"
6062        );
6063    }
6064
6065    #[test]
6066    fn an_empty_paragraph_between_blocks_renders_its_own_rows() {
6067        // "A", then two blank lines (an empty paragraph opened with Enter), then
6068        // "B": the empty paragraph must be navigable rows, not collapsed onto B.
6069        // Rows: "A", spacer, empty-paragraph, spacer, "B" — each blank row a
6070        // distinct source offset.
6071        let m = map("A\n\n\n\nB\n");
6072        let text: Vec<String> = m
6073            .rows
6074            .iter()
6075            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6076            .collect();
6077        assert_eq!(text, vec!["A", "", "", "", "B"], "got {text:?}");
6078        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
6079        // Strictly ascending — no two rows share an offset (else the caret pins).
6080        assert!(
6081            offs.windows(2).all(|w| w[0] < w[1]),
6082            "offsets not unique: {offs:?}"
6083        );
6084    }
6085
6086    #[test]
6087    fn a_tight_block_boundary_still_gets_one_separator() {
6088        // A heading directly above text (no blank line between) keeps the single
6089        // conventional separator row, as before.
6090        let m = map("# H\ntext\n");
6091        let text: Vec<String> = m
6092            .rows
6093            .iter()
6094            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6095            .collect();
6096        assert_eq!(text, vec!["H", "", "text"], "got {text:?}");
6097    }
6098
6099    #[test]
6100    fn an_escaped_delimiter_renders_without_its_backslash_and_maps_true_offsets() {
6101        // `a\*b` renders the three visible chars `a * b` — the escape backslash
6102        // is hidden — and every glyph points at its real source byte, so a caret
6103        // past the escape lands right (the `*` at source 2, `b` at source 3, not
6104        // the drifted 1/2 the naive text-offset mapping gave).
6105        let m = map("a\\*b\n");
6106        let row: Vec<(char, usize)> = m.rows[0].glyphs.iter().map(|g| (g.ch, g.src)).collect();
6107        assert_eq!(row, vec![('a', 0), ('*', 2), ('b', 3)], "got {row:?}");
6108    }
6109
6110    #[test]
6111    fn an_escaped_hash_stays_a_paragraph_and_shows_the_hash() {
6112        // `\# hi` is a paragraph beginning with a literal `#`, not a heading —
6113        // the backslash is hidden, the `#` shown at its true offset.
6114        let m = map("\\# hi\n");
6115        let text: String = m.rows[0].glyphs.iter().map(|g| g.ch).collect();
6116        assert_eq!(text, "# hi");
6117        assert_eq!(
6118            m.rows[0].glyphs[0].src, 1,
6119            "the # is at source byte 1, past the \\"
6120        );
6121    }
6122
6123    #[test]
6124    fn a_tight_nested_list_hangs_its_sublist_directly_under_the_item() {
6125        // A list item's own text and the sub-list nested under it are written on
6126        // adjacent source lines, so the rich view butts them together — no
6127        // fabricated blank row. Regression: the synthetic "breathe" separator
6128        // used to open a gap between `• a` and its `  • b`.
6129        assert_eq!(rendered(&map("- a\n  - b\n")), "• a\n  • b");
6130    }
6131
6132    #[test]
6133    fn a_loose_nested_list_keeps_its_real_blank_line() {
6134        // A genuine blank source line (a loose list) still parts the item from
6135        // its sub-list — only the *fabricated* separator is suppressed, never a
6136        // real one the author typed. The gap row wears the item's continuation
6137        // prefix (the two-space indent), so it renders as "  ", not empty.
6138        assert_eq!(rendered(&map("- a\n\n  - b\n")), "• a\n  \n  • b");
6139    }
6140
6141    #[test]
6142    fn frontmatter_is_hidden_and_the_document_opens_into_its_content() {
6143        // Leading YAML frontmatter renders nothing — no phantom blank rows for
6144        // its lines, no leading gap — and `content_start` points at the first
6145        // real block so the caret floor can keep out of the hidden metadata.
6146        let fm = "---\nconfig: prov.yaml\ncontents:\n- '[Sample](sample.md)'\n---\n";
6147        let src = format!("{fm}# leaf\n\nA line.\n");
6148        let m = map(&src);
6149        let text = rendered(&m);
6150        assert!(
6151            !text.contains("config"),
6152            "frontmatter body leaked: {text:?}"
6153        );
6154        assert!(!text.contains("prov"), "frontmatter body leaked: {text:?}");
6155        assert_eq!(
6156            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
6157            "leaf"
6158        );
6159        assert_eq!(
6160            m.content_start,
6161            fm.len(),
6162            "floor should be the first real block"
6163        );
6164    }
6165
6166    #[test]
6167    fn a_frontmatter_only_document_puts_the_floor_after_the_frontmatter() {
6168        // Nothing to render, so the caret floor is the end of the hidden
6169        // frontmatter — not 0, which is *before* the opening `---` and made the
6170        // first keystroke in a fresh metadata-only note land ahead of it. And
6171        // the frontmatter's own newlines are not trailing blank lines: they used
6172        // to open phantom rows at offsets 1..4, inside the metadata.
6173        let src = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
6174        let m = map(src);
6175        assert_eq!(m.content_start, src.len(), "floor must clear the metadata");
6176        assert!(
6177            m.rows.is_empty(),
6178            "frontmatter must render no rows: {:?}",
6179            rendered(&m)
6180        );
6181        assert!(
6182            m.stops.is_empty(),
6183            "no stop may sit inside the metadata: {:?}",
6184            m.stops
6185        );
6186    }
6187
6188    #[test]
6189    fn a_frontmatter_only_document_still_counts_its_real_blank_lines() {
6190        // Two blank lines after the frontmatter are the author's empty paragraph
6191        // and still render, counted from the metadata's end rather than from 0.
6192        let fm = "---\ntitle: n\n---\n";
6193        let m = map(&format!("{fm}\n\n"));
6194        assert_eq!(m.content_start, fm.len());
6195        assert_eq!(m.rows.len(), 2, "the two trailing newlines each open a row");
6196        assert!(
6197            m.rows.iter().all(|r| r.end_src > fm.len()),
6198            "rows must sit past the frontmatter"
6199        );
6200    }
6201
6202    #[test]
6203    fn a_document_without_frontmatter_has_a_zero_floor() {
6204        let m = map("# leaf\n\nbody\n");
6205        assert_eq!(m.content_start, 0);
6206    }
6207
6208    #[test]
6209    fn trailing_spaces_become_caret_stops_so_the_caret_can_be_drawn_past_them() {
6210        // Markdown/Djot drop the trailing space in `hello ` from the `str` node,
6211        // so without help the row would end at `hello` and the caret couldn't be
6212        // drawn past column 5 — typing a space at a line's end wouldn't move it
6213        // on screen until the next visible character reparsed the space into an
6214        // interior node. The builder recovers it from the block's span/content_span
6215        // gap and emits it as a real, caret-stoppable glyph.
6216        let m = map("hello \n");
6217        assert_eq!(
6218            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
6219            "hello "
6220        );
6221        assert_eq!(
6222            m.rows[0].end_src, 6,
6223            "the row now ends past the trailing space"
6224        );
6225        // The caret can rest both on and past the space.
6226        assert_eq!(m.pos_of_offset(5), (0, 5), "between 'o' and the space");
6227        assert_eq!(m.pos_of_offset(6), (0, 6), "past the space");
6228        // Two trailing spaces, both stops.
6229        let m = map("hello  \n");
6230        assert_eq!(
6231            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
6232            "hello  "
6233        );
6234        assert_eq!(m.pos_of_offset(7), (0, 7));
6235    }
6236
6237    #[test]
6238    fn a_headings_trailing_space_is_a_caret_stop_too() {
6239        // The hidden `# ` marker means `# hi ` renders as `hi ` in three columns;
6240        // the caret past the trailing space lands on the third.
6241        let m = map("# hi \n");
6242        assert_eq!(
6243            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
6244            "hi "
6245        );
6246        assert_eq!(m.pos_of_offset(5), (0, 3));
6247    }
6248
6249    #[test]
6250    fn a_table_cells_trailing_padding_is_not_mistaken_for_block_trailing_space() {
6251        // A cell's own `span` is the whole row, so the trailing-whitespace
6252        // recovery must not run for cells or it would swallow the `│` delimiters
6253        // and neighbours between the cell text and the row's end. The grid stays
6254        // exactly as before.
6255        let text = rendered(&map(TABLE));
6256        assert!(
6257            text.contains("│ Pear │   3 │"),
6258            "cell padding disturbed:\n{text}"
6259        );
6260    }
6261
6262    #[test]
6263    fn a_click_below_the_last_row_lands_on_the_last_stop_not_offset_zero() {
6264        // A drag into the empty space under a short document used to resolve to
6265        // offset 0 — the wrong direction, and not even a caret stop when the
6266        // document opens on hidden frontmatter (its `content_start` floor is not
6267        // a stop), which crashed the caret invariant. It now lands on the last
6268        // stop: the end of the document, where dragging downward should reach.
6269        let fm = "---\ntitle: n\n---\n";
6270        let m = map(&format!("{fm}# Hi\n\nbody\n"));
6271        let below = m.num_rows() + 5;
6272        let off = m.offset_of_pos(below, 0);
6273        assert!(
6274            m.is_stop(off),
6275            "offset {off} from a below-content click is not a stop"
6276        );
6277        assert_eq!(
6278            off,
6279            m.stops.last().copied().unwrap(),
6280            "should be the document's last stop"
6281        );
6282        assert!(
6283            off > fm.len(),
6284            "must not fall onto the hidden frontmatter floor"
6285        );
6286    }
6287
6288    #[test]
6289    fn offset_of_pos_is_a_stop_for_every_row_including_past_the_end() {
6290        // The invariant the caret motion asserts: whatever cell a click names,
6291        // the offset it resolves to is one the caret can actually rest at.
6292        for src in [
6293            "hello \n",
6294            "# A heading here \n\nbody text goes on \n",
6295            "---\nk: v\n---\n# Title\n\nprose here that wraps a bit \n",
6296        ] {
6297            let m = map(src);
6298            for row in 0..m.num_rows() + 3 {
6299                for col in 0..30 {
6300                    let off = m.offset_of_pos(row, col);
6301                    assert!(
6302                        m.is_stop(off),
6303                        "row {row} col {col} → {off} is not a stop in {src:?}"
6304                    );
6305                }
6306            }
6307        }
6308    }
6309
6310    /// `| Name | Qty |` with Name left-aligned and Qty right-aligned.
6311    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
6312
6313    #[test]
6314    fn a_table_renders_as_an_aligned_grid() {
6315        let text = rendered(&map(TABLE));
6316        assert_eq!(
6317            text,
6318            "┌──────┬─────┐\n\
6319             │ Name │ Qty │\n\
6320             ├──────┼─────┤\n\
6321             │ Pear │   3 │\n\
6322             │ Fig  │  12 │\n\
6323             └──────┴─────┘",
6324            "got:\n{text}"
6325        );
6326    }
6327
6328    #[test]
6329    fn table_columns_honour_their_alignment() {
6330        // Centre and default(left) come straight from twig's cell.alignment —
6331        // the delimiter row it's spelled in is consumed and has no node.
6332        let text = rendered(&map("| A | Bee |\n| --- | :---: |\n| x | y |\n"));
6333        assert!(text.contains("│ x │  y  │"), "centred column: {text:?}");
6334    }
6335
6336    #[test]
6337    fn table_borders_are_decoration_the_caret_never_lands_on() {
6338        let m = map(TABLE);
6339        // The top and header rules are whole decoration rows.
6340        for r in [0, 2] {
6341            assert!(m.rows[r].decoration, "row {r} should be a decoration rule");
6342            assert!(
6343                !m.rows[r].glyphs.iter().any(|g| g.stop),
6344                "row {r} has a stop"
6345            );
6346        }
6347        // The bottom border is the exception: no glyph of it is a stop, but
6348        // its end is the table's trailing caret home — the one place the caret
6349        // can stand past the last cell.
6350        let bottom = &m.rows[5];
6351        assert!(
6352            !bottom.decoration,
6353            "the bottom border holds the trailing stop"
6354        );
6355        assert!(
6356            !bottom.glyphs.iter().any(|g| g.stop),
6357            "the bottom border's glyphs are not stops"
6358        );
6359        assert!(m.is_stop(bottom.end_src), "the trailing stop is a stop");
6360        assert!(m.table_end_stop(bottom.end_src));
6361        assert_eq!(
6362            bottom.end_src,
6363            TABLE.trim_end_matches('\n').len(),
6364            "the trailing stop is the table's own end, before its newline"
6365        );
6366        assert!(
6367            !m.table_end_stop(TABLE.rfind("12").unwrap() + 2),
6368            "a cell's end is not the trailing stop"
6369        );
6370        // A content row's `│` and padding are decoration; only the cell text
6371        // and each cell's one end-stop are stops.
6372        let header = &m.rows[1];
6373        assert!(!header.decoration);
6374        for g in &header.glyphs {
6375            if g.ch == '│' {
6376                assert!(!g.stop, "a border is not a caret stop");
6377            }
6378        }
6379        let stops: String = header
6380            .glyphs
6381            .iter()
6382            .filter(|g| g.stop)
6383            .map(|g| g.ch)
6384            .collect();
6385        assert_eq!(stops, "Name Qty ", "cell text plus one end-stop space each");
6386    }
6387
6388    #[test]
6389    fn a_cell_maps_to_its_own_source_text() {
6390        let m = map(TABLE);
6391        // "Pear" starts at byte 32 in TABLE; the caret there draws on the 'P'.
6392        let pear = TABLE.find("Pear").unwrap();
6393        let (r, c) = m.pos_of_offset(pear);
6394        assert_eq!(m.rows[r].glyphs[c].ch, 'P');
6395        assert_eq!(m.offset_of_pos(r, c), pear, "round trips");
6396    }
6397
6398    #[test]
6399    fn a_wide_table_is_cut_to_fit_and_its_cells_wrap() {
6400        // Columns wider than the surface used to run off the right edge, where
6401        // nothing could reach them. They're cut to the budget instead, and the
6402        // text wraps down inside the column — the header rule stays put, and
6403        // an alignment holds on every line of a wrapped cell, not just the first.
6404        let src = "| Ingredient | Notes |\n|---|---:|\n\
6405                   | flour milled coarse | sift it twice |\n| salt | a pinch |\n";
6406        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6407        let m = build_t(&ed.nodes().unwrap(), src, Some(30));
6408        let text = rendered(&m);
6409        assert_eq!(
6410            text,
6411            "┌──────────────┬─────────────┐\n\
6412             │ Ingredient   │       Notes │\n\
6413             ├──────────────┼─────────────┤\n\
6414             │ flour milled │     sift it │\n\
6415             │ coarse       │       twice │\n\
6416             │ salt         │     a pinch │\n\
6417             └──────────────┴─────────────┘",
6418            "got:\n{text}"
6419        );
6420        for (r, row) in m.rows.iter().enumerate() {
6421            assert!(
6422                row.glyphs.len() <= 30,
6423                "row {r} overflows: {}",
6424                row.glyphs.len()
6425            );
6426        }
6427    }
6428
6429    #[test]
6430    fn a_column_too_narrow_for_a_word_breaks_it_rather_than_spilling() {
6431        // A paragraph lets an overlong word trail off the end of the line; a
6432        // table column can't — a glyph past the border lands on the border.
6433        let src = "| A | B |\n|---|---|\n| antidisestablishmentarianism | x |\n";
6434        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6435        let m = build_t(&ed.nodes().unwrap(), src, Some(20));
6436        for (r, row) in m.rows.iter().enumerate() {
6437            assert!(
6438                row.glyphs.len() <= 20,
6439                "row {r} overflows: {}",
6440                row.glyphs.len()
6441            );
6442        }
6443        // Broken across lines, but whole: every letter is still drawn, at its
6444        // own source byte, where the caret can reach it.
6445        let word = "antidisestablishmentarianism";
6446        let at = src.find(word).unwrap();
6447        for (i, ch) in word.char_indices() {
6448            assert!(
6449                m.rows
6450                    .iter()
6451                    .flat_map(|r| r.glyphs.iter())
6452                    .any(|g| g.stop && g.src == at + i && g.ch == ch),
6453                "{ch:?} at {} was lost to the break",
6454                at + i
6455            );
6456        }
6457    }
6458
6459    #[test]
6460    fn a_code_block_maps_each_line_to_its_own_source_text() {
6461        // Every glyph used to point at the block's start, which made the whole
6462        // block one offset — visible, but impossible to put a caret inside.
6463        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
6464        let m = map(src);
6465        for row in &m.rows {
6466            for g in row.glyphs.iter().filter(|g| g.stop) {
6467                assert_eq!(
6468                    src[g.src..].chars().next(),
6469                    Some(g.ch),
6470                    "glyph {:?} at {} isn't the source byte it claims",
6471                    g.ch,
6472                    g.src
6473                );
6474            }
6475        }
6476    }
6477
6478    #[test]
6479    fn an_indented_code_block_maps_past_its_stripped_indent() {
6480        // twig strips the four-space indent, so `text` isn't a source slice and
6481        // the lines have to be re-found. Offsets land on the code, not the indent.
6482        let src = "    indented\n    code\n";
6483        let m = map(src);
6484        let stops: Vec<(char, usize)> = m
6485            .rows
6486            .iter()
6487            .flat_map(|r| r.glyphs.iter().filter(|g| g.stop).map(|g| (g.ch, g.src)))
6488            .collect();
6489        assert_eq!(
6490            stops[0],
6491            ('i', 4),
6492            "first line should start past the indent"
6493        );
6494        assert!(
6495            stops.contains(&('c', 17)),
6496            "second line misplaced: {stops:?}"
6497        );
6498    }
6499
6500    #[test]
6501    fn a_fenced_block_whose_code_echoes_its_info_string_maps_to_the_code() {
6502        // The one case that defeats a forward search: the opening fence
6503        // ```` ```rust ```` ends with the same text as the code under it.
6504        let src = "```rust\nrust\n```\n";
6505        let m = map(src);
6506        let first = m.rows[0].glyphs.iter().find(|g| g.stop).unwrap();
6507        assert_eq!(first.src, 8, "matched the info string, not the code");
6508    }
6509
6510    #[test]
6511    fn a_code_block_carries_no_gutter_and_is_published_as_a_row_span() {
6512        // The old `▏ ` gutter is gone: a code row is the block prefix (none, at
6513        // the top level) plus the code text, and the whole run is named in
6514        // `code_blocks` so a frontend can box it.
6515        let src = "para\n\n```\ncode\nlines\n```\n\nafter\n";
6516        let m = map(src);
6517        assert_eq!(m.code_blocks.len(), 1, "one code block");
6518        let span = m.code_blocks[0].rows_span.clone();
6519        let rows: Vec<String> = m.rows[span.clone()]
6520            .iter()
6521            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6522            .collect();
6523        assert_eq!(rows, vec!["code".to_string(), "lines".to_string()]);
6524        assert!(!rendered(&m).contains('▏'), "gutter still drawn");
6525        assert!(
6526            m.rows[span].iter().all(|r| r.code),
6527            "every row in the span is flagged code"
6528        );
6529    }
6530
6531    #[test]
6532    fn an_empty_last_line_in_a_code_block_is_a_row_of_its_own() {
6533        // `trim_end_matches('\n')` cut the block's terminator *and* the newline
6534        // that spells a trailing empty line, so the row the Return had just made
6535        // never appeared and the caret on it fell through to the block below.
6536        // Every empty line is a row, wherever in the block it falls.
6537        let src = "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n";
6538        let m = map(src);
6539        let span = m.code_blocks[0].rows_span.clone();
6540        let rows: Vec<String> = m.rows[span.clone()]
6541            .iter()
6542            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6543            .collect();
6544        assert_eq!(
6545            rows,
6546            vec!["alpha".to_string(), "beta".to_string(), String::new()],
6547            "the empty last line gets a row"
6548        );
6549        assert!(
6550            m.rows[span.clone()].iter().all(|r| r.code),
6551            "the empty row is flagged code like the rest of the block"
6552        );
6553        // And it is the *source's* empty line, not a coarse fallback to the
6554        // block start: the offset the caret resolves to is the one Return made.
6555        let empty = span.end - 1;
6556        assert_eq!(
6557            m.rows[empty].end_src,
6558            src.find("beta\n\n").unwrap() + "beta\n".len(),
6559            "the empty row maps to the line the Return opened"
6560        );
6561
6562        // Nothing is invented where there is no empty line, and a second one is
6563        // a second row.
6564        assert_eq!(
6565            map("```\nalpha\nbeta\n```\n").code_blocks[0]
6566                .rows_span
6567                .len(),
6568            2,
6569            "a block that ends at its last code line keeps two rows"
6570        );
6571        assert_eq!(
6572            map("```\nalpha\n\n\n```\n").code_blocks[0].rows_span.len(),
6573            3,
6574            "two trailing empty lines are two rows"
6575        );
6576    }
6577
6578    #[test]
6579    fn a_directive_container_is_tinted_and_labeled_on_its_first_row() {
6580        // diaryx's `:::vis{.public .family}` visibility block, and any other
6581        // `:::name{.class}` fenced div — core is agnostic of `name`.
6582        let src = ":::vis{.public .family}\nhello\n\nworld\n:::\nafter\n";
6583        let m = map_directives(src);
6584
6585        let content_rows: Vec<usize> = (0..m.rows.len()).filter(|&i| m.rows[i].directive).collect();
6586        assert!(!content_rows.is_empty(), "some row is flagged directive");
6587
6588        let after_rows: Vec<usize> = (0..m.rows.len())
6589            .filter(|&i| !content_rows.contains(&i) && !m.rows[i].glyphs.is_empty())
6590            .collect();
6591        assert!(
6592            after_rows.iter().all(|&i| !m.rows[i].directive),
6593            "content outside the fence isn't tinted"
6594        );
6595
6596        let labels: Vec<&str> = content_rows
6597            .iter()
6598            .filter_map(|&i| m.rows[i].directive_label.as_deref())
6599            .collect();
6600        assert_eq!(
6601            labels,
6602            vec!["public family"],
6603            "only the first row carries the label"
6604        );
6605
6606        assert_eq!(
6607            rendered(&m)
6608                .lines()
6609                .filter(|l| !l.is_empty())
6610                .collect::<Vec<_>>(),
6611            vec!["hello", "world", "after"],
6612            "fence markers don't leak into the rendered text"
6613        );
6614    }
6615
6616    #[test]
6617    fn a_bare_word_directive_is_labeled_same_as_dot_classes() {
6618        // diaryx_core::visibility's own `:::vis{public family}` — no leading
6619        // dots — is what apps/web's directive serializer and the native
6620        // publish-time filter both actually write today, distinct from twig's
6621        // `.class` convention. Both must label the same way so every existing
6622        // diaryx `:::vis{...}` block reads, not just newly dot-authored ones.
6623        let src = ":::vis{public family}\nhello\n:::\n";
6624        let m = map_directives(src);
6625        let label = m.rows.iter().find_map(|r| r.directive_label.clone());
6626        assert_eq!(label.as_deref(), Some("public family"));
6627    }
6628
6629    #[test]
6630    fn a_text_directive_keeps_its_paragraph_visible() {
6631        // Regression: an inline `:name[label]{…}` used to make its paragraph
6632        // fail the "all children inline" test, so the whole line was walked as
6633        // a container of blocks and rendered as empty rows with NO caret stops —
6634        // the text vanished from the editor and the caret couldn't enter it.
6635        // diaryx's inline `:vis[…]` is exactly this shape.
6636        let src = "Text with :abbr[HTML]{title=\"HyperText\"} inline.\n";
6637        let m = map_directives(src);
6638        assert_eq!(rendered(&m).trim_end(), "Text with HTML inline.");
6639        // Every character of the line is a caret home, markup excluded — the
6640        // label reads as ordinary text, the way a link's does.
6641        let stops: usize = m
6642            .rows
6643            .iter()
6644            .map(|r| r.glyphs.iter().filter(|g| g.stop).count())
6645            .sum();
6646        assert_eq!(stops, "Text with HTML inline.".chars().count());
6647        // It is inline, so it is not the container form's tinted panel.
6648        assert!(m.rows.iter().all(|r| !r.directive));
6649    }
6650
6651    #[test]
6652    fn a_text_directives_label_maps_to_its_true_source_bytes() {
6653        // Regression (needs twig-doc >= 2.5.0): twig parses a `[label]` as a
6654        // detached slice, and until it rebased the enclosing scan's segments
6655        // onto it every node inside the label reported a span of `(0,0)`. Read
6656        // by anything that trusts a span that means "byte 0", so the label's
6657        // glyphs mapped to the START OF THE DOCUMENT — a click on the label put
6658        // the caret at the top of the file, its stops collided with the real
6659        // first line's, and an edit there landed on the wrong bytes entirely.
6660        //
6661        // The sibling test `a_text_directive_keeps_its_paragraph_visible` only
6662        // counts stops, which is exactly why this went unnoticed: the right
6663        // NUMBER of stops at completely wrong offsets.
6664        let src = "x :abbr[HTML]{title=\"y\"} z\n";
6665        let m = map_directives(src);
6666        let stops: Vec<(char, usize)> = m
6667            .rows
6668            .iter()
6669            .flat_map(|r| &r.glyphs)
6670            .filter(|g| g.stop)
6671            .map(|g| (g.ch, g.src))
6672            .collect();
6673        // `HTML` sits at 8..12. The name, brackets and `{…}` are hidden markup
6674        // the caret steps over, so the line's stops run 0, 1, 8..12, then 24.
6675        assert_eq!(
6676            stops,
6677            [
6678                ('x', 0),
6679                (' ', 1),
6680                ('H', 8),
6681                ('T', 9),
6682                ('M', 10),
6683                ('L', 11),
6684                (' ', 24),
6685                ('z', 25)
6686            ]
6687        );
6688    }
6689
6690    #[test]
6691    fn every_glyph_in_a_directive_label_points_at_its_source_byte() {
6692        // The `every_glyph_points_at_its_source_byte` invariant, extended over
6693        // directive labels now that their offsets are real. Nested markup is
6694        // included: its delimiters are hidden, so the visible glyphs must skip
6695        // them and still name their own bytes.
6696        let src = "x :abbr[a *b* c] y and :vis[family only] z\n";
6697        let m = map_directives(src);
6698        for g in m.rows.iter().flat_map(|r| &r.glyphs).filter(|g| g.stop) {
6699            let at = src[g.src..].chars().next();
6700            assert_eq!(
6701                at,
6702                Some(g.ch),
6703                "glyph {:?} claims byte {}, which is {at:?}",
6704                g.ch,
6705                g.src
6706            );
6707        }
6708        assert_eq!(rendered(&m).trim_end(), "x a b c y and family only z");
6709    }
6710
6711    #[test]
6712    fn a_directive_labels_nested_emphasis_keeps_both_its_style_and_its_offsets() {
6713        let src = "x :abbr[a *b* c] y\n";
6714        let m = map_directives(src);
6715        let b = m
6716            .rows
6717            .iter()
6718            .flat_map(|r| &r.glyphs)
6719            .find(|g| g.ch == 'b')
6720            .expect("the emphasised char");
6721        assert!(b.style.italic, "the label's *b* lost its emphasis");
6722        assert_eq!(b.src, 11, "the label's *b* lost its source byte");
6723    }
6724
6725    #[test]
6726    fn a_bare_colon_word_renders_as_the_prose_it_almost_always_is() {
6727        // Regression: twig matches a colon followed by any letter-led word, so
6728        // ordinary prose is full of "text directives" nobody meant to write.
6729        // With no `[label]` there are no children, and the arm recursed into
6730        // them — rendering *nothing*. The word vanished from the document with
6731        // no caret stop left behind, so it could not even be deleted.
6732        for src in ["a :word b\n", "note :see below\n", ":smile: hi\n"] {
6733            let m = map_directives(src);
6734            assert_eq!(
6735                rendered(&m).trim_end(),
6736                src.trim_end(),
6737                "prose was eaten: {src:?}"
6738            );
6739        }
6740    }
6741
6742    #[test]
6743    fn a_bare_colon_word_keeps_every_byte_a_caret_stop() {
6744        let src = "a :word b\n";
6745        let m = map_directives(src);
6746        // Nothing here is markup, so nothing is hidden: each byte maps to
6747        // itself and can be stood on, which is what makes the colon deletable.
6748        let stops: Vec<(char, usize)> = m
6749            .rows
6750            .iter()
6751            .flat_map(|r| &r.glyphs)
6752            .filter(|g| g.stop)
6753            .map(|g| (g.ch, g.src))
6754            .collect();
6755        assert_eq!(
6756            stops,
6757            "a :word b"
6758                .chars()
6759                .enumerate()
6760                .map(|(i, c)| (c, i))
6761                .collect::<Vec<_>>()
6762        );
6763    }
6764
6765    #[test]
6766    fn an_attribute_bearing_text_directive_draws_a_chip() {
6767        // `{…}` is deliberate in a way a bare colon is not — diaryx writes
6768        // `:vis{.family}` inline — so this one reads as an embed, on the same
6769        // `⧉ label` recipe the leaf form's placeholder row uses.
6770        // Both attribute conventions label it: twig's dot-prefixed classes and
6771        // the bare pandoc-style words diaryx also writes.
6772        for src in ["a :vis{.family} b\n", "a :vis{family} b\n"] {
6773            let m = map_directives(src);
6774            assert_eq!(rendered(&m).trim_end(), "a ⧉ vis family b", "{src:?}");
6775        }
6776        // A `key=value` attr is configuration, not a name, so it adds nothing.
6777        let m = map_directives("a :foo{title=\"x\"} b\n");
6778        assert_eq!(rendered(&m).trim_end(), "a ⧉ foo b");
6779    }
6780
6781    #[test]
6782    fn a_directive_chip_is_one_atomic_caret_stop_at_its_own_offset() {
6783        let src = "a :vis{.family} b\n";
6784        let m = map_directives(src);
6785        let stops: Vec<usize> = m
6786            .rows
6787            .iter()
6788            .flat_map(|r| &r.glyphs)
6789            .filter(|g| g.stop)
6790            .map(|g| g.src)
6791            .collect();
6792        // The chip contributes exactly one stop, at the directive's start (2),
6793        // so the caret steps over it whole instead of walking hidden markup a
6794        // byte at a time. `{.family}`'s bytes (3..15) are never stood on.
6795        assert_eq!(stops, [0, 1, 2, 15, 16]);
6796    }
6797
6798    #[test]
6799    fn a_paragraph_holding_only_a_chip_is_still_navigable() {
6800        // With no stop of its own the row would be unreachable — the caret
6801        // could never be put on the line to edit or delete the directive.
6802        let m = map_directives(":vis{.family}\n");
6803        assert!(
6804            m.row_is_navigable(0),
6805            "a chip-only paragraph has no caret home"
6806        );
6807        assert_eq!(
6808            m.offset_of_pos(0, 0),
6809            0,
6810            "its caret home isn't the directive's start"
6811        );
6812    }
6813
6814    #[test]
6815    fn a_ratio_or_a_clock_time_is_never_a_directive() {
6816        // twig requires a letter after the colon, so these stay prose — the
6817        // verbatim arm must not be reached for them at all.
6818        let src = "ratio 3:4 and 10:30\n";
6819        assert_eq!(
6820            rendered(&map_directives(src)).trim_end(),
6821            "ratio 3:4 and 10:30"
6822        );
6823    }
6824
6825    #[test]
6826    fn a_leaf_directive_is_a_placeholder_row_with_its_attrs_published() {
6827        // `::name{…}` is a standalone block with no body — an embed, a table of
6828        // contents. It used to emit no rows at all: invisible, no caret home,
6829        // vertical motion crossing a void. Now it draws the image recipe's
6830        // placeholder and publishes what the host app needs to paint the real
6831        // thing.
6832        let src = "before\n\n::embed{src=\"demo.html\" height=\"400\"}\n\nafter\n";
6833        let m = map_directives(src);
6834
6835        let row = m
6836            .rows
6837            .iter()
6838            .position(|r| r.leaf_directive.is_some())
6839            .expect("a placeholder row");
6840        assert_eq!(
6841            m.rows[row].glyphs.iter().map(|g| g.ch).collect::<String>(),
6842            "⧉ embed"
6843        );
6844        assert!(
6845            m.rows[row].glyphs.iter().any(|g| g.stop),
6846            "the caret can land on it"
6847        );
6848        assert!(
6849            m.rows[row].directive,
6850            "a frontend frames it like the container form"
6851        );
6852
6853        assert_eq!(m.directives.len(), 1);
6854        let info = &m.directives[0];
6855        assert_eq!(info.name, "embed");
6856        assert_eq!(info.rows_span, row..row + 1);
6857        assert_eq!(info.attr("src"), Some("demo.html"));
6858        assert_eq!(info.attr("height"), Some("400"));
6859        assert_eq!(info.attr("nope"), None);
6860        // The prose around it is untouched.
6861        assert!(rendered(&m).contains("before") && rendered(&m).contains("after"));
6862    }
6863
6864    #[test]
6865    fn a_leaf_directive_shows_its_label_and_honours_its_prefix() {
6866        // A `[label]` names the placeholder (the way an image's alt does), and a
6867        // quoted directive keeps the quote's gutter — it is a block like any
6868        // other, not a special case that escapes its container.
6869        let m = map_directives("::embed[Audience demo]{src=\"demo.html\"}\n");
6870        assert_eq!(rendered(&m).trim_end(), "⧉ Audience demo");
6871        assert_eq!(m.directives[0].label, "Audience demo");
6872
6873        let quoted = map_directives("> ::embed{src=\"x.html\"}\n");
6874        assert_eq!(rendered(&quoted).trim_end(), "│ ⧉ embed");
6875        assert_eq!(quoted.directives[0].name, "embed");
6876    }
6877
6878    #[test]
6879    fn a_container_directive_is_still_a_panel_not_a_placeholder() {
6880        // The three forms must not bleed into each other: only the leaf form is
6881        // a placeholder, and only the container form tints the blocks it wraps.
6882        let m = map_directives(":::note{.warning}\nBody\n:::\n");
6883        assert!(
6884            m.directives.is_empty(),
6885            "a container publishes no placeholder"
6886        );
6887        assert!(m.rows.iter().all(|r| r.leaf_directive.is_none()));
6888        assert_eq!(rendered(&m).trim_end(), "Body");
6889        assert!(
6890            m.rows
6891                .iter()
6892                .any(|r| r.directive && r.directive_label.as_deref() == Some("warning"))
6893        );
6894    }
6895
6896    /// A production-path build with both extensions on — the only way to put a
6897    /// promoted HTML element and a directive in one document, which is what the
6898    /// `container` kind made necessary to tell apart. Returns the whole `Doc`
6899    /// because [`VisualMap`] is not `Clone`; read `doc.vmap`.
6900    fn doc_built(src: &str) -> crate::Doc {
6901        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
6902        doc.build_visual(80);
6903        doc
6904    }
6905
6906    /// Every `container` node in `src`, parsed the way production does (both
6907    /// extensions on), paired with what [`container_is_directive`] makes of it.
6908    fn containers(src: &str) -> Vec<(String, bool, Option<DirectiveForm>)> {
6909        let mut ed = Editor::new_ext(
6910            src.as_bytes(),
6911            Format::Markdown,
6912            twig::MarkdownExtensions {
6913                directives: true,
6914                html_elements: true,
6915                ..Default::default()
6916            },
6917        )
6918        .unwrap();
6919        ed.nodes()
6920            .unwrap()
6921            .iter()
6922            .filter(|n| n.kind == Kind::Container)
6923            .map(|n| {
6924                (
6925                    n.name.clone().unwrap_or_default(),
6926                    container_is_directive(n),
6927                    n.directive_form,
6928                )
6929            })
6930            .collect()
6931    }
6932
6933    #[test]
6934    fn a_directive_and_an_html_element_are_told_apart_by_spelling_not_by_form() {
6935        // twig 2.8 folded `div`/`span`/`directive`/`element` into one `container`
6936        // kind. `directive_form` reads as though it separates them and does not:
6937        // a block-level `<div>` reports `Some(DirectiveForm::Container)` exactly
6938        // as a `:::note` does. Trusting it would draw directive chrome — a tinted
6939        // panel, a `.class` audience label — on every pasted Slack/Docs div.
6940        for (src, name, want) in [
6941            (":::note{.a}\nbody\n:::\n", "note", true),
6942            ("::embed{src=x}\n", "embed", true),
6943            ("a :vis[hi]{.b} b\n", "vis", true),
6944            ("<div class=\"x\">\nhi\n</div>\n", "div", false),
6945            ("<video src=\"v.mp4\" controls></video>\n", "video", false),
6946            ("<audio src=\"a.mp3\" controls></audio>\n", "audio", false),
6947            ("<figure>\n\nhi\n\n</figure>\n", "figure", false),
6948            // The `:` in an attribute must not read as a directive opener: the
6949            // `<` of the tag comes first, and first one wins.
6950            (
6951                "<video src=\"http://x.test/v.mp4\" controls></video>\n",
6952                "video",
6953                false,
6954            ),
6955            (
6956                "<source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\n",
6957                "source",
6958                false,
6959            ),
6960        ] {
6961            let found = containers(src);
6962            let hit = found.iter().find(|(n, ..)| n == name);
6963            let Some((_, is_directive, form)) = hit else {
6964                panic!("no `{name}` container in {src:?} — found {found:?}");
6965            };
6966            assert_eq!(*is_directive, want, "{name} in {src:?} (form was {form:?})");
6967        }
6968
6969        // And the reason this can't just read the field: for the one collision
6970        // that matters, the field says the same thing for both.
6971        let div = containers("<div class=\"x\">\nhi\n</div>\n");
6972        let note = containers(":::note{.a}\nbody\n:::\n");
6973        assert_eq!(
6974            div[0].2, note[0].2,
6975            "if these ever differ, `directive_form` became usable and this rule can go"
6976        );
6977    }
6978
6979    #[test]
6980    fn a_directive_nested_in_a_quote_or_list_is_still_a_directive() {
6981        // A container's span opens with its *block prefix*, not its own markup —
6982        // `> ::embed{…}` starts at the `>`. Reading only the first byte to tell a
6983        // directive from an element (both `container` since 2.8) therefore misses
6984        // every nested one, and the placeholder silently renders as nothing.
6985        for (src, ctx) in [
6986            ("> ::embed{src=\"x\"}\n", "quoted"),
6987            ("- ::embed{src=\"x\"}\n", "listed"),
6988            (">> ::embed{src=\"x\"}\n", "twice quoted"),
6989        ] {
6990            let m = map_directives(src);
6991            assert_eq!(m.directives.len(), 1, "{ctx} directive was lost");
6992            assert_eq!(m.directives[0].name, "embed", "{ctx}");
6993        }
6994    }
6995
6996    #[test]
6997    fn a_video_is_still_media_and_not_a_directive() {
6998        // The other side of the same coin: `<video>` is a `container` too, and
6999        // must reach `block_media` rather than the directive arms.
7000        let doc = doc_built("<video src=\"clip.mp4\" controls></video>\n");
7001        assert_eq!(doc.vmap.media.len(), 1, "the video is block media");
7002        assert!(
7003            doc.vmap.rows.iter().all(|r| !r.directive),
7004            "the video drew directive chrome"
7005        );
7006    }
7007
7008    #[test]
7009    fn a_directive_needs_the_extension_flag() {
7010        // `map` (twig's default extensions) leaves `directives` off — the fence
7011        // renders as literal paragraph text, same as any other unrecognized
7012        // punctuation, never corrupting or panicking.
7013        let src = ":::vis{.public}\nhello\n:::\n";
7014        let m = map(src);
7015        assert!(m.rows.iter().all(|r| !r.directive));
7016        assert!(rendered(&m).contains(":::vis{.public}"));
7017    }
7018
7019    #[test]
7020    fn a_footnote_reference_keeps_its_paragraph_visible() {
7021        // Regression: `footnote_reference` was in neither `is_inline_kind` nor
7022        // the inline walker, so a paragraph carrying one failed the "all children
7023        // inline" test, was walked as a container of blocks, and rendered as
7024        // empty rows with no caret stop anywhere — the whole line vanished.
7025        let src = "A claim[^1] and more.\n";
7026        let m = map(src);
7027        assert_eq!(rendered(&m).trim_end(), "A claim[1] and more.");
7028        // The `^` is spelling, not text: hidden the way a link's `](dest)` is.
7029        assert!(!rendered(&m).contains('^'));
7030    }
7031
7032    #[test]
7033    fn a_footnote_reference_is_raised_and_the_prose_around_it_is_not() {
7034        // What makes `[1]` read as a reference rather than as bracketed text.
7035        // The brackets ride with the label: the chip is one raised mark.
7036        let m = map("A claim[^1] and more.\n");
7037        assert_eq!(baselines_of(&m, '1'), vec![Baseline::Super]);
7038        assert_eq!(baselines_of(&m, '['), vec![Baseline::Super]);
7039        assert_eq!(baselines_of(&m, ']'), vec![Baseline::Super]);
7040        assert_eq!(baselines_of(&m, 'A'), vec![Baseline::Normal]);
7041    }
7042
7043    #[test]
7044    fn a_footnote_reference_keeps_the_link_role_it_had() {
7045        // The raised baseline is added to the role, not swapped for it: every
7046        // frontend already paints `Role::Link`, and a reference is one.
7047        let m = map("A claim[^1].\n");
7048        let label = m
7049            .rows
7050            .iter()
7051            .flat_map(|r| &r.glyphs)
7052            .find(|g| g.ch == '1')
7053            .unwrap();
7054        assert_eq!(label.style.role, Role::Link);
7055        assert_eq!(label.style.baseline, Baseline::Super);
7056    }
7057
7058    /// The [`Role`] of the first glyph spelling `ch` — how a test reads one
7059    /// run's styling off a map without caring which row it landed on.
7060    fn role_of(m: &VisualMap, ch: char) -> Role {
7061        m.rows
7062            .iter()
7063            .flat_map(|r| r.glyphs.iter())
7064            .find(|g| g.ch == ch)
7065            .unwrap_or_else(|| panic!("no glyph spelling {ch:?}"))
7066            .style
7067            .role
7068    }
7069
7070    #[test]
7071    fn a_markdown_highlight_is_a_mark_and_a_coloured_one_names_its_colour() {
7072        // twig 3.3's `highlight`/`highlight_colors`, which `parse_extensions`
7073        // turns on for every leaf document: `==text==` is a `mark` in Markdown
7074        // and not the literal `==` it used to be, and `==🔴 text==` is one
7075        // carrying a colour.
7076        //
7077        // `doc_built` rather than `map`, deliberately — the extensions are
7078        // leaf's choice, not twig's default, so a test that parsed bare
7079        // Markdown here would be testing a document leaf never builds.
7080        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
7081        assert_eq!(role_of(&doc.vmap, 'y'), Role::Mark(None));
7082        assert_eq!(
7083            role_of(&doc.vmap, 'r'),
7084            Role::Mark(Some(MarkColor::Red)),
7085            "the `data-color` twig stripped the emoji into"
7086        );
7087        assert_eq!(role_of(&doc.vmap, 'P'), Role::Body);
7088    }
7089
7090    #[test]
7091    fn the_emoji_that_named_a_highlight_is_markup_and_never_drawn() {
7092        // The colour is *spelling*: twig strips the emoji out of the mark's
7093        // content, so the reader sees the words and the wash, never the circle.
7094        // Drawing it would put a character in the rendered text that the author
7095        // wrote as syntax — the same mistake as drawing an emphasis's `*`.
7096        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
7097        let drawn: String = doc.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
7098        assert_eq!(drawn, "Plain yes and red ok");
7099    }
7100
7101    #[test]
7102    fn a_superscript_and_a_subscript_sit_off_the_baseline() {
7103        // Regression: both rendered flat, so the toolbar's superscript button
7104        // produced markup that looked exactly like the text around it.
7105        let m = map_djot("H~2~O and x^2^\n");
7106        assert_eq!(baselines_of(&m, '2'), vec![Baseline::Sub, Baseline::Super]);
7107        assert_eq!(baselines_of(&m, 'H'), vec![Baseline::Normal]);
7108        assert_eq!(baselines_of(&m, 'O'), vec![Baseline::Normal]);
7109    }
7110
7111    #[test]
7112    fn a_raised_glyph_keeps_the_style_it_was_raised_out_of() {
7113        // Why this is a `Baseline` and not a `Role`: raising a glyph says where
7114        // it sits, and must not cost it what it already was.
7115        let m = map_djot("# Heading x^2^\n");
7116        let two = m
7117            .rows
7118            .iter()
7119            .flat_map(|r| &r.glyphs)
7120            .find(|g| g.ch == '2')
7121            .unwrap();
7122        assert_eq!(two.style.baseline, Baseline::Super);
7123        assert_eq!(two.style.role, Role::Heading(1), "still heading text");
7124    }
7125
7126    #[test]
7127    fn a_footnote_references_brackets_are_decoration_and_only_its_label_is_a_stop() {
7128        let src = "see[^note] here\n";
7129        let m = map(src);
7130        // `[^note]` spans 3..10, its label `note` 5..9. The caret walks the
7131        // label; the brackets are drawn but never stood on, as a table's are,
7132        // and the `[^`/`]` bytes are stepped over like any hidden delimiter.
7133        let stops: Vec<usize> = m
7134            .rows
7135            .iter()
7136            .flat_map(|r| &r.glyphs)
7137            .filter(|g| g.stop)
7138            .map(|g| g.src)
7139            .collect();
7140        for off in 5..9 {
7141            assert!(
7142                stops.contains(&off),
7143                "label byte {off} isn't a caret stop: {stops:?}"
7144            );
7145        }
7146        for off in [3usize, 4, 9] {
7147            assert!(
7148                !stops.contains(&off),
7149                "delimiter byte {off} is a caret stop: {stops:?}"
7150            );
7151        }
7152    }
7153
7154    #[test]
7155    fn a_task_item_draws_its_box_where_the_bullet_would_be() {
7156        // Regression: the `[ ] ` is markup twig consumes — the item's paragraph
7157        // content starts past it — so a task item used to render as `• todo`,
7158        // identical to a plain bullet and with no way to see it was ticked.
7159        let m = map("- [ ] todo\n- [x] done\n- plain\n");
7160        assert_eq!(rendered(&m), "☐ todo\n☑ done\n• plain");
7161
7162        // The tick rides the item's first row, for a GUI that paints its own box.
7163        let ticks: Vec<Option<bool>> = m.rows.iter().map(|r| r.task).collect();
7164        assert_eq!(ticks, [Some(false), Some(true), None]);
7165    }
7166
7167    #[test]
7168    fn a_task_items_box_survives_a_wrap_and_marks_only_the_first_row() {
7169        let m = map_at(
7170            "- [x] a much longer task that has to wrap somewhere\n",
7171            Some(20),
7172        );
7173        assert!(m.rows.len() > 1, "the item should wrap: {:?}", rendered(&m));
7174        assert_eq!(m.rows[0].task, Some(true));
7175        assert!(
7176            m.rows[1..].iter().all(|r| r.task.is_none()),
7177            "only the first row"
7178        );
7179        // The continuation lines hang under the box, not under column zero.
7180        assert!(
7181            rendered(&m)
7182                .lines()
7183                .nth(1)
7184                .is_some_and(|l| l.starts_with("  "))
7185        );
7186    }
7187
7188    #[test]
7189    fn a_bracket_in_an_items_prose_is_not_a_checkbox() {
7190        // `task_checked` finds the box past the list marker; a plain item whose
7191        // text merely contains a bracket has none, and must keep its bullet.
7192        let m = map("- see [1] below\n");
7193        assert_eq!(rendered(&m), "• see [1] below");
7194        assert_eq!(m.rows[0].task, None);
7195    }
7196
7197    #[test]
7198    fn a_footnote_definition_renders_where_it_was_written() {
7199        // Regression: twig parses `[^1]: …` as a root *beside* `doc` — not a
7200        // child of it — so the walk from `doc` never reached one and every byte
7201        // of the note's body rendered as nothing at all.
7202        let src = "A claim[^1].\n\n[^1]: The note body.\n\nAfter.\n";
7203        let m = map(src);
7204        let text = rendered(&m);
7205        assert!(
7206            text.contains("The note body."),
7207            "the note body is invisible: {text:?}"
7208        );
7209        // In source order — between the paragraph that cites it and the one
7210        // after — not hoisted to the end, and marked to match its reference.
7211        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
7212        assert_eq!(lines, ["A claim[1].", "[1] The note body.", "After."]);
7213    }
7214
7215    #[test]
7216    fn a_footnote_definitions_body_maps_to_its_own_source_bytes() {
7217        let src = "x[^a].\n\n[^a]: body\n";
7218        let m = map(src);
7219        // `body` sits at 14..18. Its glyphs must map there — a marker that ate
7220        // the offsets would put the caret in the wrong place on every click.
7221        let body: Vec<(char, usize)> = m
7222            .rows
7223            .iter()
7224            .flat_map(|r| &r.glyphs)
7225            .filter(|g| g.stop && g.src >= 14)
7226            .map(|g| (g.ch, g.src))
7227            .collect();
7228        assert_eq!(body, [('b', 14), ('o', 15), ('d', 16), ('y', 17)]);
7229    }
7230
7231    #[test]
7232    fn an_empty_footnote_definition_still_shows_its_marker() {
7233        // The instant `[^1]: ` has been typed and nothing after it. `blocks`
7234        // renders no child, so without the explicit marker row the definition
7235        // wouldn't appear at all until something was typed into it.
7236        let src = "x[^1]\n\n[^1]:\n";
7237        let m = map(src);
7238        assert!(
7239            rendered(&m).contains("[1] "),
7240            "no marker row: {:?}",
7241            rendered(&m)
7242        );
7243    }
7244
7245    #[test]
7246    fn a_footnote_definition_wearing_a_long_label_indents_its_wrapped_body() {
7247        let src = "x[^src]\n\n[^src]: one two three four five six seven\n";
7248        let m = map_at(src, Some(24));
7249        let text = rendered(&m);
7250        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
7251        // Continuation lines hang under the marker, as a list item's do — the
7252        // indent is the marker's own width, not a fixed one.
7253        assert_eq!(lines[1].trim_end(), "[src] one two three four");
7254        assert!(
7255            lines[2].starts_with("      "),
7256            "body doesn't hang: {:?}",
7257            lines[2]
7258        );
7259        assert_eq!(lines[2].trim(), "five six seven");
7260    }
7261
7262    #[test]
7263    fn a_code_block_leaves_exactly_one_blank_row_below_it() {
7264        // The closing fence line used to be miscounted as a blank separator,
7265        // opening a phantom second gap under the block. One block boundary is
7266        // one blank row, code block or not.
7267        let src = "para\n\n```\ncode\n```\n\nafter\n";
7268        let m = map(src);
7269        let code_end = m.code_blocks[0].rows_span.end;
7270        let after = m
7271            .rows
7272            .iter()
7273            .position(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "after")
7274            .unwrap();
7275        assert_eq!(
7276            after - code_end,
7277            1,
7278            "exactly one row between code and 'after'"
7279        );
7280    }
7281
7282    #[test]
7283    fn a_fenced_block_publishes_its_language_on_its_code_block() {
7284        // The info string becomes the block's label; a bare fence and an indented
7285        // block carry none.
7286        assert_eq!(
7287            map("```rust\nlet x = 1;\n```\n").code_blocks[0]
7288                .lang
7289                .as_deref(),
7290            Some("rust")
7291        );
7292        assert_eq!(map("```\nplain\n```\n").code_blocks[0].lang, None);
7293        assert_eq!(map("    indented\n").code_blocks[0].lang, None);
7294    }
7295
7296    /// The token every glyph spelling `ch` carries, in row order — how a test
7297    /// reads a block's highlighting off the map.
7298    fn tokens_of(m: &VisualMap, ch: char) -> Vec<Option<Token>> {
7299        m.rows
7300            .iter()
7301            .flat_map(|r| r.glyphs.iter())
7302            .filter(|g| g.ch == ch)
7303            .map(|g| g.style.token)
7304            .collect()
7305    }
7306
7307    #[cfg(feature = "syntax")]
7308    #[test]
7309    fn a_fenced_block_in_a_known_language_carries_tokens() {
7310        // `let` is a keyword, the string literal a string, and the plain
7311        // identifier `x` nothing at all — it draws in the code colour. Every
7312        // glyph is still `Role::Code`: a token is beside the role, not instead.
7313        let m = map("```rust\nlet x = \"s\";\n```\n");
7314        assert_eq!(tokens_of(&m, 'l'), vec![Some(Token::Keyword)]);
7315        assert_eq!(tokens_of(&m, 'x'), vec![None]);
7316        assert_eq!(tokens_of(&m, '"'), vec![Some(Token::String); 2]);
7317        assert!(
7318            m.rows
7319                .iter()
7320                .filter(|r| r.code)
7321                .flat_map(|r| r.glyphs.iter())
7322                .all(|g| g.style.role == Role::Code),
7323            "a token replaced the code role"
7324        );
7325    }
7326
7327    #[cfg(feature = "syntax")]
7328    #[test]
7329    fn a_token_changes_nothing_about_where_a_glyph_is() {
7330        // The same block with and without a language it can be highlighted in
7331        // lays out identically: same rows, same offsets, same stops. Only the
7332        // token differs, so the caret walks a highlighted block as it walked an
7333        // unhighlighted one.
7334        let hl = map("```rust\nlet x = 1; // c\nfn f() {}\n```\n");
7335        let plain = map("```text\nlet x = 1; // c\nfn f() {}\n```\n");
7336        assert_eq!(hl.rows.len(), plain.rows.len());
7337        for (a, b) in hl.rows.iter().zip(&plain.rows) {
7338            assert_eq!(a.end_src, b.end_src);
7339            assert_eq!(a.glyphs.len(), b.glyphs.len());
7340            for (ga, gb) in a.glyphs.iter().zip(&b.glyphs) {
7341                assert_eq!((ga.ch, ga.src, ga.stop), (gb.ch, gb.src, gb.stop));
7342                assert_eq!(ga.style.token(None), gb.style);
7343            }
7344        }
7345        assert!(tokens_of(&hl, 'l').iter().any(Option::is_some));
7346        assert!(tokens_of(&plain, 'l').iter().all(Option::is_none));
7347    }
7348
7349    #[test]
7350    fn a_block_with_no_language_to_highlight_in_carries_no_tokens() {
7351        // A bare fence, an indented block, a fence in a language no grammar
7352        // covers, and inline code all draw as plain code — and so does a
7353        // `rust` fence when the `syntax` feature is off.
7354        for src in [
7355            "```\nlet x = 1;\n```\n",
7356            "    let x = 1;\n",
7357            "```no-such-language\nlet x = 1;\n```\n",
7358            "a `let x` b\n",
7359        ] {
7360            assert!(
7361                tokens_of(&map(src), 'l').iter().all(Option::is_none),
7362                "{src:?} was highlighted"
7363            );
7364        }
7365        #[cfg(not(feature = "syntax"))]
7366        assert!(
7367            tokens_of(&map("```rust\nlet x = 1;\n```\n"), 'l')
7368                .iter()
7369                .all(Option::is_none)
7370        );
7371    }
7372
7373    #[test]
7374    fn inline_code_is_not_a_code_block() {
7375        // A `code` span inside prose is styled by role, not boxed: it's part of a
7376        // normal paragraph row, so it names no `code_blocks` entry.
7377        let m = map("a `snippet` b\n");
7378        assert!(m.code_blocks.is_empty(), "inline code wrongly boxed");
7379        assert!(
7380            m.rows.iter().all(|r| !r.code),
7381            "inline code flagged a code row"
7382        );
7383    }
7384
7385    #[test]
7386    fn caret_steps_over_hidden_delimiters() {
7387        // "a **bold** c": bytes 8,9 are the closing ** — no glyph. Moving right
7388        // from 'd' (src 7) lands on the space before 'c' (src 10), not inside **.
7389        let m = map("a **bold** c\n");
7390        let (r, c) = m.pos_of_offset(7);
7391        assert_eq!(m.offset_of_pos(r, c + 1), 10);
7392    }
7393
7394    // ── the structural view of a table ───────────────────────────────────────
7395
7396    #[test]
7397    fn a_table_is_published_structurally_beside_its_picture() {
7398        let m = map(TABLE);
7399        let t = &m.tables[0];
7400        let cell = |r: usize, c: usize| -> String {
7401            t.grid[r].cells[c].glyphs.iter().map(|g| g.ch).collect()
7402        };
7403        assert_eq!(t.grid.len(), 3, "head + two body rows");
7404        assert_eq!(
7405            (cell(0, 0), cell(0, 1), cell(1, 0), cell(2, 1)),
7406            ("Name".into(), "Qty".into(), "Pear".into(), "12".into())
7407        );
7408        assert_eq!(
7409            t.grid.iter().map(|r| r.head).collect::<Vec<_>>(),
7410            [true, false, false]
7411        );
7412        // The alignment the delimiter row spelled, carried per cell — the only
7413        // place it survives, since the parser consumes that row.
7414        assert!(matches!(t.grid[1].cells[0].align, Alignment::Left));
7415        assert!(matches!(t.grid[1].cells[1].align, Alignment::Right));
7416    }
7417
7418    #[test]
7419    fn a_block_media_is_published_structurally_beside_its_placeholder() {
7420        let m = map("intro\n\n![a cat](img/cat.png)\n\nend\n");
7421        assert_eq!(m.media.len(), 1, "one block image");
7422        let img = &m.media[0];
7423        assert_eq!(img.destination, "img/cat.png");
7424        assert_eq!(img.alt, "a cat");
7425        // The placeholder row named by `rows_span` carries the label a plain
7426        // surface paints and a capable frontend replaces.
7427        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
7428        assert_eq!(
7429            img.rows_span.end - img.rows_span.start,
7430            1,
7431            "one placeholder row"
7432        );
7433        assert_eq!(row_text(img.rows_span.start), "🖼 a cat");
7434        // The row carries the mark `media_spans` derives the side-table from.
7435        assert!(m.rows[img.rows_span.start].media.is_some());
7436    }
7437
7438    #[test]
7439    fn an_image_without_alt_labels_itself_with_its_filename() {
7440        let m = map("![](photos/beach.jpg)\n");
7441        let row = &m.rows[m.media[0].rows_span.start];
7442        assert_eq!(
7443            row.glyphs.iter().map(|g| g.ch).collect::<String>(),
7444            "🖼 beach.jpg"
7445        );
7446        assert_eq!(m.media[0].alt, "");
7447    }
7448
7449    #[test]
7450    fn an_empty_cells_home_is_read_from_either_shape_of_span() {
7451        // A whole-row span: the cell's pipes are the `col`-th and next.
7452        let row = "|  |  |";
7453        assert_eq!(empty_cell_offset(row, 10, 0), 12);
7454        assert_eq!(empty_cell_offset(row, 10, 1), 15);
7455        // A cell's own span, opening pipe to closing pipe exclusive: the same
7456        // homes, each read from its own span.
7457        assert_eq!(empty_cell_offset("|  ", 10, 0), 12);
7458        assert_eq!(empty_cell_offset("|  ", 13, 1), 15);
7459        // Nothing to stand in: just inside the pipe, never past the span.
7460        assert_eq!(empty_cell_offset("|", 10, 0), 11);
7461        assert_eq!(empty_cell_offset("", 10, 1), 10);
7462    }
7463
7464    #[test]
7465    fn a_hidden_marks_content_end_is_a_caret_home_but_not_a_glyph_stop() {
7466        // `a **bold** b`: the `d` is at 7, the content ends at 8, the closing
7467        // `**` draws nothing, and the space after it is at 10. Two homes at one
7468        // spot on screen: 8 (inside the bold) and 10 (past it).
7469        let m = map("a **bold** b\n");
7470        assert!(
7471            !m.stops.contains(&8),
7472            "8 has no glyph, so it is no glyph stop"
7473        );
7474        assert_eq!(m.mark_ends, vec![8]);
7475        assert!(m.is_stop(8), "but the caret may rest there");
7476        assert_eq!(m.snap_to_stop(8), 8, "and is left there when placed there");
7477        // Left/Right take both homes; the character-pairing walk takes one.
7478        assert_eq!(m.caret_stop_after(7), Some(8));
7479        assert_eq!(m.caret_stop_after(8), Some(10));
7480        assert_eq!(m.caret_stop_before(10), Some(8));
7481        assert_eq!(m.caret_stop_before(8), Some(7));
7482        assert_eq!(m.stop_after(7), Some(10));
7483        assert_eq!(m.stop_before(10), Some(7));
7484        // Drawn where the next glyph is: after the `d`, not on it.
7485        assert_eq!(m.pos_of_offset(8), m.pos_of_offset(10));
7486    }
7487
7488    #[test]
7489    fn every_hidden_inline_mark_gives_its_content_end_a_home() {
7490        // One end per mark, whatever it is spelled with; nested marks closing
7491        // together share the outer's end and the inner's alike.
7492        assert_eq!(
7493            map("*em* `code` [link](u) ~~del~~\n").mark_ends,
7494            vec![3, 10, 17, 27]
7495        );
7496        assert_eq!(map("***both***\n").mark_ends, vec![7]);
7497        // A mark that closes at its row's end coincides with the row's own end
7498        // stop — one offset, in both tables.
7499        let m = map("**bold**\n");
7500        assert_eq!(m.mark_ends, vec![6]);
7501        assert!(m.stops.contains(&6));
7502        // Revealed, the delimiter is glyphs of its own and the end is an
7503        // ordinary glyph stop: nothing to add.
7504        let mut ed = Editor::new_str("a **bold** b\n", Format::Markdown).unwrap();
7505        let src = "a **bold** b\n";
7506        let revealed = build(
7507            &ed.nodes().unwrap(),
7508            src,
7509            Some(80),
7510            false,
7511            &HashMap::new(),
7512            Some(0..src.len()),
7513        );
7514        assert!(revealed.mark_ends.is_empty());
7515        assert!(revealed.stops.contains(&8));
7516    }
7517
7518    #[test]
7519    fn a_marks_content_end_is_a_home_inside_a_table_cell() {
7520        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
7521        let m = map(src);
7522        let end = src.find("bold").unwrap() + 4; // 32, before the closing `**`
7523        assert_eq!(m.mark_ends, vec![end]);
7524        assert_eq!(m.snap_to_stop(end), end);
7525        // Drawn after the `d`, in this cell — where the cell's own end stop is.
7526        assert_eq!(m.pos_of_offset(end), m.pos_of_offset(end + 2));
7527    }
7528
7529    #[test]
7530    fn a_block_media_gives_the_caret_a_home_before_and_after_it() {
7531        // `![x](y)` on its own line: the caret can rest in front of the image
7532        // (its start) and just past it (the row end), and nowhere inside the
7533        // markup — the same coarse mapping a thematic break uses.
7534        let src = "![x](y.png)\n";
7535        let m = map(src);
7536        let img = &m.rows[m.media[0].rows_span.start];
7537        let start = 0; // the image opens the document
7538        let end = "![x](y.png)".len();
7539        // Every placeholder glyph maps to the image start and is a stop there.
7540        assert!(img.glyphs.iter().all(|g| g.src == start && g.stop));
7541        assert_eq!(img.end_src, end, "the row ends past the image");
7542        assert_eq!(m.stops.first(), Some(&start));
7543        assert!(m.stops.contains(&end), "a stop sits after the image");
7544        // Nothing inside the markup is a stop.
7545        assert!(!m.stops.iter().any(|&s| s > start && s < end));
7546    }
7547
7548    #[test]
7549    fn an_inline_image_amid_text_is_not_a_block_media() {
7550        // An image sharing its line with prose isn't block-level: it stays in the
7551        // inline path (rendered as its alt text), and publishes no MediaInfo.
7552        let m = map("see ![a cat](cat.png) here\n");
7553        assert!(m.media.is_empty(), "not a block image");
7554        assert!(
7555            rendered(&m).contains("a cat"),
7556            "alt text still renders inline"
7557        );
7558    }
7559
7560    /// The block images `Doc` publishes for `src`, driven through the real
7561    /// production build (`build_visual` → `build_cached`) with `html_elements`
7562    /// on — the path a `<picture>` actually travels. Not the raw `build` the
7563    /// other tests use: the editor's flat whole-arena snapshot tangles the links
7564    /// of inline-promoted HTML (phantom roots, dangling `parent`s), which only
7565    /// the per-block subtree walk `build_cached` does untangles.
7566    fn doc_media(src: &str) -> Vec<MediaInfo> {
7567        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
7568        doc.build_visual(80);
7569        doc.vmap.media.clone()
7570    }
7571
7572    #[test]
7573    fn a_video_block_is_media_with_its_src_poster_and_kind() {
7574        // The load-bearing assumption of video support: twig has no `video` node
7575        // kind, so `html_elements` promotion must land a `<video>` as a generic
7576        // `element` whose tag name and attributes survive onto `FlatNode` — the
7577        // same treatment `<picture>` gets. If that ever stops holding, this is
7578        // the test that says so.
7579        let m = doc_media("<video src=\"clip.mp4\" poster=\"still.png\" controls>\n</video>\n");
7580        assert_eq!(m.len(), 1, "the video is one block media");
7581        assert_eq!(m[0].kind, MediaKind::Video);
7582        assert_eq!(m[0].destination, "clip.mp4");
7583        assert_eq!(m[0].poster, "still.png");
7584    }
7585
7586    #[test]
7587    fn a_single_line_video_is_a_block_too() {
7588        // The spelling everyone actually writes. It used to parse as a paragraph
7589        // of raw inline HTML — CommonMark opens a block on a complete tag only
7590        // when the line ends there, and its fixed tag list predates `<video>` —
7591        // so the tags never reached core as an element at all. twig 2.5.1 widened
7592        // that list under `html_elements`; this is the test that would catch the
7593        // pin sliding back.
7594        let m = doc_media("<video src=\"clip.mp4\" controls></video>\n");
7595        assert_eq!(m.len(), 1, "single-line <video> is a block");
7596        assert_eq!(m[0].kind, MediaKind::Video);
7597        assert_eq!(m[0].destination, "clip.mp4");
7598    }
7599
7600    #[test]
7601    fn a_single_line_picture_is_a_block_with_its_alternatives() {
7602        // `<picture>` had the identical gap and it went unnoticed because the
7603        // conventional spelling breaks the lines. Same twig fix covers it.
7604        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\
7605                   <img src=\"l.svg\" alt=\"banner\"></picture>\n";
7606        let m = doc_media(src);
7607        assert_eq!(m.len(), 1);
7608        assert_eq!(m[0].kind, MediaKind::Image);
7609        assert_eq!(m[0].destination, "l.svg");
7610        assert_eq!(m[0].resolve(ColorScheme::Dark), "d.svg");
7611    }
7612
7613    #[test]
7614    fn an_audio_block_is_media_with_no_poster() {
7615        let m = doc_media("<audio src=\"take.mp3\" controls>\n</audio>\n");
7616        assert_eq!(m.len(), 1);
7617        assert_eq!(m[0].kind, MediaKind::Audio);
7618        assert_eq!(m[0].destination, "take.mp3");
7619        assert!(m[0].poster.is_empty(), "audio has no poster frame");
7620    }
7621
7622    #[test]
7623    fn a_videos_source_children_are_its_candidates_typed_by_mime() {
7624        // A `<video>` with no `src` of its own — the common shape, since it's how
7625        // you offer more than one codec. The candidates come from `<source src>`
7626        // (not `srcset`, which is `<picture>`'s spelling) and carry their MIME.
7627        let src = "<video controls>\n\
7628                   <source src=\"a.webm\" type=\"video/webm\">\n\
7629                   <source src=\"a.mp4\" type=\"video/mp4\">\n\
7630                   fallback\n\
7631                   </video>\n";
7632        let m = doc_media(src);
7633        assert_eq!(m.len(), 1);
7634        assert!(
7635            m[0].destination.is_empty(),
7636            "no src attribute on the element"
7637        );
7638        assert_eq!(m[0].sources.len(), 2);
7639        assert_eq!(m[0].sources[0].srcset, "a.webm");
7640        assert_eq!(m[0].sources[0].mime, "video/webm");
7641        assert_eq!(m[0].sources[1].srcset, "a.mp4");
7642        // With an empty destination, `resolve` falls through to the first
7643        // candidate rather than handing the frontend nothing to load.
7644        assert_eq!(m[0].resolve(ColorScheme::Light), "a.webm");
7645    }
7646
7647    #[test]
7648    fn a_video_placeholder_row_carries_its_own_sigil_and_mark() {
7649        // The placeholder contract images already hold, now for a video: the row
7650        // renders as a labelled stand-in a plain surface can paint as-is, and
7651        // carries the mark a capable frontend replaces it from.
7652        let src = "<video src=\"clip.mp4\" controls>\n</video>\n";
7653        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
7654        doc.build_visual(80);
7655        let row = &doc.vmap.rows[doc.vmap.media[0].rows_span.start];
7656        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
7657        assert!(
7658            text.starts_with('🎬'),
7659            "video sigil, not the image one: {text:?}"
7660        );
7661        assert!(row.media.is_some(), "the mark rides the placeholder row");
7662    }
7663
7664    #[test]
7665    fn a_picture_block_carries_its_source_alternatives() {
7666        // A `<picture>` with a dark-mode `<source>`: one block image, whose
7667        // fallback destination is the `<img>` and whose `sources` carry the
7668        // `<source>`'s media + srcset for a theme-aware frontend to pick.
7669        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"banner\"></picture>\n";
7670        let images = doc_media(src);
7671        assert_eq!(images.len(), 1, "the picture is one block image");
7672        let img = &images[0];
7673        assert_eq!(img.destination, "light.svg", "fallback is the <img>");
7674        assert_eq!(img.alt, "banner");
7675        assert_eq!(
7676            img.sources,
7677            vec![MediaSource {
7678                media: "(prefers-color-scheme: dark)".into(),
7679                srcset: "dark.svg".into(),
7680                mime: String::new(),
7681            }],
7682        );
7683    }
7684
7685    #[test]
7686    fn a_picture_inside_a_heading_is_still_a_block_media_with_sources() {
7687        // fig.md's shape: the banner is an `<h1>` wrapping the `<picture>`.
7688        let src = "<h1><picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\"><img src=\"l.svg\" alt=\"fig\"></picture></h1>\n";
7689        let images = doc_media(src);
7690        assert_eq!(images.len(), 1, "heading-wrapped picture is a block image");
7691        assert_eq!(images[0].destination, "l.svg");
7692        assert_eq!(images[0].sources.len(), 1);
7693        assert_eq!(images[0].sources[0].srcset, "d.svg");
7694    }
7695
7696    #[test]
7697    fn a_plain_image_has_no_media_sources() {
7698        // A bare Markdown image carries an empty `sources` — nothing to pick from.
7699        let images = doc_media("![alt](p.png)\n");
7700        assert_eq!(images.len(), 1);
7701        assert!(
7702            images[0].sources.is_empty(),
7703            "no <picture>, no alternatives"
7704        );
7705    }
7706
7707    #[test]
7708    fn resolve_picks_the_source_matching_the_scheme() {
7709        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"b\"></picture>\n";
7710        let images = doc_media(src);
7711        let img = &images[0];
7712        // Dark theme takes the dark source; light falls through to the <img>.
7713        assert_eq!(img.resolve(ColorScheme::Dark), "dark.svg");
7714        assert_eq!(img.resolve(ColorScheme::Light), "light.svg");
7715    }
7716
7717    #[test]
7718    fn resolve_falls_back_for_a_plain_image_and_unknown_media() {
7719        // A plain image ignores the scheme.
7720        let plain = doc_media("![a](p.png)\n");
7721        assert_eq!(plain[0].resolve(ColorScheme::Dark), "p.png");
7722
7723        // A <source> with an unrecognized media query is skipped; a light source
7724        // is taken under a light theme.
7725        let m = doc_media(
7726            "<picture><source media=\"print\" srcset=\"p.svg\"><source media=\"(prefers-color-scheme: light)\" srcset=\"l.svg\"><img src=\"f.svg\" alt=\"x\"></picture>\n",
7727        );
7728        assert_eq!(m[0].resolve(ColorScheme::Light), "l.svg");
7729        assert_eq!(
7730            m[0].resolve(ColorScheme::Dark),
7731            "f.svg",
7732            "no dark source → <img>"
7733        );
7734    }
7735
7736    #[test]
7737    fn resolve_reads_the_first_srcset_url_ignoring_descriptors() {
7738        // A comma/descriptor srcset resolves to its first URL.
7739        assert_eq!(first_srcset_url("a.png 1x, b.png 2x"), Some("a.png"));
7740        assert_eq!(first_srcset_url("  solo.svg  "), Some("solo.svg"));
7741        assert_eq!(first_srcset_url(""), None);
7742        // An empty (unconditional) media always matches.
7743        assert!(media_matches("", ColorScheme::Light));
7744        assert!(media_matches(
7745            "(prefers-color-scheme:dark)",
7746            ColorScheme::Dark
7747        ));
7748        assert!(!media_matches(
7749            "(prefers-color-scheme: dark)",
7750            ColorScheme::Light
7751        ));
7752    }
7753
7754    #[test]
7755    fn a_block_media_carries_its_list_prefix() {
7756        // An image that is a list item's body opens past the bullet, like every
7757        // other block does.
7758        let m = map("- ![alt](p.png)\n");
7759        let row = &m.rows[m.media[0].rows_span.start];
7760        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
7761        assert!(
7762            text.starts_with("• "),
7763            "the list marker prefixes the image row: {text:?}"
7764        );
7765        assert!(text.contains("🖼 alt"));
7766    }
7767
7768    #[test]
7769    fn the_structural_table_spans_exactly_its_drawn_rows() {
7770        // A frontend drawing its own grid skips `rows_span` and renders from
7771        // `grid`. If the span were short the leftover border rows would be
7772        // painted as text under the real table; if long it would eat a
7773        // neighbouring paragraph. Both are silent, so pin it to the picture.
7774        let m = map(&format!("before\n\n{TABLE}\nafter\n"));
7775        let t = &m.tables[0];
7776        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
7777        assert!(
7778            row_text(t.rows_span.start).starts_with('┌'),
7779            "opens on the top border"
7780        );
7781        assert!(
7782            row_text(t.rows_span.end - 1).starts_with('└'),
7783            "closes on the bottom border"
7784        );
7785        assert!(
7786            !row_text(t.rows_span.start - 1).contains('┌'),
7787            "the row before the span is not the table's"
7788        );
7789        assert_eq!(
7790            row_text(t.rows_span.end),
7791            "",
7792            "the span ends before the gap row"
7793        );
7794    }
7795
7796    #[test]
7797    fn a_nested_tables_structure_carries_the_block_prefix() {
7798        // The picture puts the quote's gutter on every row of the grid. A
7799        // frontend drawing its own table has to draw that too and start past it,
7800        // so the prefix has to travel with the structure — without it a quoted
7801        // table renders flush at the margin and leaves the quote it's in.
7802        let m = map("> | a | b |\n> |---|---|\n> | c | d |\n");
7803        let t = &m.tables[0];
7804        let prefix: String = t.prefix.iter().map(|g| g.ch).collect();
7805        assert_eq!(prefix, "│ ", "the quote's gutter should ride the structure");
7806        // And it matches what the picture actually drew.
7807        let drawn: String = m.rows[t.rows_span.start]
7808            .glyphs
7809            .iter()
7810            .map(|g| g.ch)
7811            .collect();
7812        assert!(
7813            drawn.starts_with(&prefix),
7814            "picture and structure disagree: {drawn:?}"
7815        );
7816    }
7817
7818    #[test]
7819    fn a_top_level_table_carries_no_prefix() {
7820        assert!(map(TABLE).tables[0].prefix.is_empty());
7821    }
7822
7823    #[test]
7824    fn structural_cells_are_unwrapped_even_when_the_picture_wraps_them() {
7825        // The picture wraps a cell to its column; a frontend laying the grid out
7826        // in pixels needs the text as the document spells it, before that
7827        // decision. Narrow enough that the drawn cell must break.
7828        let src = "| Name |\n|------|\n| alpha beta gamma |\n";
7829        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7830        let m = build_t(&ed.nodes().unwrap(), src, Some(12));
7831        let drawn = rendered(&m);
7832        let cell: String = m.tables[0].grid[1].cells[0]
7833            .glyphs
7834            .iter()
7835            .map(|g| g.ch)
7836            .collect();
7837        assert_eq!(
7838            cell, "alpha beta gamma",
7839            "structure must not carry the wrap"
7840        );
7841        assert!(
7842            drawn.lines().count() > 5,
7843            "the picture should have wrapped, else this proves nothing:\n{drawn}"
7844        );
7845    }
7846
7847    // ── display columns ──────────────────────────────────────────────────────
7848
7849    #[test]
7850    fn a_table_column_is_as_wide_as_its_cells_are_drawn() {
7851        // A column sized by counting characters is drawn narrower than the text
7852        // it has to hold — `你好` is two characters in four cells — and the cell
7853        // spills over the border it is supposed to sit inside, taking the whole
7854        // grid out of square with it. Squareness is the property: every row of a
7855        // grid is drawn to the same column, whatever its cells are spelled with.
7856        for src in [
7857            "| A | B |\n|---|---|\n| 你好 | y |\n",
7858            "| A | B |\n|---|---|\n| a👨‍👩‍👧b | y |\n",
7859            "| A | 漢字 |\n|---|---|\n| x | y |\n",
7860        ] {
7861            let m = map(src);
7862            let widths: Vec<usize> = m.rows.iter().map(|r| r.width()).collect();
7863            assert!(
7864                widths.windows(2).all(|w| w[0] == w[1]),
7865                "ragged grid {widths:?} for {src:?}:\n{}",
7866                rendered(&m)
7867            );
7868        }
7869    }
7870
7871    #[test]
7872    fn a_cell_wrapped_narrow_never_breaks_inside_a_character() {
7873        // A column too narrow for its cell hard-breaks the text, and every line
7874        // of it is given an end stop just past its last glyph. Broken into runs
7875        // of four glyphs, the first line of this cell ends between `👨‍👩` and the
7876        // joiner holding `👧` on — so its end stop lands inside a character,
7877        // where a click or Down can reach it and the next Backspace takes the
7878        // cluster apart from the middle.
7879        let src = "| A |\n|---|\n| 👨‍👩‍👧👨‍👩‍👧 |\n";
7880        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7881        let m = build_t(&ed.nodes().unwrap(), src, Some(8));
7882        let boundaries: Vec<usize> = src
7883            .grapheme_indices(true)
7884            .map(|(i, _)| i)
7885            .chain(std::iter::once(src.len()))
7886            .collect();
7887        for off in (0..=src.len()).filter(|&o| m.is_stop(o)) {
7888            assert!(
7889                boundaries.contains(&off),
7890                "stop at {off} is inside a character:\n{}",
7891                rendered(&m)
7892            );
7893        }
7894    }
7895
7896    #[test]
7897    fn a_wrapped_cell_keeps_every_line_inside_its_column() {
7898        // The width is a promise in a table, where a glyph past the column lands
7899        // on the border or in the next cell — and it is a promise about cells,
7900        // which is not what a count of glyphs measures.
7901        let src = "| A |\n|---|\n| 你好世界漢字 |\n";
7902        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7903        let m = build_t(&ed.nodes().unwrap(), src, Some(14));
7904        for r in &m.rows {
7905            assert_eq!(r.width(), 14, "{:?} is not drawn to the grid", rendered(&m));
7906        }
7907    }
7908
7909    #[test]
7910    fn a_hard_break_falls_between_clusters_and_measures_in_cells() {
7911        let glyphs = |s: &str| {
7912            let mut out = Vec::new();
7913            push_text(&mut out, s, 0, Style::default());
7914            out
7915        };
7916        let piece = |p: &[Glyph]| p.iter().map(|g| g.ch).collect::<String>();
7917
7918        // Six cells of CJK broken at four: two characters, then one — never
7919        // between the two cells of `好`.
7920        let w = glyphs("你好世");
7921        let pieces: Vec<String> = hard_break(&w, 4).iter().map(|p| piece(p)).collect();
7922        assert_eq!(pieces, ["你好", "世"]);
7923
7924        // A character wider than the column has nowhere legal to break, so it
7925        // keeps its cells rather than being cut in half.
7926        let w = glyphs("你好");
7927        let pieces: Vec<String> = hard_break(&w, 1).iter().map(|p| piece(p)).collect();
7928        assert_eq!(pieces, ["你", "好"]);
7929
7930        // An empty word yields no pieces at all — a double space stays a space.
7931        assert!(hard_break(&[], 4).is_empty());
7932    }
7933
7934    #[test]
7935    fn an_empty_list_item_still_gets_a_bulleted_row_with_a_caret_home() {
7936        // Pressing Enter at the end of a list item opens a new, empty item —
7937        // a childless `list_item`. Without a row of its own the new bullet
7938        // wouldn't appear until something was typed into it (the caret would be
7939        // stranded on an offset no row draws). It now renders as one prefixed
7940        // row whose end is a caret stop, so the bullet shows and the caret lands
7941        // just past the marker.
7942        let m = map("- item\n- \n");
7943        assert_eq!(m.num_rows(), 2, "the empty second item needs its own row");
7944        assert_eq!(
7945            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
7946            "• ",
7947            "the empty item draws just its bullet",
7948        );
7949        // Its end is the caret home (past the `- ` marker), and it's a real stop.
7950        assert!(
7951            m.is_stop(m.rows[1].end_src),
7952            "the empty item's caret home is not a stop"
7953        );
7954        assert_eq!(
7955            m.pos_of_offset(m.rows[1].end_src),
7956            (1, 2),
7957            "caret sits after '• '"
7958        );
7959    }
7960
7961    #[test]
7962    fn a_notes_row_range_stops_at_the_note_even_when_it_ends_in_a_link() {
7963        // The peek bug: a note whose body ends in a link has its last byte
7964        // inside the hidden destination, so mapping `end - 1` through
7965        // `pos_of_offset` snapped *forward* — past its own row, past the drawn
7966        // gap, and onto the next note's row. The popover then drew both notes.
7967        let src = "A[^1] B[^2].\n\n[^1]: bare text\n\n[^2]: [title](https://example.com/x)\n\n[^3]: last\n";
7968        let m = map(src);
7969        let body = src.find("[title]").unwrap();
7970        let end = src.find("\n\n[^3]").unwrap();
7971
7972        let (first, last) = m.row_range_for(body..end);
7973        assert_eq!(
7974            first, last,
7975            "a one-block note is one row, not a span onto the next"
7976        );
7977
7978        // The old arithmetic, kept here as the thing that must stay wrong: it
7979        // is what this method exists instead of.
7980        assert_ne!(
7981            m.pos_of_offset(end - 1).0,
7982            last,
7983            "the forward snap still leaves the note's row — that is the whole point",
7984        );
7985
7986        // A note ending in *visible* text was never broken, and still isn't:
7987        // both readings agree there, which is why the original test missed it.
7988        let plain = src.find("bare text").unwrap();
7989        let plain_end = src.find("\n\n[^2]").unwrap();
7990        let (pf, pl) = m.row_range_for(plain..plain_end);
7991        assert_eq!(pf, pl);
7992        assert_eq!(m.pos_of_offset(plain_end - 1).0, pl);
7993    }
7994
7995    #[test]
7996    fn a_row_range_covers_every_row_of_a_block_that_spans_several() {
7997        // The range is a span, not a point: a quote of two paragraphs covers its
7998        // gap row and both of its text rows, so a peek draws the whole thing.
7999        let src = "> one\n>\n> two\n\nafter\n";
8000        let m = map(src);
8001        let (first, last) = m.row_range_for(0..src.find("\n\nafter").unwrap());
8002        assert_eq!((first, last), (0, 2));
8003
8004        // And a range with no visible byte at all still covers the row it opened
8005        // on, rather than collapsing to nothing.
8006        let (f, l) = m.row_range_for(0..1);
8007        assert_eq!((f, l), (0, 0));
8008    }
8009
8010    #[test]
8011    fn an_empty_block_quote_still_gets_a_gutter_row_with_a_caret_home() {
8012        // The peer of the empty list item, and the case that made an empty line
8013        // in a quote draw as plain body text: a childless `block_quote` — a bare
8014        // `> `, which is what the toolbar's Quote button leaves on a blank line —
8015        // has no inner block to carry the gutter, so the whole quote used to
8016        // render as *nothing*. It didn't merely lose its bar; the row went away
8017        // and the caret had no home on it.
8018        let m = map("a\n\n> \n\nb\n");
8019        assert_eq!(
8020            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
8021            "│ ",
8022            "the empty quote draws just its gutter",
8023        );
8024        assert!(
8025            m.rows[2]
8026                .glyphs
8027                .iter()
8028                .all(|g| g.style.role == Role::QuoteGutter)
8029        );
8030        assert!(
8031            !m.rows[2].decoration,
8032            "it is a line text can go on, not a drawn gap"
8033        );
8034        assert!(
8035            m.is_stop(m.rows[2].end_src),
8036            "the empty quote's caret home is not a stop"
8037        );
8038        assert_eq!(
8039            m.pos_of_offset(m.rows[2].end_src),
8040            (2, 2),
8041            "caret sits after '│ '"
8042        );
8043
8044        // And a document that is *only* an empty quote still renders a row — it
8045        // used to render none at all, leaving the caret nowhere to stand.
8046        let m = map("> \n");
8047        assert_eq!(m.num_rows(), 1);
8048        assert_eq!(
8049            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
8050            "│ "
8051        );
8052    }
8053
8054    #[test]
8055    fn a_quotes_own_trailing_marker_lines_stay_inside_the_quote() {
8056        // Enter at the end of `> a` writes `> a\n>\n> \n`. Those last two lines
8057        // hold no block — a quote's `content_span` stops at its last child — so
8058        // the children walk never reaches them, and they used to fall through to
8059        // the document-level trailing pass, which knows no prefix: the gutter
8060        // stopped and the writer's new line drew as plain prose. Fixable only
8061        // since twig 3.2.0, where the quote's *span* covers its own marker lines
8062        // (`0..3` before, `0..8` now) and there is finally a node saying they
8063        // are the quote's.
8064        let m = map("> a\n>\n> \n");
8065        assert_eq!(m.num_rows(), 3, "one row per line the quote spells");
8066        for (i, row) in m.rows.iter().enumerate() {
8067            let text = row.glyphs.iter().map(|g| g.ch).collect::<String>();
8068            assert!(text.starts_with("│ "), "row {i} lost the gutter: {text:?}");
8069            assert!(
8070                !row.decoration,
8071                "row {i} is a line to type on, not a drawn gap"
8072            );
8073            assert!(m.is_stop(row.end_src), "row {i} has no caret home");
8074        }
8075        assert_eq!(
8076            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
8077            "│ a"
8078        );
8079        // Distinct offsets, so ↑/↓ between them moves the caret rather than
8080        // landing twice on the same byte.
8081        assert!(m.rows[0].end_src < m.rows[1].end_src);
8082        assert!(m.rows[1].end_src < m.rows[2].end_src);
8083
8084        // A blank line *after* the quote is not the quote's: it is spelled with
8085        // no marker, so it stays an ordinary boundary and the gutter ends.
8086        let m = map("> a\n\nb\n");
8087        assert_eq!(m.num_rows(), 3);
8088        assert_eq!(
8089            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
8090            "b"
8091        );
8092        assert!(
8093            !m.rows[1]
8094                .glyphs
8095                .iter()
8096                .any(|g| g.style.role == Role::QuoteGutter)
8097        );
8098
8099        // Nesting is the case this could get wrong, and the depth has to come
8100        // from which quote's span the line falls in rather than from the row
8101        // above it. A trailing `>` under `> > a` matches only the OUTER quote,
8102        // so it wears one gutter; spell it `> >` and it wears two.
8103        let m = map("> > a\n>\n");
8104        assert_eq!(
8105            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
8106            "│ │ a"
8107        );
8108        assert_eq!(
8109            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8110            "│ "
8111        );
8112        let m = map("> > a\n> >\n");
8113        assert_eq!(
8114            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8115            "│ │ "
8116        );
8117
8118        // And a marker line BETWEEN two quoted paragraphs is untouched: that is
8119        // the boundary `emit_separators_before` spells, and it stays a drawn gap
8120        // rather than becoming a line to type on.
8121        let m = map("> a\n>\n> b\n");
8122        assert_eq!(m.num_rows(), 3);
8123        assert!(
8124            m.rows[1].decoration,
8125            "the gap between two quoted blocks is still a gap"
8126        );
8127    }
8128
8129    #[test]
8130    fn an_empty_ordered_item_gets_its_number_and_a_caret_home() {
8131        let m = map("1. item\n2. \n");
8132        assert_eq!(m.num_rows(), 2);
8133        assert_eq!(
8134            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
8135            "2. "
8136        );
8137        assert!(m.is_stop(m.rows[1].end_src));
8138        assert_eq!(
8139            m.pos_of_offset(m.rows[1].end_src),
8140            (1, 3),
8141            "caret sits after '2. '"
8142        );
8143    }
8144
8145    #[test]
8146    fn an_empty_headings_caret_home_is_past_its_hidden_marker() {
8147        // The toolbar's H1 on a blank line writes `# ` and nothing else. The row
8148        // it renders is empty (the marker is hidden), so its end *is* its only
8149        // caret stop — and it has to be the offset past the `# `, where typing
8150        // continues the heading. Anchored at the block's start instead, the caret
8151        // drew in front of the hashes and the first character typed there landed
8152        // before them (`x# `), which isn't a heading at all.
8153        let m = map("# \n");
8154        assert_eq!(m.num_rows(), 1);
8155        assert!(m.rows[0].glyphs.is_empty(), "the `# ` marker is hidden");
8156        assert_eq!(m.rows[0].end_src, 2, "the caret home is past the marker");
8157        assert!(m.is_stop(2), "the empty heading's caret home is not a stop");
8158    }
8159
8160    #[test]
8161    fn a_headings_rows_carry_its_level_even_with_nothing_typed_in_it() {
8162        // The row-level fact a proportional frontend sizes a whole line by. An
8163        // empty heading has no glyph to read a `Role::Heading` off, so a renderer
8164        // scanning glyphs drew `# ` (and its caret) at body height until the
8165        // first character landed.
8166        let m = map("# \n");
8167        assert_eq!(
8168            m.rows[0].heading,
8169            Some(1),
8170            "the empty heading knows its level"
8171        );
8172
8173        // Every row of one that wraps, not just the first — and nothing else.
8174        let m = map_at(
8175            "## a heading long enough to wrap over two rows\n\nbody\n",
8176            Some(20),
8177        );
8178        let heads: Vec<Option<u8>> = m.rows.iter().map(|r| r.heading).collect();
8179        assert!(
8180            heads.iter().filter(|h| **h == Some(2)).count() >= 2,
8181            "got {heads:?}"
8182        );
8183        assert_eq!(
8184            m.rows.last().and_then(|r| r.heading),
8185            None,
8186            "the paragraph under it is not a heading",
8187        );
8188    }
8189
8190    #[test]
8191    fn an_empty_heading_leaves_the_rows_under_it_at_their_own_offsets() {
8192        // The row's end is also what the *next* row's separator is measured from,
8193        // so an empty heading that under-reported it shifted every offset below —
8194        // and the blank line under the heading then claimed the same offset as the
8195        // heading's own end. `pos_of_offset` resolves such a tie downstream (a
8196        // soft wrap belongs to the row below), so the caret at the end of the
8197        // heading was drawn two rows lower, on the blank line.
8198        // `text\n\n# \n\n`: the heading's content opens at 8, and the two rows
8199        // under it end at 9 and 10 — the blank line and the document's end.
8200        let m = map("text\n\n# \n\n");
8201        let end = m.rows.last().expect("a trailing blank row").end_src;
8202        assert_eq!(end, 10, "the trailing rows must end at their real offsets");
8203        // The heading's caret home is its own row's, not one shared with a row
8204        // below — the tie that drew the caret two rows down.
8205        assert_eq!(m.pos_of_offset(8), (2, 0), "the empty heading's own row");
8206        assert!(
8207            m.rows[3..].iter().all(|r| r.end_src > 8),
8208            "rows below own later offsets"
8209        );
8210    }
8211
8212    // ── block boundaries ─────────────────────────────────────────────────────
8213
8214    /// Every drawn boundary in `src`, in order, as `(above, below)`.
8215    fn boundaries(m: &VisualMap) -> Vec<(BlockClass, BlockClass)> {
8216        m.rows
8217            .iter()
8218            .filter_map(|r| r.boundary)
8219            .map(|b| (b.above, b.below))
8220            .collect()
8221    }
8222
8223    #[test]
8224    fn a_boundary_says_which_blocks_it_divides() {
8225        use BlockClass::*;
8226        let m = map("one\n\ntwo\n\n# Head\n\ntail\n\n> quoted\n\n```\ncode\n```\n");
8227        assert_eq!(
8228            boundaries(&m),
8229            vec![
8230                (Paragraph, Paragraph),
8231                (Paragraph, Heading),
8232                (Heading, Paragraph),
8233                (Paragraph, Quote),
8234                (Quote, Code),
8235                // The blank the document trails off with is a boundary too — it
8236                // closes the last block above the empty paragraph the caret rests
8237                // on. See `emit_trailing_blank_lines`.
8238                (Code, Paragraph),
8239            ],
8240            "each gap names the pair it falls between, in document order"
8241        );
8242    }
8243
8244    // ── hidden blocks ────────────────────────────────────────────────────────
8245
8246    /// The row texts of `m`, one string per row.
8247    fn row_texts(m: &VisualMap) -> Vec<String> {
8248        m.rows
8249            .iter()
8250            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
8251            .collect()
8252    }
8253
8254    #[test]
8255    fn a_comment_between_two_blocks_is_stepped_over_not_drawn_as_a_gap() {
8256        // `<!-- exec -->` is a top-level block that draws no rows. The blocks
8257        // either side of it meet across the one boundary a paragraph and a code
8258        // block always meet across — not that boundary *plus* one blank row per
8259        // line of the comment, which is what counting the separator from the
8260        // paragraph's end used to spell.
8261        let m = map("para one\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n");
8262        assert_eq!(row_texts(&m), ["para one", "", "code", "", "after"]);
8263        assert_eq!(
8264            boundaries(&m),
8265            vec![
8266                (BlockClass::Paragraph, BlockClass::Code),
8267                (BlockClass::Code, BlockClass::Paragraph),
8268            ],
8269            "the boundary names the drawn blocks either side, not the comment"
8270        );
8271        // The gap stands past the comment, so the caret's row lookup never
8272        // resolves inside it.
8273        assert_eq!(
8274            m.rows[1].end_src, 23,
8275            "the gap row ends at the comment's end"
8276        );
8277    }
8278
8279    #[test]
8280    fn a_comment_opening_the_document_draws_no_leading_gap() {
8281        let m = map("<!-- lead -->\n\npara\n");
8282        assert_eq!(row_texts(&m), ["para"]);
8283        assert_eq!(m.content_start, 0, "the comment is still the first block");
8284    }
8285
8286    #[test]
8287    fn a_comment_closing_the_document_is_not_trailing_blank_lines() {
8288        // Its lines are not blank lines the author opened with Enter, so no
8289        // gap-plus-empty-paragraph is fabricated under the last drawn block.
8290        let m = map("para\n\n<!-- trail -->\n");
8291        assert_eq!(row_texts(&m), ["para"]);
8292        // Enter at the end of the document still opens the empty paragraph the
8293        // caret rests on: the newlines *after* the comment count as they would
8294        // after any block.
8295        let m = map("para\n\n<!-- trail -->\n\n");
8296        assert_eq!(row_texts(&m), ["para", "", ""]);
8297    }
8298
8299    #[test]
8300    fn a_comment_in_a_list_item_leaves_the_bullet_to_what_follows_it() {
8301        // The first *drawn* child wears the item's marker; a hidden first child
8302        // would otherwise take it and leave the text without one.
8303        let m = map("- <!-- note -->\n\n  text\n- two\n");
8304        let texts = row_texts(&m);
8305        assert!(
8306            texts.iter().any(|t| t == "• text"),
8307            "the text wears the bullet: {texts:?}"
8308        );
8309        assert!(
8310            !texts.iter().any(|t| t == "• "),
8311            "no empty bullet row for the comment: {texts:?}"
8312        );
8313    }
8314
8315    #[test]
8316    fn the_cached_build_does_not_spell_the_document_out_as_blank_rows_after_a_comment() {
8317        // The bug as seen: a 200-line document with one comment in it rendered
8318        // ~200 blank rows after the comment, one per source line, because the
8319        // comment's per-block builder handed back a `last_off` of 0. Parity with
8320        // `build` alone would not catch a *shared* wrong answer, so the count is
8321        // pinned outright.
8322        let body = (0..200)
8323            .map(|i| format!("line {i}"))
8324            .collect::<Vec<_>>()
8325            .join("\n\n");
8326        let src = format!("intro\n\n<!-- exec -->\n{body}\n");
8327        let mut ed = Editor::new_str(&src, Format::Markdown).unwrap();
8328        let mut cache = BlockCache::default();
8329        let (plain, cached) = render_both(&mut ed, &src, Some(80), &mut cache);
8330        assert_maps_eq(&plain, &cached, "comment then 200 paragraphs");
8331        // intro, then 200 × (gap, paragraph): 401 rows and not a row more.
8332        assert_eq!(cached.rows.len(), 401);
8333    }
8334
8335    #[test]
8336    fn a_link_reference_definition_is_stepped_over_like_a_comment() {
8337        // `[a]: /a` is a root beside `doc` with no rows of its own. Merged into
8338        // the walk it is a hidden block: the blocks either side meet across one
8339        // boundary, and its line is not a blank row.
8340        let m = map("see [a]\n\n[a]: /a\n\nafter\n");
8341        assert_eq!(row_texts(&m), ["see a", "", "after"]);
8342        assert_eq!(
8343            boundaries(&m),
8344            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
8345        );
8346    }
8347
8348    #[test]
8349    fn link_reference_definitions_closing_the_document_are_not_trailing_blank_lines() {
8350        // The README shape: prose, then a `[links]` block nobody reads. Its
8351        // lines used to be counted as blank ones, an empty paragraph per
8352        // definition under the last real block.
8353        let m = map("see [a] and [b]\n\n<!-- links -->\n[a]: /a\n[b]: /b \"bee\"\n");
8354        assert_eq!(row_texts(&m), ["see a and b"]);
8355    }
8356
8357    #[test]
8358    fn a_definition_glued_under_a_paragraph_stays_inside_it() {
8359        // `[a]: /a` at the front of a paragraph's lines is stripped from the
8360        // paragraph's text, but the paragraph's span still starts on its line.
8361        // Both blocks start at the same offset; the definition, sorted first,
8362        // is stepped over, and the paragraph draws as it always did — one gap
8363        // above it, none inside.
8364        let m = map("intro\n\n[a]: /a\ntext [a]\n");
8365        assert_eq!(row_texts(&m), ["intro", "", "text a"]);
8366    }
8367
8368    #[test]
8369    fn a_definition_with_no_span_is_left_out_of_the_walk() {
8370        // twig before 3.3.3 reported `0..0` for every link reference
8371        // definition. One of those has nowhere to be merged: sorted first by
8372        // its zero start it would open the document with a phantom block, and
8373        // the walk would step back to offset 0. It is simply not a block. A
8374        // footnote definition is always placed; it has a body to draw.
8375        assert!(!is_placed_definition(&Kind::Reference, &(0..0)));
8376        assert!(is_placed_definition(&Kind::Reference, &(7..14)));
8377        assert!(is_placed_definition(&Kind::Footnote, &(0..0)));
8378        assert!(!is_placed_definition(&Kind::Str, &(7..14)));
8379    }
8380
8381    #[test]
8382    fn the_trailing_gap_closes_the_last_block() {
8383        // Two Enters at the end of a document: a drawn gap, then the navigable
8384        // empty paragraph. Only the gap is labelled, so a frontend that shrinks
8385        // boundaries shrinks the spacer and leaves the row being typed on alone.
8386        let m = map("# Head\n\n\n");
8387        assert_eq!(
8388            boundaries(&m),
8389            vec![(BlockClass::Heading, BlockClass::Paragraph)]
8390        );
8391    }
8392
8393    #[test]
8394    fn only_the_drawn_gap_rows_carry_a_boundary() {
8395        let m = map("one\n\ntwo\n");
8396        for row in &m.rows {
8397            assert_eq!(
8398                row.boundary.is_some(),
8399                row.decoration,
8400                "a boundary is exactly a drawn gap row: {:?}",
8401                row.glyphs.iter().map(|g| g.ch).collect::<String>()
8402            );
8403        }
8404    }
8405
8406    #[test]
8407    fn preserve_flow_labels_no_boundary() {
8408        // Every blank line is a caret home there — somewhere text can go, not a
8409        // gap between blocks — so nothing is drawn-only and nothing is labelled.
8410        // A frontend keying its spacing off `boundary` can't shrink a row the
8411        // author is about to type on.
8412        let m = map_preserve("one\n\ntwo\n\n# Head\n", Some(80));
8413        assert!(boundaries(&m).is_empty());
8414    }
8415
8416    #[test]
8417    fn a_list_draws_no_boundary_between_its_items() {
8418        // Tight or loose, core puts no gap row between two items of one list —
8419        // so an item↔item boundary is a shape no frontend will ever be handed,
8420        // and spacing one is spacing something that isn't there.
8421        for src in ["- one\n- two\n", "- one\n\n- two\n"] {
8422            let m = map(src);
8423            assert!(
8424                boundaries(&m).is_empty(),
8425                "no gap row inside the list of {src:?}"
8426            );
8427        }
8428        // Leaving the list is an ordinary boundary, and the list is named as
8429        // what sits above it.
8430        let m = map("- one\n- two\n\npara\n");
8431        assert_eq!(
8432            boundaries(&m),
8433            vec![(BlockClass::List, BlockClass::Paragraph)]
8434        );
8435    }
8436
8437    #[test]
8438    fn a_nested_boundary_names_the_blocks_inside_the_container() {
8439        // Two paragraphs inside a blockquote are divided by a Paragraph↔Paragraph
8440        // boundary — the quote is the container they're both in, not what the gap
8441        // separates.
8442        let m = map("> one\n>\n> two\n");
8443        assert_eq!(
8444            boundaries(&m),
8445            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
8446        );
8447    }
8448
8449    #[test]
8450    fn a_directive_container_draws_one_boundary_like_every_other_block() {
8451        // A container's rows stop at its last *child*, so without anchoring
8452        // `last_off` past the closing `:::` the separator logic counted the fence
8453        // line as a blank row of its own and drew the gap twice — one authored
8454        // blank line, two boundaries, and a frontend spacing each of them put
8455        // double margin under every fenced div. The code-block arm anchors past
8456        // its ``` for exactly this reason; compare the two here.
8457        let fenced = map_directives(":::note\nin\n:::\n\ntwo\n");
8458        assert_eq!(
8459            boundaries(&fenced),
8460            vec![(BlockClass::Directive, BlockClass::Paragraph)],
8461            "one authored gap, one boundary row"
8462        );
8463        let code = map("```\nc\n```\n\ntwo\n");
8464        assert_eq!(
8465            boundaries(&code).len(),
8466            boundaries(&fenced).len(),
8467            "a fenced div spaces like a fenced code block"
8468        );
8469        // Nesting closes several fences at once; still one gap.
8470        let nested = map_directives(":::a\n:::b\nin\n:::\n:::\n\ntwo\n");
8471        assert_eq!(
8472            boundaries(&nested),
8473            vec![(BlockClass::Directive, BlockClass::Paragraph)]
8474        );
8475    }
8476
8477    #[test]
8478    fn a_block_media_names_itself_in_the_boundaries_either_side() {
8479        use BlockClass::*;
8480        // A block image is never a node of its own — `media_only` promotes the
8481        // *paragraph* wrapping it — so classifying the node the walk stands on
8482        // called the picture `Paragraph` and left `BlockClass::Media` unreachable:
8483        // a frontend could not give a photo more air than a line of prose.
8484        // `label_media_boundaries` reads it back off the finished rows instead.
8485        let m = map("one\n\n![alt](p.png)\n\ntwo\n");
8486        assert_eq!(boundaries(&m), vec![(Paragraph, Media), (Media, Paragraph)]);
8487        // At the edges of the document too: the leading gap has no boundary of
8488        // its own, and the trailing one is `emit_trailing_blank_lines`'.
8489        let edges = map("![a](p.png)\n\nmid\n\n![b](q.png)\n");
8490        assert_eq!(
8491            boundaries(&edges),
8492            vec![(Media, Paragraph), (Paragraph, Media)]
8493        );
8494        // One gap spelled with several rows — the row closing the block above and
8495        // the row opening the one below, with the author's spare blank line
8496        // navigable between them — carries the same pair on every drawn row.
8497        let roomy = map("one\n\n\n\n![alt](p.png)\n");
8498        assert_eq!(
8499            boundaries(&roomy),
8500            vec![(Paragraph, Media), (Paragraph, Media)]
8501        );
8502    }
8503
8504    #[test]
8505    fn a_block_video_is_media_at_its_boundaries_not_a_directive_panel() {
8506        // Worse than the image case before `label_media_boundaries`: a `<video>`
8507        // arrives as twig's generic `container`, which classifies `Directive` —
8508        // the one class a frontend reads as "draw a tinted panel here". A movie
8509        // got the chrome of a fenced div.
8510        let mut doc = crate::Doc::from_source(
8511            "one\n\n<video src=\"v.mp4\"></video>\n\ntwo\n".to_string(),
8512            Format::Markdown,
8513        )
8514        .unwrap();
8515        doc.build_visual(80);
8516        assert_eq!(
8517            boundaries(&doc.vmap),
8518            vec![
8519                (BlockClass::Paragraph, BlockClass::Media),
8520                (BlockClass::Media, BlockClass::Paragraph),
8521            ]
8522        );
8523    }
8524
8525    #[test]
8526    fn the_incremental_walk_labels_boundaries_like_the_full_one() {
8527        // `assert_maps_eq` compares boundaries too, so this pins the two doors
8528        // into `BlockClass::from_node_kind` — a `FlatNode`'s kind on the full
8529        // build, a query match's on the cached one — against a document with one
8530        // of every boundary in it.
8531        let src = "one\n\n# Head\n\ntwo\n\n- a\n- b\n\n> q\n\n```\nc\n```\n\npara\n";
8532        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
8533        let mut cache = BlockCache::default();
8534        let (full, cached) = render_both(&mut ed, src, Some(80), &mut cache);
8535        assert_maps_eq(&full, &cached, "boundary labelling");
8536        assert!(
8537            !boundaries(&full).is_empty(),
8538            "the fixture has boundaries to compare"
8539        );
8540    }
8541
8542    #[test]
8543    fn every_caret_stop_opens_a_cluster_of_its_row() {
8544        // The two ways of finding a cluster have to agree. `push_text` marks the
8545        // stops by segmenting one run of text; the column mapping segments the
8546        // whole row, decoration and all. A stop that came out as the *middle* of
8547        // some row-level cluster would be a caret with no column of its own —
8548        // drawn at the column of whatever swallowed it.
8549        let src = "# 標題\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` 你好\n\n\
8550                   - 項目 one\n- e\u{0301}dge\n\n> 引用 text\n\n\
8551                   | A | 值 |\n|---|---|\n| 你好 | 👩‍🚀 |\n";
8552        let m = map(src);
8553        for (r, row) in m.rows.iter().enumerate() {
8554            let openers: Vec<usize> = clusters(&row.glyphs).iter().map(|c| c.glyph).collect();
8555            for (i, g) in row.glyphs.iter().enumerate() {
8556                assert!(
8557                    !g.stop || openers.contains(&i),
8558                    "row {r}: the stop at glyph {i} ({:?}) is inside a cluster, \
8559                     so it is drawn at another glyph's column",
8560                    g.ch
8561                );
8562            }
8563        }
8564    }
8565
8566    // ── the presentation vocabulary ─────────────────────────────────────────
8567
8568    /// A block's own attributes, in the three formats that spell one on the
8569    /// block itself: HTML's tag, djot's `{…}` line, and — the odd one — a
8570    /// Markdown `<div>` around it, which is where twig has to put a Markdown
8571    /// block's attributes because the format has nowhere else.
8572    #[test]
8573    fn a_block_carries_its_alignment_on_every_row_it_draws() {
8574        // HTML, on the paragraph. `lead` is somebody else's class and is
8575        // neither read nor in the way.
8576        let html = map_leaf("<p class=\"lead center\">hi</p>\n", Format::Html);
8577        assert_eq!(line_facts(&html), vec![(Some(Align::Center), None)]);
8578
8579        // djot's attribute line, on the block.
8580        let dj = map_leaf("{.right}\nhi\n", Format::Djot);
8581        assert_eq!(line_facts(&dj), vec![(Some(Align::Right), None)]);
8582
8583        // A heading carries it too, and on every row a wrapped one draws.
8584        let h = map_leaf("{.center}\n# a heading\n", Format::Djot);
8585        assert_eq!(line_facts(&h), vec![(Some(Align::Center), None)]);
8586        assert_eq!(h.rows[0].heading, Some(1));
8587
8588        // Both keys at once, and the line spacing is read the same way.
8589        let both = map_leaf("{.justify data-line-height=\"1.5\"}\nhi\n", Format::Djot);
8590        assert_eq!(
8591            line_facts(&both),
8592            vec![(Some(Align::Justify), Some(LineSpacing::OneHalf))]
8593        );
8594
8595        // An unknown token and an unknown ratio are somebody else's, and the
8596        // block draws at the theme's default rather than at a guess.
8597        let other = map_leaf("{.lead data-line-height=\"1.3\"}\nhi\n", Format::Djot);
8598        assert_eq!(line_facts(&other), vec![(None, None)]);
8599    }
8600
8601    /// `<div class="center">` around three paragraphs centres all three, which
8602    /// is what the author of that HTML meant — and around one is the sole-child
8603    /// shape twig's `set_block_attrs` writes in Markdown.
8604    #[test]
8605    fn a_div_lends_its_alignment_to_every_block_inside_it() {
8606        let m = map_leaf(
8607            "<div class=\"center\" data-line-height=\"2\">\n\none\n\ntwo\n\n</div>\n",
8608            Format::Markdown,
8609        );
8610        assert_eq!(
8611            line_facts(&m),
8612            vec![
8613                (Some(Align::Center), Some(LineSpacing::Double)),
8614                (Some(Align::Center), Some(LineSpacing::Double)),
8615            ]
8616        );
8617
8618        // The nearer node wins, and the block after the div is untouched — the
8619        // context is restored, not left running.
8620        let nested = map_leaf(
8621            "<div class=\"center\">\n\n<div class=\"right\">\n\ninner\n\n</div>\n\nouter\n\n</div>\n\nafter\n",
8622            Format::Markdown,
8623        );
8624        assert_eq!(
8625            line_facts(&nested),
8626            vec![
8627                (Some(Align::Right), None),
8628                (Some(Align::Center), None),
8629                (None, None),
8630            ]
8631        );
8632    }
8633
8634    /// Size, face and colour are the run's, and the block's when the whole
8635    /// block is meant — read at both levels with the nearer winning.
8636    #[test]
8637    fn a_span_s_size_beats_its_block_s_and_its_face_falls_through() {
8638        // `<div data-font>` over `<p data-size>` over `<span data-size>`: the
8639        // span wins on size, the block is still what says the face.
8640        // The span is not first on its line: a `<span …>` opening one is an
8641        // HTML *block* to CommonMark, which is a fact about Markdown and not
8642        // about this.
8643        let m = map_leaf(
8644            "<div data-font=\"serif\">\n\nc <span data-size=\"small\">a</span> b\n\n</div>\n",
8645            Format::Markdown,
8646        );
8647        let a = style_of(&m, 'a');
8648        assert_eq!(a.size, Some(SizeStep::Small));
8649        assert_eq!(a.font, Some(FontFamily::Serif));
8650        // The text outside the span keeps the div's face and no size at all.
8651        let b = style_of(&m, 'b');
8652        assert_eq!(b.size, None);
8653        assert_eq!(b.font, Some(FontFamily::Serif));
8654
8655        // djot spells the same span anonymously and it reads identically.
8656        let dj = map_leaf(
8657            "{data-size=\"large\"}\nx [y]{data-size=\"xx-large\" data-color=\"blue\"} z\n",
8658            Format::Djot,
8659        );
8660        assert_eq!(style_of(&dj, 'x').size, Some(SizeStep::Large));
8661        assert_eq!(style_of(&dj, 'y').size, Some(SizeStep::XxLarge));
8662        assert_eq!(style_of(&dj, 'y').color, Some(MarkColor::Blue));
8663        // The block's size is still the block's outside the span.
8664        assert_eq!(style_of(&dj, 'z').size, Some(SizeStep::Large));
8665        assert_eq!(style_of(&dj, 'z').color, None);
8666    }
8667
8668    /// The one key two nodes share. `data-color` on a `mark` is the highlight's
8669    /// *background* and reaches a glyph through [`Role::Mark`]; the same key on
8670    /// an attributed span is the text's foreground. Same vocabulary, same enum,
8671    /// no collision — and a mark inside a coloured span wears both.
8672    #[test]
8673    fn a_mark_keeps_its_highlight_colour_and_a_span_colours_the_text() {
8674        let m = map_leaf("a ==\u{1f534} red== b\n", Format::Markdown);
8675        let r = style_of(&m, 'r');
8676        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)));
8677        assert_eq!(r.color, None, "a highlight is not a text colour");
8678
8679        let both = map_leaf(
8680            "<span data-color=\"blue\">a ==\u{1f534} red== b</span>\n",
8681            Format::Markdown,
8682        );
8683        let r = style_of(&both, 'r');
8684        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)), "the highlight");
8685        assert_eq!(r.color, Some(MarkColor::Blue), "the letters");
8686    }
8687
8688    /// A page break is the `::page-break` leaf directive, and djot spells the
8689    /// same document as an empty `::: page-break` fence whose name comes back
8690    /// as a class. Both draw the placeholder row every leaf directive gets and
8691    /// both carry the same [`DirectiveMark`], because a frontend that opens a
8692    /// page at one must not be able to tell which format the file is in.
8693    #[test]
8694    fn a_page_break_reads_the_same_in_markdown_and_in_djot() {
8695        for (fmt, src) in [
8696            (Format::Markdown, "a\n\n::page-break\n\nb\n"),
8697            (Format::Djot, "a\n\n::: page-break\n:::\n\nb\n"),
8698        ] {
8699            let m = map_leaf(src, fmt);
8700            let marks: Vec<&DirectiveMark> = m
8701                .rows
8702                .iter()
8703                .filter_map(|r| r.leaf_directive.as_ref())
8704                .collect();
8705            assert_eq!(marks.len(), 1, "{fmt:?} draws one placeholder");
8706            assert_eq!(marks[0].name, "page-break", "{fmt:?}");
8707            assert!(marks[0].attrs.is_empty(), "{fmt:?}: {:?}", marks[0].attrs);
8708            assert!(
8709                m.rows
8710                    .iter()
8711                    .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>()
8712                        == "\u{29c9} page-break"),
8713                "{fmt:?} draws the label, got {:?}",
8714                m.rows
8715                    .iter()
8716                    .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
8717                    .collect::<Vec<_>>()
8718            );
8719        }
8720
8721        // A Markdown `:::note` with nothing in it is *not* this: its name is
8722        // its own, and nothing about it says "a block with no body" the way
8723        // djot's spelling of a leaf directive does.
8724        let empty_fence = map_leaf("::: note\n:::\n", Format::Markdown);
8725        assert!(
8726            empty_fence.rows.iter().all(|r| r.leaf_directive.is_none()),
8727            "a named empty fence keeps the reading it has"
8728        );
8729    }
8730
8731    /// A djot fence carrying more than its name keeps the rest as an attribute
8732    /// rather than folding it into the name: the *first* class token is the
8733    /// name, because that is where `insert_directive` puts it.
8734    #[test]
8735    fn a_djot_fence_s_first_class_is_the_directive_s_name_and_the_rest_is_attributes() {
8736        let m = map_leaf("{.page-break .wide}\n:::\n:::\n", Format::Djot);
8737        let mark = m
8738            .rows
8739            .iter()
8740            .find_map(|r| r.leaf_directive.as_ref())
8741            .expect("a placeholder");
8742        assert_eq!(mark.name, "page-break");
8743        assert_eq!(
8744            mark.attrs,
8745            vec![("class".to_string(), Some("wide".to_string()))]
8746        );
8747    }
8748}