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;
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::{Baseline, MarkColor, Role, Style};
32
33/// One rendered character plus the source byte offset it originates from.
34/// Synthetic glyphs (a list bullet, a quote gutter) point at their block's
35/// start, so clicking one lands the caret at the start of that block.
36#[derive(Clone)]
37pub struct Glyph {
38    pub ch: char,
39    pub style: Style,
40    pub src: usize,
41    /// Whether the caret may *rest* on this glyph. Decoration — a table border
42    /// or a cell's alignment padding — is visible but isn't text, so the caret
43    /// steps over it instead of into it. It also can't be a stop even in
44    /// principle: a run of decoration shares one `src`, and a caret can only
45    /// move by changing offset, so resting on it would pin horizontal motion.
46    /// A click still maps through `src`, which is why decoration points at the
47    /// text it decorates.
48    ///
49    /// Real text is a stop once per *grapheme cluster*, on the glyph that opens
50    /// it: the continuation glyphs of an emoji or an accented letter are drawn,
51    /// but standing between them is standing inside a character.
52    pub stop: bool,
53}
54
55/// One visual line. `end_src` is the source offset a caret sits at when placed
56/// at the line's end (past its last glyph) — the anchor for end-of-line and
57/// click-past-content.
58///
59/// `Clone` so a block's rows can be cached and re-emitted at a shifted offset
60/// across an edit — see [`BlockCache`].
61#[derive(Clone)]
62pub struct VRow {
63    pub glyphs: Vec<Glyph>,
64    pub end_src: usize,
65    /// A row that is drawn but holds no caret: a table's `├───┼───┤` rules, and
66    /// the blank gap a block boundary is spelled with. Vertical motion steps
67    /// over it, `pos_of_offset` never resolves onto it, and its stops (it has
68    /// none) and `end_src` stay out of the map's stop table.
69    ///
70    /// Emptiness isn't the test — an empty paragraph is a blank row too, and a
71    /// real caret stop. The test is whether the row is somewhere text can go.
72    pub decoration: bool,
73    /// This row is one line of a fenced or indented code block. Set on every row
74    /// the `"code_block"` arm emits — including its blank lines, which carry no
75    /// glyph to tell them apart otherwise. A frontend draws its own chrome (a
76    /// border and a tinted background) around each maximal run of these, and
77    /// scrolls them horizontally instead of wrapping; see
78    /// [`VisualMap::code_blocks`]. Survives the row shuffling of [`BlockCache`]
79    /// reuse and [`build_spliced`] because it rides on the row, not on a
80    /// row-index span the way a table's picture does.
81    pub code: bool,
82    /// A fenced code block's info string (its language), carried on the *first*
83    /// row of the block so it survives row reuse the way [`code`](Self::code)
84    /// does. `None` on every other row, and on an indented block (which has no
85    /// fence to label). A frontend paints it as a small label on the block's box
86    /// and edits it through a prompt — see [`CodeBlockInfo::lang`]. It's a plain
87    /// display string, not a source slice, so it needs no offset shifting; the
88    /// label re-derives from twig on the next build.
89    pub code_lang: Option<String>,
90    /// This row belongs to a `:::name{.class}` directive container — twig's
91    /// generic fenced-div block, whose meaning is entirely up to the host app
92    /// (diaryx's `:::vis{.audience}` visibility blocks, say). Set on every row
93    /// the `"directive"` arm emits, the same way [`code`](Self::code) marks a
94    /// code block's rows, so a frontend can draw a tinted panel around each
95    /// maximal run of these.
96    pub directive: bool,
97    /// A directive container's space-joined attrs — dot-prefixed classes
98    /// (`.public .family` → `"public family"`) unioned with bare pandoc-style
99    /// words (`public family`, no leading dot — diaryx's other `:::vis{...}`
100    /// convention), carried on the block's *first* row only — the
101    /// [`code_lang`](Self::code_lang) pattern. `None` on every other row, and
102    /// when the directive carries no such attrs. A frontend paints it as a
103    /// small label on the block's panel; it's a plain display string, not a
104    /// source slice, so it rides row reuse untouched.
105    pub directive_label: Option<String>,
106    /// Set on the single placeholder row a block-level image renders to, carrying
107    /// the image's destination and alt text; `None` on every other row. The row's
108    /// glyphs are the default `🖼 alt` label (which a plain surface paints as-is);
109    /// an image-capable frontend reads this to paint the real picture instead,
110    /// skipping the row named by [`MediaInfo::rows_span`]. Like
111    /// [`code_lang`](Self::code_lang) it's plain display strings, not source
112    /// slices, so it rides row reuse and needs no offset shifting; the map's
113    /// [`media`](VisualMap::media) side-table is derived from it once the rows
114    /// are final, the same way [`code_blocks`](VisualMap::code_blocks) is.
115    pub media: Option<MediaMark>,
116    /// Set on the **first** row of a task list item, carrying whether its box is
117    /// ticked; `None` on every other row, including a plain `list_item`'s. The
118    /// row's glyphs already draw the box as `☐ `/`☑ ` in the marker's place, so a
119    /// plain surface needs nothing further; a GUI reads this to paint a real
120    /// checkbox widget and to know which way it is facing.
121    ///
122    /// A `bool` rather than a source span, for the reason
123    /// [`code_lang`](Self::code_lang) is a plain string: it rides [`BlockCache`]
124    /// reuse and [`build_spliced`] untouched, needing no offset shifting. To
125    /// *toggle* the box, a frontend maps its click to a source offset the way it
126    /// maps any other — the marker's glyphs carry the item's own `src` — and
127    /// hands that to [`crate::Doc::toggle_task_at`].
128    pub task: Option<bool>,
129    /// Set on the single placeholder row a **leaf** directive (`::name{…}`)
130    /// renders to, carrying its name and attributes; `None` on every other row.
131    /// The container form isn't this — it wraps real blocks and marks each of
132    /// them [`directive`](Self::directive) instead. Like [`media`](Self::media)
133    /// it's plain display strings, so it rides row reuse untouched, and the map's
134    /// [`directives`](VisualMap::directives) side-table is derived from it once
135    /// the rows are final.
136    pub leaf_directive: Option<DirectiveMark>,
137    /// The heading level (1–6) of the block this row belongs to, on every row a
138    /// `heading` emits (a long one wraps to several) and `None` everywhere else.
139    ///
140    /// A frontend that sizes a whole line — a proportional renderer giving the
141    /// row a bigger line box — needs the level *per row*, and the glyphs can't
142    /// always supply it: an empty heading (`# ` with nothing typed after it,
143    /// which is what the toolbar's H1 leaves on a blank line) has no glyph to
144    /// carry a [`Role::Heading`] at all, so a glyph scan called it body text and
145    /// the line drew at body height until the first character landed. Riding the
146    /// row says it once, for the empty case and the wrapped case alike.
147    ///
148    /// Per-*glyph* styling still comes from [`Role::Heading`] on the glyphs; this
149    /// is the row-level fact, and the two agree wherever a heading has content —
150    /// same `u8` level, clamped the same way [`heading_style`] clamps it.
151    pub heading: Option<u8>,
152    /// What this row divides, on the blank rows a block boundary is *drawn* with
153    /// and `None` on every other row — including the navigable blank lines of
154    /// preserve-soft flow, which are somewhere text can go rather than a gap
155    /// between blocks. So `boundary.is_some()` is exactly "this row is a drawn
156    /// block boundary", the [`decoration`](Self::decoration) rows that come from
157    /// [`Builder::emit_separators_before`].
158    ///
159    /// It exists because a boundary's *height* is a frontend decision but its
160    /// *kind* is not. Typography spaces a boundary by what it separates — the
161    /// margin above a heading is wider than the one between two paragraphs, so
162    /// the heading groups with the text it introduces — and a frontend that has
163    /// only rows to look at has to re-derive the structure by sniffing glyph
164    /// roles. Three frontends sniffing separately is three chances to disagree
165    /// about the same document. Core already knows, having just walked the AST
166    /// to emit this row, so it says so once here and each frontend multiplies by
167    /// its own spacing.
168    pub boundary: Option<Boundary>,
169}
170
171/// What a drawn block boundary separates: the kinds of the blocks it falls
172/// between — the pair a frontend spaces by.
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174pub struct Boundary {
175    pub above: BlockClass,
176    pub below: BlockClass,
177}
178
179/// The block kinds core tells apart when it walks a document — the vocabulary
180/// [`Boundary`] is spelled in. A statement about *structure*, not about how any
181/// of it should look: what a frontend does with "this gap sits above a heading"
182/// is entirely the frontend's.
183///
184/// `Class` rather than `Kind` because [`twig::BlockKind`] already means
185/// something else in this crate's public surface — the *command* vocabulary
186/// (`Paragraph | Heading(n)`) a toolbar passes to [`Doc::set_block`](crate::Doc::set_block).
187/// This is the reverse direction: what a block already *is*, read back off a
188/// rendered row.
189///
190/// [`BlockClass::Other`] is the honest answer for a node kind core doesn't
191/// separate out, so adding one here is additive for every frontend: nothing has
192/// to change until it wants to space that kind differently.
193#[derive(Clone, Copy, Debug, PartialEq, Eq)]
194pub enum BlockClass {
195    Paragraph,
196    Heading,
197    /// A whole list. Its *items* are [`BlockClass::ListItem`]; note that core
198    /// draws no boundary row between two items of one list, tight or loose, so
199    /// an item↔item pair never reaches a frontend.
200    List,
201    ListItem,
202    Quote,
203    Code,
204    Table,
205    /// A block-level image, video, or audio.
206    ///
207    /// Never reached through [`from_node_kind`](BlockClass::from_node_kind): a
208    /// block picture is not a node of its own — [`Builder::media_only`] promotes
209    /// the paragraph (or `<picture>`/`<video>` container) wrapping it — so the
210    /// walk only ever sees the wrapper's kind. [`label_media_boundaries`] reads
211    /// it back off the finished rows instead, after the fact.
212    Media,
213    /// A `:::name{.class}` directive container.
214    Directive,
215    Rule,
216    Footnote,
217    Other,
218}
219
220impl BlockClass {
221    /// Classify a twig node kind — the same vocabulary [`Builder::block`]
222    /// matches on, so the two can't drift about what a block is. Both the
223    /// whole-arena walk (which has [`FlatNode`]s) and the incremental top-level
224    /// walk (which has only a query match's kind) reach it by this one door.
225    pub fn from_node_kind(kind: &Kind) -> BlockClass {
226        match kind {
227            Kind::Para => BlockClass::Paragraph,
228            Kind::Heading => BlockClass::Heading,
229            Kind::BulletList | Kind::OrderedList | Kind::TaskList => BlockClass::List,
230            Kind::ListItem | Kind::TaskListItem => BlockClass::ListItem,
231            Kind::BlockQuote => BlockClass::Quote,
232            Kind::CodeBlock => BlockClass::Code,
233            Kind::Table => BlockClass::Table,
234            Kind::Image => BlockClass::Media,
235            // twig 2.8 folded `div`/`span`/`directive`/`element` into one
236            // `container` kind, so a `:::note` panel and a promoted `<video>`
237            // arrive here indistinguishable — telling them apart needs the
238            // node's `origin`, and the incremental walk has only this kind.
239            // `Directive` is the right answer for the case that motivates the
240            // class (nothing else draws a tinted panel) and a harmless one for
241            // the rest: `BlockClass` is descriptive and core never branches on
242            // it. The one case where it was actively wrong — a promoted
243            // `<video>`, which would have been handed to a frontend as something
244            // to draw a fenced-div panel around — is corrected by
245            // [`label_media_boundaries`] once the rows are final, along the same
246            // door as a block image. Anything else that must be exact reads
247            // [`container_is_directive`] off a real node.
248            Kind::Container => BlockClass::Directive,
249            Kind::ThematicBreak => BlockClass::Rule,
250            Kind::Footnote => BlockClass::Footnote,
251            _ => BlockClass::Other,
252        }
253    }
254}
255
256/// The name and attributes a leaf directive's placeholder row carries, so a
257/// frontend that knows the host app's vocabulary can paint the real thing —
258/// an embedded page for diaryx's `::embed{src=…}`, a generated table of
259/// contents for a `::toc`, and the plain `⧉ name` label for one it doesn't
260/// know. The peer of [`MediaMark`], and plain strings for the same reason: they
261/// survive the row shuffling of [`BlockCache`] reuse and [`build_spliced`].
262#[derive(Clone, Debug, PartialEq, Eq)]
263pub struct DirectiveMark {
264    /// The directive's type — `embed`, `toc`, `vis` — with no leading colons.
265    /// Core is agnostic of what it means: the vocabulary is the host app's.
266    pub name: String,
267    /// Its `{…}` attributes as `(key, value)` pairs in source order. A bare
268    /// attribute (`{public}`) has a `None` value, the way twig reports it.
269    pub attrs: Vec<(String, Option<String>)>,
270    /// The directive's `[label]` text, flattened from its inline children, or
271    /// empty when it has none. Also what the placeholder label shows.
272    pub label: String,
273    /// How many visual rows this directive reserves — the label row plus blank
274    /// filler rows below it, so a frontend painting something real has the
275    /// vertical room. `1` is the bare placeholder, and the only value core
276    /// produces today: unlike an image (whose height a terminal frontend
277    /// measures and reports back), nothing has told core how tall an embed is.
278    /// A pixel-laid-out GUI sets its own height regardless.
279    pub rows: usize,
280}
281
282/// What a block-level media placeholder actually is, so a frontend knows which
283/// widget to build over the reserved rows: a raster, a movie player, or a
284/// transport with no picture at all. Core classifies and stops there — it opens
285/// nothing, so this is a statement about the *markup*, not about a file it has
286/// verified exists or can decode.
287#[derive(Clone, Copy, Debug, PartialEq, Eq)]
288pub enum MediaKind {
289    /// A `![](…)` / `<img>` / `<picture>` — a still picture.
290    Image,
291    /// An HTML `<video>`. Markdown and Djot spell no video of their own, so this
292    /// only ever arrives through `html_elements` promotion (or a `::video{…}`
293    /// directive a host app maps itself, which core reports as a directive).
294    Video,
295    /// An HTML `<audio>` — a transport with no picture, so a frontend gives it a
296    /// fixed control height rather than measuring an aspect ratio.
297    Audio,
298}
299
300/// Which of the two caret homes a block media has — see
301/// [`VisualMap::block_media_stop`].
302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
303pub enum MediaStop {
304    /// The stop in front of the picture. What is typed here belongs above it.
305    Before,
306    /// The stop just past it. What is typed here belongs below it.
307    After,
308}
309
310impl MediaKind {
311    /// The emoji a plain surface prefixes the placeholder label with — the
312    /// `🖼`/`🎬`/`🔊` that makes the row read as *a thing* rather than as text.
313    fn sigil(self) -> char {
314        match self {
315            MediaKind::Image => '🖼',
316            MediaKind::Video => '🎬',
317            MediaKind::Audio => '🔊',
318        }
319    }
320}
321
322/// The destination and label a block-level media placeholder row carries, so a
323/// capable frontend can resolve and paint the real thing. Plain strings (no
324/// source offsets), so they survive the row shuffling of [`BlockCache`] reuse
325/// and [`build_spliced`] untouched — see [`VRow::media`].
326#[derive(Clone, Debug, PartialEq, Eq)]
327pub struct MediaMark {
328    /// Whether this is a picture, a movie, or a sound — which widget the
329    /// frontend builds over the reserved rows.
330    pub kind: MediaKind,
331    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
332    /// the AST. A frontend resolves a relative path against the document's
333    /// directory itself; core holds no I/O.
334    ///
335    /// Empty is possible and legal for a `<video>`/`<audio>`, which may carry no
336    /// `src` of its own and name its candidates in child `<source>`s instead —
337    /// unlike an `<img>`, whose `src` *is* the picture. A frontend with an empty
338    /// destination takes its URL from [`sources`](MediaMark::sources).
339    pub destination: String,
340    /// A `<picture>`'s theme/media alternatives, in document order, when this
341    /// block image came from one; empty for a plain `![](…)` / bare `<img>`. Each
342    /// is a `<source>`'s media query + candidate URL(s); a frontend that knows its
343    /// theme picks the first whose media matches and falls back to [`destination`]
344    /// (the `<img>`). Core keeps them verbatim and picks nothing — it has no theme.
345    ///
346    /// [`destination`]: MediaMark::destination
347    pub sources: Vec<MediaSource>,
348    /// The media's alt text (its rendered inline children, flattened), or empty
349    /// when it has none. Also what the placeholder label shows. For a `<video>`/
350    /// `<audio>` this is the element's own text content — the "your browser does
351    /// not support…" fallback, which doubles as its accessible name.
352    pub alt: String,
353    /// A `<video poster="…">`'s still frame, verbatim, or empty when there is
354    /// none (and always empty for an image or audio). It is an *image*
355    /// destination, so a frontend already able to draw a picture can show it
356    /// before the movie loads — or in place of one it can't play at all.
357    pub poster: String,
358    /// How many visual rows this media reserves — the placeholder label row plus
359    /// the blank filler rows below it, so a frontend that paints a real raster has
360    /// the vertical room to draw it. `1` is the bare placeholder (a frontend that
361    /// can't draw pictures, or an image it couldn't resolve). A terminal frontend
362    /// asks for as many rows as the fitted picture is tall; the pixel-laid-out GUI
363    /// ignores this and sets its own row height, so it always leaves it `1`. The
364    /// count comes from the frontend (via [`crate::Doc::set_media_rows`]) because
365    /// core does no I/O and can't measure the image itself. See [`VRow::media`].
366    pub rows: usize,
367}
368
369/// One `<source>` under a `<picture>`, `<video>`, or `<audio>`: a candidate URL
370/// plus whichever of the two things HTML lets a `<source>` be chosen by — a
371/// media query (`<picture>`) or a MIME type (`<video>`/`<audio>`). Verbatim from
372/// the AST: core carries the alternatives and resolves none of them, having
373/// neither a theme nor a codec list to judge them by.
374///
375/// The two spellings are normalised onto one field. `<picture>` writes
376/// `srcset`, `<video>`/`<audio>` write `src`; both land in
377/// [`srcset`](MediaSource::srcset), since a frontend wants the URL either way
378/// and only `<picture>` ever uses the descriptor syntax.
379#[derive(Clone, Debug, PartialEq, Eq)]
380pub struct MediaSource {
381    /// The `<source media="…">` query, verbatim (`"(prefers-color-scheme: dark)"`),
382    /// or empty for a `<source>` with no `media` (an unconditional override, and
383    /// the norm for `<video>`/`<audio>`, which pick by codec rather than theme).
384    pub media: String,
385    /// The candidate URL(s): a `<picture>`'s `srcset` verbatim — one URL, or a
386    /// comma-separated candidate list with `1x`/`2x`/width descriptors — or a
387    /// `<video>`/`<audio>` `<source>`'s plain `src`. A frontend takes the first
388    /// URL token; the theme and codec cases both only ever need that.
389    pub srcset: String,
390    /// The `<source type="…">` MIME type (`"video/webm"`), verbatim, or empty
391    /// when the `<source>` declares none. How a `<video>`/`<audio>` frontend
392    /// picks a candidate it can actually decode; a `<picture>`'s sources
393    /// normally leave it empty and are chosen by [`media`](MediaSource::media).
394    pub mime: String,
395}
396
397/// The rendered document plus the offset⇄position mapping the caret rides on.
398#[derive(Clone, Default)]
399pub struct VisualMap {
400    /// The document's **default monospace rendering** — one [`VRow`] of glyphs
401    /// per visual line, tables spelled with box-drawing borders (`│ ─ ┌┬┐…`) and
402    /// cells padded to whole character-cell columns. Any monospace surface can
403    /// draw these verbatim, so a consumer gets a working view for free: the TUI
404    /// paints them as-is, and a five-line plain-text dump would too.
405    ///
406    /// It's a *default*, not the only truth. A frontend with its own geometry —
407    /// a proportional GUI — lays text out in its own units, and for a table
408    /// skips the box-drawn rows named by [`TableInfo::rows_span`] and draws from
409    /// the structural [`TableInfo`] instead. The box glyphs live here rather than
410    /// in a frontend precisely because they *are* a renderable default: unlike a
411    /// colour (a role each surface must map to its own palette — see
412    /// [`crate::style`]), `┌─┐` is finished text that needs no interpretation.
413    pub rows: Vec<VRow>,
414    /// The first source offset that is actually rendered — the caret floor for
415    /// the WYSIWYG view. Non-zero when a leading `metadata` block (YAML/TOML
416    /// frontmatter) is skipped: the frontmatter is preserved in the source and
417    /// editable in the source view, but hidden and unreachable here, so the
418    /// caret and selection can't wander into it (and copy won't grab it).
419    pub content_start: usize,
420    /// Every offset the caret may rest at, ascending and deduplicated: each
421    /// row's stop glyphs plus the row's own end (the "after the last character"
422    /// spot every line needs). Decoration contributes nothing.
423    ///
424    /// Left/Right read this instead of walking the grid, because the grid isn't
425    /// laid out in offset order: a table with wrapped cells puts column 1's
426    /// second line *below* column 2's first, so "the next stop rightward" and
427    /// "the next stop in the document" part ways. Following the document is what
428    /// a caret means — and on every row that *is* in order the two agree anyway,
429    /// so nothing else has to change.
430    stops: Vec<usize>,
431    /// Every table in the document, in order, described structurally rather than
432    /// drawn — see [`TableInfo`] for why both exist.
433    pub tables: Vec<TableInfo>,
434    /// Every fenced/indented code block, in order, as the range of [`rows`] it
435    /// occupies — a frontend draws one bordered, tinted box around each and
436    /// scrolls it horizontally rather than wrapping. Derived from the per-row
437    /// [`VRow::code`] flag once the rows are final (so it survives incremental
438    /// row reuse), the same way [`collect_stops`] derives the stop table.
439    ///
440    /// [`rows`]: VisualMap::rows
441    pub code_blocks: Vec<CodeBlockInfo>,
442    /// Every block-level image in the document, in order — one per placeholder
443    /// row a frontend replaces with a real picture. Derived from the per-row
444    /// [`VRow::media`] mark once the rows are final (so it survives incremental
445    /// row reuse), the same way [`code_blocks`](VisualMap::code_blocks) is
446    /// derived from [`VRow::code`].
447    pub media: Vec<MediaInfo>,
448    /// Every **leaf** directive in the document, in order — one per placeholder
449    /// row a frontend may replace with whatever the host app's vocabulary makes
450    /// of it. Derived from the per-row [`VRow::leaf_directive`] mark once the
451    /// rows are final, exactly as [`media`](VisualMap::media) is.
452    pub directives: Vec<DirectiveInfo>,
453}
454
455impl VisualMap {
456    pub fn num_rows(&self) -> usize {
457        self.rows.len()
458    }
459
460    /// The width of `row` in display columns — the rightmost column its caret
461    /// can occupy, and so what a goal column is clamped to on the way in.
462    pub fn row_width(&self, row: usize) -> usize {
463        self.rows.get(row).map_or(0, |r| r.width())
464    }
465
466    /// The screen `(row, col)` for a source offset — where to draw the caret:
467    /// the *nearest* stop at or past `off`. Snaps a hidden offset (inside a
468    /// delimiter) to the next visible glyph, and never resolves onto decoration
469    /// (a table border, a cell's padding), which is drawn but holds no caret.
470    ///
471    /// "Nearest" rather than "the first one found" because a table's wrapped
472    /// cells put rows slightly out of offset order: scanning top to bottom, the
473    /// second line of column 1 comes *after* the first line of column 2 but
474    /// holds smaller offsets. Where rows are in order the two rules agree.
475    ///
476    /// A soft wrap is the one place two rows want the same offset: the row above
477    /// ends where the row below opens, the space the wrap ate being drawn on the
478    /// row above and the offset past it being the row below's first character.
479    /// It resolves *downstream*, to the row that character is on — the row
480    /// above's last column is a phantom, a place the caret can be drawn but
481    /// never sent, and resolving upstream into it is what pinned Down at the
482    /// first wrap of a paragraph: it aimed at the row below's column 0, landed
483    /// on the offset it already had, and read that back as the row above's end.
484    pub fn pos_of_offset(&self, off: usize) -> (usize, usize) {
485        let mut best: Option<(usize, usize, usize)> = None; // (src, row, col)
486        for (r, row) in self.rows.iter().enumerate() {
487            if row.decoration {
488                continue;
489            }
490            // Offsets ascend *within* a row, so its first stop at or past `off`
491            // is the best this row has to offer.
492            let cand = row
493                .glyphs
494                .iter()
495                .enumerate()
496                .find(|(_, g)| g.stop && g.src >= off)
497                .map(|(i, g)| (g.src, r, row.col_of_glyph(i)))
498                .or_else(|| (row.end_src >= off).then_some((row.end_src, r, row.width())));
499            if let Some(c) = cand {
500                // `<=`, so a tie goes to the later row: the only offset two rows
501                // both hold is a wrap boundary, and it belongs to the row below.
502                if best.is_none_or(|b| c.0 <= b.0) {
503                    best = Some(c);
504                }
505            }
506            // A row's *first* stop never decreases from one row to the next —
507            // true even across a table's wrapped cells, since a cell's lines run
508            // downward. So once a row opens past the best found so far, no later
509            // row can beat it and the scan stays proportional to `off`.
510            if let (Some(b), Some(first)) = (best, row.glyphs.iter().find(|g| g.stop))
511                && first.src > b.0
512            {
513                break;
514            }
515        }
516        match best {
517            Some((_, r, c)) => (r, c),
518            None => {
519                let r = self.last_stop_row();
520                (r, self.row_width(r))
521            }
522        }
523    }
524
525    /// The rows a source range occupies, inclusive: `(first, last)`.
526    ///
527    /// A *different question* from [`pos_of_offset`](Self::pos_of_offset), which
528    /// is why it can't be spelled with two calls to it. That one answers "where
529    /// does the caret go", and for a caret its forward snap is right — an offset
530    /// inside a hidden delimiter has no column of its own, so the caret belongs
531    /// at the next visible glyph, wherever that turns out to be. This one asks
532    /// "which rows does this block cover", and there the snap is a trap: a
533    /// footnote whose body *ends* in a link (`[^2]: [title](url)`) has a last
534    /// byte inside the hidden destination, so `pos_of_offset(end - 1)` walked
535    /// clean off the note's row and landed on the next note's — and a peek
536    /// slicing `first..=last` out of the frame drew two notes where the reader
537    /// asked for one. Every block ending in a link, an image, or any trailing
538    /// hidden markup had the same fault; only a block ending in visible text
539    /// (which is what the tests happened to use) did not.
540    ///
541    /// `row.end_src` is no help either: it is where the *rendered* text of a row
542    /// ends, not how far into the source the block reaches, and redefining it
543    /// would move every end-of-line caret.
544    ///
545    /// So the last row is found by asking which rows *open* before the range
546    /// does, rather than by mapping its last byte: a row belongs to the range
547    /// when its first caret stop lies before `range.end`. Decoration is skipped
548    /// (a drawn gap between blocks is not part of either), and the answer is
549    /// never shorter than one row — a range whose every byte is hidden still
550    /// covers the row it started on.
551    pub fn row_range_for(&self, range: Range<usize>) -> (usize, usize) {
552        if self.rows.is_empty() {
553            return (0, 0);
554        }
555        let first = self.pos_of_offset(range.start).0;
556        let mut last = first;
557        for (r, row) in self.rows.iter().enumerate().skip(first) {
558            if row.decoration {
559                continue;
560            }
561            let open = row
562                .glyphs
563                .iter()
564                .find(|g| g.stop)
565                .map_or(row.end_src, |g| g.src);
566            if open >= range.end {
567                // A row's first stop never decreases from one row to the next —
568                // the invariant `pos_of_offset` breaks on, true even across a
569                // table's wrapped cells — so nothing below can be in range.
570                break;
571            }
572            last = r;
573        }
574        (first, last)
575    }
576
577    /// The source offset of the task checkbox drawn at `(row, col)`, or `None`
578    /// when that cell holds no box — the hit-test a frontend runs on a click
579    /// before treating it as a tick rather than a caret placement.
580    ///
581    /// Only the box's own cells answer. Clicking an item's *text* places the
582    /// caret like any other click, so the box is a target aimed at rather than
583    /// something tripped over while editing — which is also why this is a
584    /// separate question from [`offset_of_pos`](Self::offset_of_pos) instead of
585    /// a flag on the offset it returns.
586    pub fn task_box_at(&self, row: usize, col: usize) -> Option<usize> {
587        let r = self.rows.get(row)?;
588        self.task_box_at_glyph(row, r.glyph_at_col(col)?)
589    }
590
591    /// [`task_box_at`](Self::task_box_at) keyed by glyph index rather than
592    /// display column — for a frontend that shapes its own rows (the GUI) and so
593    /// resolves a click to a glyph before it ever has a column.
594    pub fn task_box_at_glyph(&self, row: usize, glyph: usize) -> Option<usize> {
595        let r = self.rows.get(row)?;
596        r.task?;
597        let g = r.glyphs.get(glyph)?;
598        (g.style.role == Role::ListMarker).then_some(g.src)
599    }
600
601    /// The source offset for a screen `(row, col)` — where a click or a
602    /// visual-space move lands the caret. Clicking decoration maps through its
603    /// `src`, which points at the text it decorates, so a click on a border or
604    /// on a cell's padding lands in that cell.
605    ///
606    /// The inverse of [`pos_of_offset`](Self::pos_of_offset), which it has to
607    /// agree with: `col` is a display column, and the one it names may be the
608    /// far cell of a wide glyph — [`VRow::glyph_at_col`] is where that lands.
609    pub fn offset_of_pos(&self, row: usize, col: usize) -> usize {
610        let Some(r) = self.rows.get(row) else {
611            // A click or drag below the last row — a short document with empty
612            // space under it, dragged into to extend a selection. Land on the
613            // document's last caret stop (its end), not offset 0: jumping the
614            // caret to the top is the wrong direction, and 0 isn't even a stop
615            // when the document opens on hidden frontmatter or a `# ` marker, so
616            // returning it would leave the caret where it draws in one place and
617            // types in another (`move_to` would then clamp it onto the unhomeable
618            // frontmatter floor). `None` only for a document with no stops at all
619            // (empty), where the caret has nowhere to be but 0.
620            return self.stops.last().copied().unwrap_or(0);
621        };
622        match r.glyph_at_col(col).and_then(|i| r.glyphs.get(i)) {
623            // A glyph that holds no caret is clickable, but where it points
624            // isn't always somewhere the caret can be: the blank gap between two
625            // paragraphs stands at an offset that belongs to neither of them,
626            // and the tail of a grapheme cluster stands inside a character.
627            // Land on the nearest real stop instead of handing back an offset
628            // that looks like the gap but types into the paragraph above.
629            Some(g) if !g.stop => self.nearest_stop(g.src),
630            Some(g) => g.src,
631            // A row's end is a stop by construction — unless the row is
632            // decoration, which contributes none.
633            None if r.decoration => self.nearest_stop(r.end_src),
634            None => r.end_src,
635        }
636    }
637
638    /// Which of a block media's two caret homes `off` is, or `None` for every
639    /// other offset in the document.
640    ///
641    /// [`block_media`](Builder::block_media) gives a block-level image, video, or
642    /// audio exactly two stops — one in front of it and one just past it — and
643    /// nothing inside the markup. Both are ordinary offsets to everything else in
644    /// core, but they are the two places where inserting text would *dissolve the
645    /// picture*: `![](p.png)` with anything typed against it is no longer a block
646    /// image but a paragraph with an inline one, and the frontend that was
647    /// painting a photo there paints a text run instead. A caller that is about to
648    /// insert asks this so it can open a paragraph first — see
649    /// [`Doc::insert`](crate::Doc::insert).
650    ///
651    /// An *inline* image reports `None`: it has no placeholder row and no stops of
652    /// its own, and typing beside one is ordinary editing.
653    ///
654    /// Answers with the media's own source span as well, since a caller that has
655    /// to keep the picture whole usually has to address it — [`Doc::backspace`]
656    /// takes the picture out in one piece rather than nibbling a byte off its
657    /// markup, which is the same dissolution from the other side.
658    ///
659    /// [`Doc::backspace`]: crate::Doc::backspace
660    pub fn block_media_stop(&self, off: usize) -> Option<(MediaStop, Range<usize>)> {
661        for m in &self.media {
662            let Some(row) = self.rows.get(m.rows_span.start) else {
663                continue;
664            };
665            // Every glyph of the `🖼 alt` label maps to the media's start offset;
666            // the row's end is past its markup. Read the start off the label
667            // rather than the first glyph, which on a quoted or listed picture is
668            // the block prefix and points at the gutter.
669            let Some(start) = row
670                .glyphs
671                .iter()
672                .find(|g| g.style.role == Role::Image)
673                .map(|g| g.src)
674            else {
675                continue;
676            };
677            if off == start {
678                return Some((MediaStop::Before, start..row.end_src));
679            }
680            if off == row.end_src {
681                return Some((MediaStop::After, start..row.end_src));
682            }
683        }
684        None
685    }
686
687    /// Snap `off` to the nearest caret stop — the funnel a frontend that
688    /// hit-tests pixels straight to a source offset must run its result through.
689    /// A click or drag can land in the blank gap a paragraph break is drawn with,
690    /// or inside a hidden delimiter; both are offsets the caret can't rest at, so
691    /// resting there would draw the caret in one place and type in another. This
692    /// settles it on a real caret home instead. Idempotent on an offset that is
693    /// already a stop — the `(row, col)` click path already snaps this way inside
694    /// [`offset_of_pos`](Self::offset_of_pos), and this gives the pixel path the
695    /// same guarantee. Returns `off` unchanged only for an empty document (no
696    /// stops at all).
697    pub fn snap_to_stop(&self, off: usize) -> usize {
698        self.nearest_stop(off)
699    }
700
701    /// The caret stop nearest `off`, preferring the one before it when `off`
702    /// falls exactly between two. Returns `off` unchanged if there are no stops
703    /// at all (an empty document).
704    fn nearest_stop(&self, off: usize) -> usize {
705        let i = self.stops.partition_point(|&s| s < off);
706        let after = self.stops.get(i).copied();
707        let before = i.checked_sub(1).map(|j| self.stops[j]);
708        match (before, after) {
709            (Some(b), Some(a)) if off - b <= a - off => b,
710            (_, Some(a)) => a,
711            (Some(b), None) => b,
712            (None, None) => off,
713        }
714    }
715
716    /// Whether the caret can occupy `row` at all: decoration rows (a table's
717    /// border rules) are stepped over by vertical motion.
718    pub fn row_is_navigable(&self, row: usize) -> bool {
719        self.rows.get(row).is_some_and(|r| !r.decoration)
720    }
721
722    /// The first offset the caret can rest at on `row` — its first stop, or the
723    /// row's own end when it holds no text (an empty paragraph). `None` for a
724    /// decoration row, which holds no caret at all.
725    ///
726    /// Not `offset_of_pos(row, 0)`: column 0 of a quoted or listed row is the
727    /// gutter, and a gutter's `src` points at the *block* it opens, so the stop
728    /// nearest it is the one on the block's first row rather than on this one.
729    /// Which is right for a click — the gutter decorates the whole block — and
730    /// wrong for Home, whose whole question is where *this* row starts.
731    pub fn row_start(&self, row: usize) -> Option<usize> {
732        let r = self.rows.get(row).filter(|r| !r.decoration)?;
733        Some(
734            r.glyphs
735                .iter()
736                .find(|g| g.stop)
737                .map_or(r.end_src, |g| g.src),
738        )
739    }
740
741    /// The last row the caret can rest on — the fallback when an offset is past
742    /// everything rendered (a table's bottom border must not swallow the caret).
743    fn last_stop_row(&self) -> usize {
744        (0..self.rows.len())
745            .rev()
746            .find(|&r| self.row_is_navigable(r))
747            .unwrap_or(0)
748    }
749
750    /// The nearest row above `row` the caret can occupy, skipping decoration.
751    pub fn navigable_above(&self, row: usize) -> Option<usize> {
752        (0..row.min(self.rows.len()))
753            .rev()
754            .find(|&r| self.row_is_navigable(r))
755    }
756
757    /// The nearest row below `row` the caret can occupy, skipping decoration.
758    pub fn navigable_below(&self, row: usize) -> Option<usize> {
759        ((row + 1)..self.rows.len()).find(|&r| self.row_is_navigable(r))
760    }
761
762    /// The caret stop just before `off` — one press of Left. `None` at the
763    /// first stop in the document.
764    ///
765    /// Runs of decoration (a table border, a cell's alignment padding) are
766    /// stepped over in a single press: they hold no stop, so they aren't in the
767    /// table to land on.
768    pub fn stop_before(&self, off: usize) -> Option<usize> {
769        let i = self.stops.partition_point(|&s| s < off);
770        i.checked_sub(1).map(|i| self.stops[i])
771    }
772
773    /// The caret stop just after `off` — one press of Right. `None` at the last
774    /// stop in the document.
775    pub fn stop_after(&self, off: usize) -> Option<usize> {
776        let i = self.stops.partition_point(|&s| s <= off);
777        self.stops.get(i).copied()
778    }
779
780    /// The first caret stop at or past `off` — where the caret at a hidden
781    /// offset is *drawn*, and so where a rightward walk over the rendered text
782    /// starts from.
783    pub fn stop_at_or_after(&self, off: usize) -> Option<usize> {
784        let i = self.stops.partition_point(|&s| s < off);
785        self.stops.get(i).copied()
786    }
787
788    /// The last caret stop at or before `off` — where a leftward walk starts
789    /// from. Snapping the way the walk is headed, rather than always forward,
790    /// is what keeps a leftward motion from ever moving the caret right.
791    pub fn stop_at_or_before(&self, off: usize) -> Option<usize> {
792        let i = self.stops.partition_point(|&s| s <= off);
793        i.checked_sub(1).map(|i| self.stops[i])
794    }
795
796    /// Whether the caret may rest at `off` — the invariant every motion in this
797    /// view has to leave standing.
798    pub fn is_stop(&self, off: usize) -> bool {
799        self.stops.binary_search(&off).is_ok()
800    }
801
802    /// The visible text a caret crosses walking rightward from `from` up to
803    /// (but not including) `to` — `UITextInput.text(in:)`'s `[from, to)` in
804    /// *this* view. A hidden inline-mark delimiter (`**`, `` ` ``, `_`, an
805    /// escape backslash) never got a glyph in the first place — see
806    /// [`push_text`]/[`synth`] — so it contributes nothing; what's left is
807    /// exactly what's drawn on screen for that span.
808    ///
809    /// Built from the same stop glyphs [`stop_after`](Self::stop_after) steps
810    /// across (every glyph with [`Glyph::stop`] set, i.e. one per grapheme
811    /// cluster, decoration excluded) — **plus one inserted `'\n'` for every
812    /// genuine block boundary strictly inside `[from, to)`**: a run of whole
813    /// [`decoration`] rows sitting between two content rows — a paragraph
814    /// gap, a table rule, an image's reserved filler rows — never an ordinary
815    /// soft wrap, which puts no decoration *row* between the two halves of
816    /// its one paragraph (only inline decoration glyphs, e.g. a table's `│`,
817    /// live inside a single content row, and never split one).
818    ///
819    /// [`decoration`]: VRow::decoration
820    ///
821    /// Without that inserted break, two blocks abutting in this string were
822    /// indistinguishable from one run of text: [`collect_stops`] gives a
823    /// block boundary *zero* stops of its own (crossing one is a single,
824    /// free hop — see `the_caret_skips_the_gap_between_two_paragraphs` in
825    /// `doc.rs`'s tests, which pins that as intentional caret behaviour, a
826    /// paragraph gap costing no extra Right presses, not a bug to fix here).
827    /// So the last word of one paragraph and the first word of the next used
828    /// to land directly adjacent with *nothing* between them in this string
829    /// (`"...edb\n\nhello\n"` read back as `"edbhello"`), and `UITextInput`'s
830    /// default word tokenizer then saw one unbroken run of letters and
831    /// selected across the boundary — reported as double-tapping the last
832    /// word on a line expanding the selection into the following
833    /// paragraph(s).
834    ///
835    /// This means the once-strict equality with `distance_offset`/
836    /// `step_offset` (`leaf-ffi`) no longer always holds: those intentionally
837    /// keep costing a block boundary *zero* stops, while this text now
838    /// spends one *character* on it that is never itself a stop. So the
839    /// relationship is `visible_text(a, b).chars().count() >=
840    /// distance_offset(a, b)`, equality holding whenever `(a, b)` spans no
841    /// block boundary (the common case, and the only case the previous
842    /// equality was ever tested against). It can only ever be *greater*,
843    /// never less: every character this function omits relative to a plain
844    /// stop count is a stop with no glyph of its own (a hidden delimiter, or
845    /// a block's own trailing "end of row" stop), and every such omission at
846    /// a block's end is exactly paired with the one inserted separator that
847    /// follows it, so nothing this function returns is ever short of what a
848    /// consumer walking stops one at a time would need. That inequality is
849    /// still exactly what `UITextInput`'s tokenizer needs: it only ever reads
850    /// this string to find a boundary and converts the character index it
851    /// finds back to a position with `position(from:offset:)`, which walks
852    /// stops — an inserted separator is never handed back as one, it only
853    /// keeps two paragraphs' words apart for the tokenizer's letter-run scan.
854    ///
855    /// `from` is snapped to its nearest stop first, exactly as a caret asked
856    /// to stand at a hidden offset is drawn at the next stop instead; `to` is
857    /// left as given, so a stop landing exactly on it is still the walk's
858    /// last step — the same asymmetry `distance_offset`'s own loop has.
859    pub fn visible_text(&self, from: usize, to: usize) -> String {
860        self.visible_items(from, to)
861            .into_iter()
862            .map(|(_, ch)| ch.unwrap_or('\n'))
863            .collect()
864    }
865
866    /// The UTF-16 length of `visible_text(from, to)` — what an `NSRange`
867    /// location into that text is, without building the string.
868    ///
869    /// AppKit's `NSTextInputClient` and `NSAccessibility` speak in UTF-16
870    /// units of *the text as the system sees it*, which for leaf is the visible
871    /// text — delimiters hidden. A frontend reporting its selection to the
872    /// system converts each end with this and gets back an index into the
873    /// string `visible_text(0, end)` returns, which is exactly what the system
874    /// will index into.
875    pub fn visible_utf16_len(&self, from: usize, to: usize) -> usize {
876        self.visible_items(from, to)
877            .into_iter()
878            .map(|(_, ch)| ch.map_or(1, char::len_utf16))
879            .sum()
880    }
881
882    /// The inverse of `visible_utf16_len(0, ·)`: the source offset of the
883    /// visible character a UTF-16 index into `visible_text(0, to)` lands on.
884    ///
885    /// An index inside a surrogate pair resolves to the character that owns
886    /// it; one at or past the end of the text returns `None`, so a caller can
887    /// substitute the document's end stop. A synthetic block separator (the
888    /// `\n` the text spells a boundary with) resolves to the gap offset, which
889    /// is not a stop, so a caller placing a caret there gets it snapped like
890    /// any other hidden offset.
891    pub fn offset_at_visible_utf16(&self, to: usize, index: usize) -> Option<usize> {
892        let mut seen = 0usize;
893        for (src, ch) in self.visible_items(0, to) {
894            let len = ch.map_or(1, char::len_utf16);
895            if index < seen + len {
896                return Some(src);
897            }
898            seen += len;
899        }
900        None
901    }
902
903    /// The items `visible_text` spells, in order: every stop glyph in range
904    /// keyed by its own source offset (`Some(ch)`), and every block boundary
905    /// in range keyed by its gap offset (`None`, drawn as `\n`).
906    fn visible_items(&self, from: usize, to: usize) -> Vec<(usize, Option<char>)> {
907        let from = self.nearest_stop(from);
908
909        // Real content: every stop glyph in range, keyed by its own source
910        // offset (`None` tags it as a genuine character, versus the
911        // synthetic separators below).
912        let mut items: Vec<(usize, Option<char>)> = self
913            .rows
914            .iter()
915            .filter(|r| !r.decoration)
916            .flat_map(|r| r.glyphs.iter())
917            .filter(|g| g.stop && g.src >= from && g.src < to)
918            .map(|g| (g.src, Some(g.ch)))
919            .collect();
920
921        // Every whole decoration row is a candidate block boundary; its
922        // `end_src` is the gap offset itself (never a stop — see
923        // `place_caret_snaps_out_of_the_blank_gap_between_paragraphs` in
924        // `doc.rs`) — a source offset like any glyph's, so it merges into the
925        // same ordering. `None` marks it a synthetic separator rather than a
926        // real character, tagged distinctly so a query landing exactly on the
927        // gap offset still opens with its break even with no glyph on either
928        // side to anchor it to (a range spanning nothing but a bare gap).
929        let mut boundaries: Vec<usize> = self
930            .rows
931            .iter()
932            .filter(|r| r.decoration)
933            .map(|r| r.end_src)
934            .filter(|&src| src >= from && src < to)
935            .collect();
936        boundaries.sort_unstable();
937        boundaries.dedup();
938        items.extend(boundaries.into_iter().map(|src| (src, None)));
939
940        // Row order matches source order except across a table's wrapped
941        // cells (see `pos_of_offset`), so sort rather than trust it here too.
942        // A boundary can't share an offset with a glyph (it's the undrawn gap
943        // between two blocks' real content), so tie-breaking never arises.
944        items.sort_by_key(|&(src, _)| src);
945        items
946    }
947}
948
949/// Collect the caret stops of a laid-out grid: every stop glyph's offset plus
950/// every row's end, ascending and deduplicated. Duplicates are the norm rather
951/// than the exception — a wrapped line's end is the same offset as the next
952/// line's first glyph — and collapsing them is what makes one press of Left or
953/// Right cross exactly one stop.
954fn collect_stops(rows: &[VRow]) -> Vec<usize> {
955    let mut stops: Vec<usize> = rows
956        .iter()
957        .filter(|r| !r.decoration)
958        .flat_map(|r| {
959            r.glyphs
960                .iter()
961                .filter(|g| g.stop)
962                .map(|g| g.src)
963                .chain(std::iter::once(r.end_src))
964        })
965        .collect();
966    stops.sort_unstable();
967    stops.dedup();
968    stops
969}
970
971/// Group the rows tagged [`VRow::code`] into one [`CodeBlockInfo`] per maximal
972/// run — the block-level view a frontend needs to box and scroll each code
973/// block. Two code blocks are always parted by the blank separator row a block
974/// boundary is spelled with (never itself a code row), so a contiguous run is
975/// exactly one block. Derived from the final rows rather than tracked through
976/// the builder so it comes out right no matter how [`build_cached`] and
977/// [`build_spliced`] shuffle rows around.
978fn code_block_spans(rows: &[VRow]) -> Vec<CodeBlockInfo> {
979    let mut blocks = Vec::new();
980    let mut start: Option<usize> = None;
981    for (i, row) in rows.iter().enumerate() {
982        match (row.code, start) {
983            (true, None) => start = Some(i),
984            (false, Some(s)) => {
985                blocks.push(CodeBlockInfo {
986                    rows_span: s..i,
987                    lang: rows[s].code_lang.clone(),
988                });
989                start = None;
990            }
991            _ => {}
992        }
993    }
994    if let Some(s) = start {
995        blocks.push(CodeBlockInfo {
996            rows_span: s..rows.len(),
997            lang: rows[s].code_lang.clone(),
998        });
999    }
1000    blocks
1001}
1002
1003/// The value of `node`'s `key` attribute, if it carries one *with* a value. A
1004/// bare attribute (`controls`, `muted`) has a `None` value and so reads as
1005/// absent here — a caller wanting presence-not-value tests the list directly.
1006/// Shared by the media element and `<source>` readers.
1007fn attr_of(node: &FlatNode, key: &str) -> Option<String> {
1008    node.attrs
1009        .iter()
1010        .find(|(k, _)| k == key)
1011        .and_then(|(_, v)| v.clone())
1012}
1013
1014/// Collect one [`MediaInfo`] per row carrying a [`VRow::media`] mark — the
1015/// block-level view a frontend needs to replace each placeholder row with a real
1016/// picture. The mark rides the block's *first* row and names how many rows the
1017/// media reserves ([`MediaMark::rows`]); the rows below it are blank
1018/// [`decoration`](VRow::decoration) fillers that hold the vertical space and no
1019/// caret. So the span runs from the marked row across those fillers. Derived from
1020/// the final rows rather than tracked through the builder so it survives however
1021/// [`build_cached`] and [`build_spliced`] shuffle rows around.
1022fn media_spans(rows: &[VRow]) -> Vec<MediaInfo> {
1023    rows.iter()
1024        .enumerate()
1025        .filter_map(|(i, row)| {
1026            row.media.as_ref().map(|m| MediaInfo {
1027                rows_span: i..i + m.rows.max(1),
1028                kind: m.kind,
1029                destination: m.destination.clone(),
1030                sources: m.sources.clone(),
1031                alt: m.alt.clone(),
1032                poster: m.poster.clone(),
1033            })
1034        })
1035        .collect()
1036}
1037
1038/// Re-label the drawn block boundaries either side of a block-level media
1039/// placeholder, so the pair a frontend spaces by names the picture.
1040///
1041/// [`BlockClass::from_node_kind`] classifies the node the walk is standing on,
1042/// and a block image is never a node of its own: [`Builder::media_only`] promotes
1043/// its *wrapper* — a `paragraph`, or the `container` a `<video>`/`<audio>`
1044/// arrives as — so the gap above a picture reported [`BlockClass::Paragraph`] and
1045/// the gap above a movie reported [`BlockClass::Directive`], the class a frontend
1046/// paints a tinted panel for. [`BlockClass::Media`] was unreachable in
1047/// consequence: the vocabulary named a kind no frontend could ever be told about.
1048///
1049/// Done as a pass over the finished rows rather than inside the walk because
1050/// only the rows know. The incremental top-level walk carries no node arena at
1051/// all (`nodes: &[]`) and can classify by kind alone, so teaching the wrapper
1052/// promotion to the whole-arena walk would label the full and incremental builds
1053/// differently — the exact drift that walk's own comment forbids. Both builds
1054/// emit the same [`VRow::media`] marks, so both reach the same answer here. The
1055/// [`media_spans`] / [`code_block_spans`] pattern.
1056///
1057/// One gap can be spelled with several rows — [`Builder::emit_separators_before`]
1058/// draws the row that closes the block above and the row that opens the block
1059/// below, with any extra blank source lines navigable between them — and gives
1060/// every one of them the same [`Boundary`]. So the walk crosses those navigable
1061/// blanks and relabels the whole run, stopping at the first row that is neither.
1062fn label_media_boundaries(rows: &mut [VRow]) {
1063    let spans: Vec<Range<usize>> = rows
1064        .iter()
1065        .enumerate()
1066        .filter_map(|(i, row)| row.media.as_ref().map(|m| i..i + m.rows.max(1)))
1067        .collect();
1068    // A row inside one gap: a drawn boundary to relabel, or one of the navigable
1069    // blank lines sitting between two drawn ones. Anything else ends the run.
1070    fn in_gap(row: &VRow) -> bool {
1071        row.boundary.is_some() || (!row.decoration && row.glyphs.is_empty())
1072    }
1073    for span in spans {
1074        for i in (0..span.start).rev() {
1075            if !in_gap(&rows[i]) {
1076                break;
1077            }
1078            if let Some(b) = rows[i].boundary.as_mut() {
1079                b.below = BlockClass::Media;
1080            }
1081        }
1082        for row in rows.iter_mut().skip(span.end) {
1083            if !in_gap(row) {
1084                break;
1085            }
1086            if let Some(b) = row.boundary.as_mut() {
1087                b.above = BlockClass::Media;
1088            }
1089        }
1090    }
1091}
1092
1093/// Collect one [`DirectiveInfo`] per row carrying a [`VRow::leaf_directive`]
1094/// mark — the block-level view a frontend needs to replace each placeholder row
1095/// with whatever the directive means to it. The peer of [`media_spans`], derived
1096/// from the final rows for the same reason: it survives however [`build_cached`]
1097/// and [`build_spliced`] shuffle rows around.
1098fn directive_spans(rows: &[VRow]) -> Vec<DirectiveInfo> {
1099    rows.iter()
1100        .enumerate()
1101        .filter_map(|(i, row)| {
1102            row.leaf_directive.as_ref().map(|m| DirectiveInfo {
1103                rows_span: i..i + m.rows.max(1),
1104                name: m.name.clone(),
1105                attrs: m.attrs.clone(),
1106                label: m.label.clone(),
1107            })
1108        })
1109        .collect()
1110}
1111
1112/// The source range of a fenced code block's info string — everything on the
1113/// opening line past the fence (`` ```rust `` → the `rust`). `block_start` is the
1114/// code block node's `span.start`. `None` for an indented code block, which
1115/// opens with no fence to carry one. The range is empty for a fence written
1116/// bare (`` ``` `` alone), which is exactly where a language would be inserted.
1117///
1118/// Shared by the WYSIWYG builder (to label the box) and [`crate::Doc`] (to edit
1119/// the label through a prompt), so the two agree on where the language lives.
1120pub fn code_info_span(source: &str, block_start: usize) -> Option<Range<usize>> {
1121    let rest = source.get(block_start..)?;
1122    let line_len = rest.find('\n').unwrap_or(rest.len());
1123    let line = &rest[..line_len];
1124    // A fence may be indented up to three spaces; past that it opens with a run
1125    // of the same fence character.
1126    let indent = line.len() - line.trim_start().len();
1127    if indent > 3 {
1128        return None;
1129    }
1130    let fence = line[indent..].chars().next()?;
1131    if fence != '`' && fence != '~' {
1132        return None; // an indented block, not a fenced one
1133    }
1134    let fence_len = line[indent..].chars().take_while(|&c| c == fence).count();
1135    let info_start = block_start + indent + fence_len;
1136    Some(info_start..block_start + line_len)
1137}
1138
1139/// A fenced code block's language for display: its info string, trimmed, or
1140/// `None` when there's no fence or the fence carries no language. The trimmed
1141/// text is what a frontend labels the box with; [`code_info_span`] is what an
1142/// edit replaces.
1143pub fn code_language(source: &str, block_start: usize) -> Option<String> {
1144    let span = code_info_span(source, block_start)?;
1145    let text = source.get(span)?.trim();
1146    (!text.is_empty()).then(|| text.to_string())
1147}
1148
1149/// A horizontal rule's dash count when the map isn't wrapping to a column grid
1150/// (the GUI, which wraps at pixel width): a fixed, sane width the frontend can
1151/// paint or re-wrap, instead of a runaway count from an unbounded wrap width.
1152const UNWRAPPED_RULE_WIDTH: usize = 40;
1153
1154/// Render the document to a [`VisualMap`]. `wrap` is the column budget for
1155/// word-wrapping (`Some` for the monospace TUI), or `None` to emit one row per
1156/// block — the GUI does its own proportional pixel wrapping over these rows.
1157/// Text and offsets come from the AST (`str` nodes carry the verbatim source
1158/// slice and an exact span), so the original source string isn't needed here.
1159pub fn build(
1160    nodes: &[FlatNode],
1161    source: &str,
1162    wrap: Option<usize>,
1163    preserve_soft: bool,
1164    media_rows: &HashMap<String, usize>,
1165    reveal: Option<Range<usize>>,
1166) -> VisualMap {
1167    let Some(doc) = nodes.iter().position(|n| n.kind == Kind::Doc) else {
1168        return VisualMap::default();
1169    };
1170    let top = top_level(nodes, doc);
1171    let mut b = Builder {
1172        nodes,
1173        source,
1174        wrap: wrap.map(|w| w.max(8)),
1175        rows: Vec::new(),
1176        tables: Vec::new(),
1177        last_off: 0,
1178        media_rows,
1179        break_glyph: Cell::new(' '),
1180        preserve_soft,
1181        reveal: reveal.clone(),
1182    };
1183    b.top_blocks(&top);
1184    // The hidden frontmatter's end is the baseline for both the trailing blank
1185    // rows and the caret floor — see [`hidden_prefix_end`]. `top_level` has
1186    // already dropped every `metadata` child, so read it off the arena.
1187    let hidden_end = hidden_prefix_end(source, metadata_end_of(nodes, doc));
1188    b.emit_trailing_blank_lines(
1189        top.last().map_or(BlockClass::Paragraph, |&i| {
1190            BlockClass::from_node_kind(&nodes[i].kind)
1191        }),
1192        hidden_end,
1193    );
1194    let content_start = top.first().map_or(hidden_end, |&i| nodes[i].span.start);
1195    let stops = collect_stops(&b.rows);
1196    label_media_boundaries(&mut b.rows);
1197    let code_blocks = code_block_spans(&b.rows);
1198    let media = media_spans(&b.rows);
1199    let directives = directive_spans(&b.rows);
1200    VisualMap {
1201        rows: b.rows,
1202        content_start,
1203        stops,
1204        tables: b.tables,
1205        code_blocks,
1206        media,
1207        directives,
1208    }
1209}
1210
1211/// Like [`build`], but reuses a persistent [`BlockCache`] so an edit re-renders
1212/// only the top-level blocks whose source bytes changed *and* marshals only
1213/// those blocks from twig instead of the whole arena.
1214///
1215/// `top` is the document's top-level blocks — twig's `child_spans` of the doc
1216/// root: `(node_id, kind, span)` for each, in order. `fetch_subtree(node_id)`
1217/// marshals one block's subtree (local-indexed, root at 0) and is called *only*
1218/// for a block that missed the cache, i.e. one that actually changed. So a
1219/// keystroke marshals one small subtree, not ~20k nodes. The result is
1220/// byte-for-byte identical to [`build`] on the same document (the
1221/// `build_cached_matches_build` test pins this); [`build`] stays the cache-free,
1222/// whole-arena reference. This is the entry point [`crate::Doc`] uses.
1223// One builder, and every one of these is a distinct input to the same layout
1224// pass — a struct of them would be built at the one call site and unpacked
1225// here, which is the same arguments with an extra name in the way.
1226#[allow(clippy::too_many_arguments)]
1227pub fn build_cached(
1228    top: &[QueryMatch],
1229    source: &str,
1230    wrap: Option<usize>,
1231    preserve_soft: bool,
1232    media_rows: &HashMap<String, usize>,
1233    reveal: Option<Range<usize>>,
1234    cache: &mut BlockCache,
1235    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
1236) -> VisualMap {
1237    let wrap = wrap.map(|w| w.max(8));
1238
1239    // Wrapping is a function of the width, so a width change makes every cached
1240    // row's wrap wrong: start the cache over.
1241    if cache.wrap != Some(wrap) {
1242        cache.entries.clear();
1243        cache.wrap = Some(wrap);
1244    }
1245    cache.generation = cache.generation.wrapping_add(1);
1246
1247    // Frontmatter (a leading `metadata` block) is document metadata, not prose:
1248    // hidden in the rich view exactly as [`Builder::blocks`] skips it.
1249    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
1250
1251    // The outer builder only accumulates rows/tables and spells block boundaries
1252    // — both a function of the source and `last_off`, never of a node array — so
1253    // it carries an empty `nodes`. Each changed block is rendered by a *fresh*
1254    // builder over that block's subtree.
1255    let mut b = Builder {
1256        nodes: &[],
1257        source,
1258        wrap,
1259        rows: Vec::new(),
1260        tables: Vec::new(),
1261        last_off: 0,
1262        media_rows,
1263        break_glyph: Cell::new(' '),
1264        preserve_soft,
1265        reveal: reveal.clone(),
1266    };
1267
1268    // Record the per-block row decomposition as we go, so a later
1269    // [`build_spliced`] can patch one block without rebuilding the map.
1270    let mut layout_blocks: Vec<BlockLayout> = Vec::with_capacity(blocks.len());
1271    let mut all_shift_safe = true;
1272    for (i, block) in blocks.iter().enumerate() {
1273        let start = block.span.start;
1274        let before_sep = b.rows.len();
1275        if i > 0 {
1276            // This walker has no node arena at all (see the `nodes: &[]` above),
1277            // but a top-level query match carries its kind — the same string
1278            // `BlockClass::from_node_kind` classifies for the whole-arena walk, so
1279            // the incremental and full builds label a boundary identically.
1280            b.emit_separators_before(
1281                start,
1282                &[],
1283                true,
1284                Boundary {
1285                    above: BlockClass::from_node_kind(&blocks[i - 1].kind),
1286                    below: BlockClass::from_node_kind(&block.kind),
1287                },
1288            );
1289        }
1290        let sep_rows = b.rows.len() - before_sep;
1291        let after_sep = b.rows.len();
1292        let bytes = block_bytes(source, &block.span);
1293        let hash = block_hash(bytes);
1294        // How this block meets the reveal line, if at all — part of its cache
1295        // key, since the same bytes render differently on the caret's line.
1296        let rkey = reveal_key(&reveal, &block.span);
1297
1298        // Hit: clone the block's rows shifted to its current offset and restore
1299        // the (shifted) `last_off` so the next separator lands right — no marshal.
1300        // Only shift-safe blocks are ever cached, so a hit is safe by construction.
1301        if let Some(hit) = cache.reuse(hash, bytes, &rkey) {
1302            let delta = start as isize - hit.built_start as isize;
1303            for row in &hit.rows {
1304                b.rows.push(shift_row(row, delta));
1305            }
1306            b.last_off = (hit.last_off as isize + delta) as usize;
1307        } else {
1308            // Miss: marshal just this block's subtree and render it. A subtree is
1309            // self-contained with local ids (root at 0) and absolute spans, so a
1310            // fresh builder over it produces the same rows the whole-arena path
1311            // would. An empty subtree (twig couldn't hand it back) renders nothing.
1312            let subtree = fetch_subtree(block.node_id);
1313            if !subtree.is_empty() {
1314                let mut sub = Builder {
1315                    nodes: &subtree,
1316                    source,
1317                    wrap,
1318                    rows: Vec::new(),
1319                    tables: Vec::new(),
1320                    last_off: 0,
1321                    media_rows,
1322                    break_glyph: Cell::new(' '),
1323                    preserve_soft,
1324                    reveal: reveal.clone(),
1325                };
1326                sub.block(0, &[], &[]);
1327                let last_off = sub.last_off;
1328                // Cache only a block that is table-free AND renders inside its own
1329                // span: those two are the conditions for reuse-by-shift to be
1330                // correct. A block failing either is re-rendered every build (a
1331                // fresh render always matches a fresh whole-document build).
1332                if sub.tables.is_empty() {
1333                    if rows_within(&sub.rows, &block.span) {
1334                        cache.store(hash, bytes, start, sub.rows.clone(), last_off, rkey);
1335                    }
1336                    b.rows.extend(sub.rows);
1337                } else {
1338                    // A table block is never cached; rebase its row-index
1339                    // bookkeeping onto the combined row vector and append.
1340                    let base = b.rows.len();
1341                    for t in &mut sub.tables {
1342                        t.rows_span = (t.rows_span.start + base)..(t.rows_span.end + base);
1343                    }
1344                    b.rows.extend(sub.rows);
1345                    b.tables.extend(sub.tables);
1346                }
1347                b.last_off = last_off;
1348            }
1349        }
1350        let content_rows = b.rows.len() - after_sep;
1351        all_shift_safe &= rows_within(&b.rows[after_sep..], &block.span);
1352        layout_blocks.push(BlockLayout {
1353            span: block.span.clone(),
1354            kind: block.kind.clone(),
1355            sep_rows,
1356            content_rows,
1357        });
1358    }
1359
1360    let before_trailing = b.rows.len();
1361    let hidden_end = hidden_prefix_end(
1362        source,
1363        top.iter()
1364            .filter(|m| m.kind == Kind::Metadata)
1365            .map(|m| m.span.end)
1366            .next_back(),
1367    );
1368    b.emit_trailing_blank_lines(
1369        blocks.last().map_or(BlockClass::Paragraph, |m| {
1370            BlockClass::from_node_kind(&m.kind)
1371        }),
1372        hidden_end,
1373    );
1374    let trailing_rows = b.rows.len() - before_trailing;
1375
1376    // Evict every entry no block reused this build, so the cache tracks the
1377    // current document instead of growing without bound over a session.
1378    let g = cache.generation;
1379    cache.entries.retain(|_, bucket| {
1380        bucket.retain(|e| e.generation == g);
1381        !bucket.is_empty()
1382    });
1383
1384    cache.layout = Layout {
1385        blocks: layout_blocks,
1386        trailing_rows,
1387        built_len: source.len(),
1388        has_tables: !b.tables.is_empty(),
1389        all_shift_safe,
1390        reveal: reveal.clone(),
1391    };
1392
1393    // The first rendered offset is the first non-metadata block's start — the
1394    // analogue of [`first_content_offset`] for the top-level list. With nothing
1395    // but frontmatter it's the end of that frontmatter, and 0 for an empty
1396    // document ([`hidden_prefix_end`]).
1397    let content_start = blocks.first().map_or(hidden_end, |m| m.span.start);
1398    let stops = collect_stops(&b.rows);
1399    label_media_boundaries(&mut b.rows);
1400    let code_blocks = code_block_spans(&b.rows);
1401    let media = media_spans(&b.rows);
1402    let directives = directive_spans(&b.rows);
1403    VisualMap {
1404        rows: b.rows,
1405        content_start,
1406        stops,
1407        tables: b.tables,
1408        code_blocks,
1409        media,
1410        directives,
1411    }
1412}
1413
1414/// The fast path for a single-block edit: patch the previous [`VisualMap`] in
1415/// place rather than reassembling it. Returns `Some(new_map)` when it applies,
1416/// or `None` to tell the caller to fall back to [`build_cached`] (always
1417/// correct). Consumes `prev` either way — on `None` the caller rebuilds from
1418/// scratch and doesn't need it.
1419///
1420/// It applies only when `dirty` (twig's dirty byte range) falls inside exactly
1421/// one top-level block AND the block structure around it is unchanged — verified
1422/// by matching the new `top` list against the previous [`Layout`] block for
1423/// block: kinds unchanged, spans before the edit identical, spans after it
1424/// shifted by the byte delta, count unchanged. Any deviation — a block split or
1425/// merged, a fence opened to swallow later blocks, a table anywhere, a
1426/// multi-block edit — fails the match and returns `None`. That check is what
1427/// makes the byte-range trustworthy: twig's dirty range is exact about *bytes*
1428/// but silent about *reparse*, and the structural match catches the reparse
1429/// effects it can't see.
1430///
1431/// When it applies, the unchanged prefix rows move verbatim, the suffix rows
1432/// shift by the delta *in place* (integer adds, no glyph copy), and only the one
1433/// dirty block is re-marshalled and re-rendered; stops splice the same way by
1434/// offset. So the cost is O(rows after the edit), and nothing before the edit is
1435/// touched. The hash-keyed entry cache is left alone — a later [`build_cached`]
1436/// will miss on the changed block, re-render it, and evict the stale entry, so
1437/// chained splices neither corrupt nor grow it.
1438// One builder, and every one of these is a distinct input to the same layout
1439// pass — a struct of them would be built at the one call site and unpacked
1440// here, which is the same arguments with an extra name in the way.
1441#[allow(clippy::too_many_arguments)]
1442pub fn build_spliced(
1443    prev: VisualMap,
1444    source: &str,
1445    wrap: Option<usize>,
1446    preserve_soft: bool,
1447    top: &[QueryMatch],
1448    dirty: Range<usize>,
1449    media_rows: &HashMap<String, usize>,
1450    reveal: Option<Range<usize>>,
1451    cache: &mut BlockCache,
1452    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
1453) -> Option<VisualMap> {
1454    let wrap = wrap.map(|w| w.max(8));
1455    // A width change invalidates every cached row — a full rebuild's job.
1456    if cache.wrap != Some(wrap) {
1457        return None;
1458    }
1459    // So does a moved reveal line, and for the same reason: this path reuses
1460    // every row outside the dirty block, and those rows encode which line was
1461    // showing its raw markup when they were built. Typing almost always moves
1462    // the caret, so under `MarkupMode::Full` this bails to `build_cached` on
1463    // most keystrokes — still block-cached, so only the edited block and the
1464    // revealed one actually re-render.
1465    if cache.layout.reveal != reveal {
1466        return None;
1467    }
1468    // Take the previous layout; on any bail below the caller rebuilds it (and the
1469    // map) via `build_cached`, so leaving it empty is fine. A table or a block
1470    // that renders outside its span (a degenerate inline span) makes shifting
1471    // unsound, so those force the full-rebuild path.
1472    let prev_layout = std::mem::take(&mut cache.layout);
1473    if prev_layout.built_len == 0 || prev_layout.has_tables || !prev_layout.all_shift_safe {
1474        return None;
1475    }
1476    // The layout addresses `prev` by row index, so it is only usable against the
1477    // map it was built from. A frontend is free to hold the map it was handed and
1478    // present it differently — leaf-ratatui splices blank filler rows under an
1479    // oversized heading so the raster has somewhere to stand — and if one of those
1480    // comes back here the row arithmetic below lands on the wrong rows: the
1481    // re-rendered block is laid over a filler and the rows it really occupied
1482    // survive into the suffix, stranding a stale copy of the edited line and
1483    // pushing everything after it one row down, once per keystroke. A row count
1484    // that doesn't match what this layout describes is the tell, and the honest
1485    // answer is the full rebuild.
1486    let described_rows = prev_layout
1487        .blocks
1488        .iter()
1489        .map(|pl| pl.sep_rows + pl.content_rows)
1490        .sum::<usize>()
1491        + prev_layout.trailing_rows;
1492    if described_rows != prev.rows.len() {
1493        return None;
1494    }
1495
1496    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
1497    if blocks.is_empty() || blocks.len() != prev_layout.blocks.len() {
1498        return None;
1499    }
1500    let delta = source.len() as isize - prev_layout.built_len as isize;
1501
1502    // The single block whose NEW span contains the whole dirty range. A dirty
1503    // range straddling a block boundary (or a separator) finds none → bail.
1504    let k = blocks
1505        .iter()
1506        .position(|m| m.span.start <= dirty.start && dirty.end <= m.span.end)?;
1507
1508    // Structural match: every OTHER block is unchanged — same kind throughout,
1509    // span identical before the edit and shifted by `delta` after it. A mismatch
1510    // means the reparse reshaped the block structure, which only a full rebuild
1511    // renders correctly.
1512    for (i, (m, pl)) in blocks.iter().zip(&prev_layout.blocks).enumerate() {
1513        if m.kind != pl.kind {
1514            return None;
1515        }
1516        if i == k {
1517            continue;
1518        }
1519        let want = if i < k {
1520            pl.span.clone()
1521        } else {
1522            (pl.span.start as isize + delta) as usize..(pl.span.end as isize + delta) as usize
1523        };
1524        if m.span != want {
1525            return None;
1526        }
1527    }
1528    // The dirty block itself: start unchanged (the edit is inside it, past its
1529    // start), end moved by exactly the delta.
1530    let pk_start = prev_layout.blocks[k].span.start;
1531    let pk_end = prev_layout.blocks[k].span.end;
1532    let pk_sep = prev_layout.blocks[k].sep_rows;
1533    let pk_content = prev_layout.blocks[k].content_rows;
1534    if blocks[k].span.start != pk_start || blocks[k].span.end != (pk_end as isize + delta) as usize
1535    {
1536        return None;
1537    }
1538
1539    // Re-render the dirty block from its subtree. A table makes the splice
1540    // bookkeeping unsafe, so bail if one appears.
1541    let subtree = fetch_subtree(blocks[k].node_id);
1542    if subtree.is_empty() {
1543        return None;
1544    }
1545    let mut sub = Builder {
1546        nodes: &subtree,
1547        source,
1548        wrap,
1549        rows: Vec::new(),
1550        tables: Vec::new(),
1551        last_off: 0,
1552        media_rows,
1553        break_glyph: Cell::new(' '),
1554        preserve_soft,
1555        reveal: reveal.clone(),
1556    };
1557    sub.block(0, &[], &[]);
1558    // A table, or content that renders outside the block's span (a degenerate
1559    // inline span), makes the shift bookkeeping unsound — fall back.
1560    if !sub.tables.is_empty() || !rows_within(&sub.rows, &blocks[k].span) {
1561        return None;
1562    }
1563    let new_content = sub.rows;
1564    let new_content_len = new_content.len();
1565    let new_stops = collect_stops(&new_content);
1566
1567    // Row span of the dirty block's CONTENT. Its leading separator stays in the
1568    // prefix: the gap before block k is unchanged, since k's start didn't move.
1569    let content_start_row: usize = prev_layout.blocks[..k]
1570        .iter()
1571        .map(|pl| pl.sep_rows + pl.content_rows)
1572        .sum::<usize>()
1573        + pk_sep;
1574    let content_end_row = content_start_row + pk_content;
1575
1576    // Splice rows: [prefix | new content | suffix + delta]. The prefix moves
1577    // untouched; the suffix shifts in place — integer adds, no glyph copy.
1578    let mut rows = prev.rows;
1579    let mut suffix = rows.split_off(content_end_row);
1580    rows.truncate(content_start_row);
1581    for row in &mut suffix {
1582        shift_row_in_place(row, delta);
1583    }
1584    rows.reserve(new_content_len + suffix.len());
1585    rows.extend(new_content);
1586    rows.extend(suffix);
1587
1588    // Splice stops by offset. The old dirty block covered `[pk_start, pk_end]`:
1589    // prefix stops fall below it, suffix stops above it (shift by delta), the new
1590    // content supplies the middle. The three ranges stay disjoint and ascending,
1591    // so the result needs no re-sort.
1592    let p1 = prev.stops.partition_point(|&s| s < pk_start);
1593    let p2 = prev.stops.partition_point(|&s| s <= pk_end);
1594    let mut stops = Vec::with_capacity(p1 + new_stops.len() + (prev.stops.len() - p2));
1595    stops.extend_from_slice(&prev.stops[..p1]);
1596    stops.extend(new_stops);
1597    for &s in &prev.stops[p2..] {
1598        stops.push((s as isize + delta) as usize);
1599    }
1600
1601    // Record the patched layout for the next splice: spans move to the new
1602    // coordinates, and the dirty block takes its new content-row count.
1603    let mut new_blocks = prev_layout.blocks;
1604    for (pl, m) in new_blocks.iter_mut().zip(&blocks) {
1605        pl.span = m.span.clone();
1606    }
1607    new_blocks[k].content_rows = new_content_len;
1608    cache.layout = Layout {
1609        blocks: new_blocks,
1610        trailing_rows: prev_layout.trailing_rows,
1611        built_len: source.len(),
1612        has_tables: false,
1613        // Every prefix/suffix block was shift-safe last build (we bailed
1614        // otherwise) and the re-rendered block was just checked, so the patched
1615        // document is still entirely shift-safe.
1616        all_shift_safe: true,
1617        reveal,
1618    };
1619
1620    label_media_boundaries(&mut rows);
1621    let code_blocks = code_block_spans(&rows);
1622    let media = media_spans(&rows);
1623    let directives = directive_spans(&rows);
1624    Some(VisualMap {
1625        rows,
1626        content_start: blocks[0].span.start,
1627        stops,
1628        tables: Vec::new(),
1629        code_blocks,
1630        media,
1631        directives,
1632    })
1633}
1634
1635/// A persistent, content-keyed cache of the rows each top-level block renders
1636/// to — the [`VisualMap`] analogue of the GUI's ShapedLine cache, one level
1637/// down. Held by a [`crate::Doc`] and threaded into [`build_cached`], it is what
1638/// makes a rebuild after a keystroke cost "re-render the edited block + shift
1639/// the rest" instead of re-rendering the whole document.
1640///
1641/// A top-level block's rows are a pure function of its source bytes and the wrap
1642/// width, so an unchanged block's rows are cloned and their source offsets
1643/// shifted by the edit's byte delta rather than rebuilt glyph by glyph. Two
1644/// things make that purity hold: at the top level the render prefix is always
1645/// empty (nesting prefixes — a quote gutter, a list indent — exist only *inside*
1646/// a top-level block, within its cached unit), and a block's output never reads
1647/// the incoming `last_off` (it writes `last_off` from its own content before any
1648/// nested separator reads it). So the only thing that differs between two
1649/// positions of an unchanged block is a uniform offset shift. Keyed by a fast
1650/// hash of the block's bytes with the bytes kept for a verify-on-hit — exactly
1651/// the shape cache's weak-hash-then-compare, so a collision costs a re-render,
1652/// never a wrong row.
1653///
1654/// Tables are never cached (a block that emits any table row is always rebuilt):
1655/// their rows are cross-referenced from the map's `tables` side-table by row
1656/// index, which a blind offset-shift wouldn't fix up, and they are rare enough
1657/// that the simplicity beats the reuse.
1658#[derive(Default)]
1659pub struct BlockCache {
1660    /// The wrap width every entry was built at; a change invalidates all of
1661    /// them. `None` before the first build (distinct from `Some(None)`, the
1662    /// unwrapped GUI width).
1663    wrap: Option<Option<usize>>,
1664    /// Bumped once per [`build_cached`]. An entry reused or inserted this build
1665    /// carries the current value; stale entries are dropped at the end of it.
1666    generation: u64,
1667    /// `hash(bytes)` → the block(s) sharing that hash — a bucket because
1668    /// distinct blocks can collide, while two *identical* blocks share one entry
1669    /// (free dedup).
1670    entries: HashMap<u64, Vec<CachedBlock>>,
1671    /// The row/stop decomposition of the last build, which [`build_spliced`]
1672    /// patches in place for a single-block edit. Kept in step with whatever
1673    /// [`VisualMap`] was last produced; empty before the first build.
1674    layout: Layout,
1675}
1676
1677/// How the last build's [`VisualMap`] decomposes into top-level blocks — the
1678/// bookkeeping [`build_spliced`] needs to splice one block's rows and stops
1679/// without rebuilding the whole map. Every field describes the *previous* build,
1680/// in that build's coordinates.
1681#[derive(Default)]
1682struct Layout {
1683    /// One entry per rendered (metadata-filtered) top-level block, in order.
1684    blocks: Vec<BlockLayout>,
1685    /// Trailing blank rows past the last block (from `emit_trailing_blank_lines`).
1686    trailing_rows: usize,
1687    /// The source length this layout was built at — the reference for the edit's
1688    /// byte delta.
1689    built_len: usize,
1690    /// Whether the last build drew any table. A table's cross-referenced row
1691    /// indices don't survive a blind splice, so their presence makes
1692    /// [`build_spliced`] bail to a full rebuild.
1693    has_tables: bool,
1694    /// Whether every block rendered strictly inside its own span (see
1695    /// [`rows_within`]). A block that doesn't — a malformed Markdown inline node
1696    /// that twig leaves with a degenerate `0..0` span renders at a fixed offset
1697    /// outside its block — can't be shifted correctly, so its presence makes
1698    /// [`build_spliced`] bail to a full rebuild.
1699    all_shift_safe: bool,
1700    /// The reveal line this layout was built under (see [`Builder::reveal`]).
1701    /// A splice reuses every row it isn't re-rendering, so a reveal line that
1702    /// has moved would leave the old line still showing its delimiters and the
1703    /// new one still hiding them — [`build_spliced`] bails when this changes.
1704    reveal: Option<Range<usize>>,
1705}
1706
1707/// One top-level block's contribution to the last build: its span and kind (for
1708/// the structural match that proves only one block changed) and how many
1709/// separator and content rows it emitted (to locate its slice of the row
1710/// vector).
1711struct BlockLayout {
1712    span: Range<usize>,
1713    kind: Kind,
1714    sep_rows: usize,
1715    content_rows: usize,
1716}
1717
1718/// One cached block: the rows it rendered to, plus what a reuse at a new
1719/// position needs to shift them. Offsets are stored absolute (as built) and
1720/// shifted by `new_start - built_start` on reuse.
1721struct CachedBlock {
1722    /// The block's exact source bytes, compared on a hash hit so a collision
1723    /// can never hand back another block's rows.
1724    bytes: Box<[u8]>,
1725    /// The offset the rows were built at (the block's `span.start`).
1726    built_start: usize,
1727    /// The block's rows, offsets absolute as built.
1728    rows: Vec<VRow>,
1729    /// `last_off` after this block was emitted, absolute as built — restored
1730    /// (shifted) on reuse so the following separator lands correctly.
1731    last_off: usize,
1732    /// Where the reveal line fell *within this block* when the rows were built,
1733    /// as a block-relative byte range — see [`reveal_key`]. Compared alongside
1734    /// `bytes` on a hit, because identical source renders to different rows
1735    /// depending on whether the caret's line is inside it: the same `*em*`
1736    /// shows its asterisks on the revealed line and hides them everywhere else.
1737    ///
1738    /// Block-relative rather than absolute so an unaffected block still hits
1739    /// after an edit shifts it, and `None` for the overwhelmingly common
1740    /// no-reveal case — which is why an entry stored under `MarkupMode::None`
1741    /// keeps hitting for every block that isn't the caret's.
1742    reveal: Option<Range<usize>>,
1743    /// The build that last reused or inserted this entry (see `generation`).
1744    generation: u64,
1745}
1746
1747/// Where `reveal` falls inside a block, in block-relative bytes — the extra key
1748/// a cached block is stored and matched under.
1749///
1750/// `None` when the block doesn't meet the reveal line at all, which is every
1751/// block on every build in the two hidden modes, and all but one of them under
1752/// [`crate::MarkupMode::Full`]. So the cache keeps its hit rate as the caret
1753/// moves: only the line the caret leaves and the line it arrives at re-render.
1754fn reveal_key(reveal: &Option<Range<usize>>, span: &Range<usize>) -> Option<Range<usize>> {
1755    let r = reveal.as_ref()?;
1756    // The same generous intersection test `Builder::revealed` uses, so a block
1757    // is keyed as revealed exactly when its glyphs will be built that way.
1758    (span.start <= r.end && r.start <= span.end).then(|| {
1759        let start = r.start.max(span.start) - span.start;
1760        let end = r.end.min(span.end) - span.start;
1761        start..end
1762    })
1763}
1764
1765impl BlockCache {
1766    /// Look up a block by hash, verify its bytes and reveal key, and on a hit
1767    /// stamp it used this build and hand back a borrow to shift-and-clone from.
1768    /// `None` on a miss (unknown hash, a collision whose bytes differ, or the
1769    /// same bytes built under a different reveal).
1770    fn reuse(
1771        &mut self,
1772        hash: u64,
1773        bytes: &[u8],
1774        reveal: &Option<Range<usize>>,
1775    ) -> Option<&CachedBlock> {
1776        let g = self.generation;
1777        let bucket = self.entries.get_mut(&hash)?;
1778        let e = bucket
1779            .iter_mut()
1780            .find(|e| &*e.bytes == bytes && &e.reveal == reveal)?;
1781        e.generation = g;
1782        Some(&*e)
1783    }
1784
1785    /// Cache the rows a freshly-rendered block produced (or refresh an existing
1786    /// entry for the same bytes and reveal — an identical block elsewhere, or a
1787    /// re-render).
1788    fn store(
1789        &mut self,
1790        hash: u64,
1791        bytes: &[u8],
1792        built_start: usize,
1793        rows: Vec<VRow>,
1794        last_off: usize,
1795        reveal: Option<Range<usize>>,
1796    ) {
1797        let g = self.generation;
1798        let bucket = self.entries.entry(hash).or_default();
1799        if let Some(e) = bucket
1800            .iter_mut()
1801            .find(|e| &*e.bytes == bytes && e.reveal == reveal)
1802        {
1803            e.built_start = built_start;
1804            e.rows = rows;
1805            e.last_off = last_off;
1806            e.generation = g;
1807        } else {
1808            bucket.push(CachedBlock {
1809                bytes: bytes.into(),
1810                built_start,
1811                rows,
1812                last_off,
1813                reveal,
1814                generation: g,
1815            });
1816        }
1817    }
1818}
1819
1820/// The source bytes a top-level block covers — the block cache's key material.
1821///
1822/// Clamped to the source rather than sliced by the span as twig gives it,
1823/// because that span can end *past* the last byte: the final block of a document
1824/// with no trailing newline is closed on the virtual newline the parser supplies
1825/// at EOF, so its `span.end` is `source.len() + 1`. Slicing by such a range
1826/// yields `None`, and the obvious `unwrap_or(&[])` reads that as *this block has
1827/// no bytes* — the wrong answer twice over.
1828///
1829/// Two blocks whose spans both overrun then key alike, and the second is served
1830/// the first one's rows. That is not hypothetical: a footnote definition is a
1831/// root beside `doc` merged back into the top level by [`top_blocks`], while the
1832/// `section` above it spans the definition's bytes too, so both end at EOF —
1833/// and a document ending in `[^note]: …` renders that definition as a second
1834/// copy of the heading. Even alone, a block that keeps hashing empty as the user
1835/// types in it is served the stale rows built before the edit.
1836///
1837/// Clamping hands back the bytes the block really covers, which tells both cases
1838/// apart, and costs nothing for a span that was in range to begin with.
1839fn block_bytes<'a>(source: &'a str, span: &Range<usize>) -> &'a [u8] {
1840    let bytes = source.as_bytes();
1841    let start = span.start.min(bytes.len());
1842    &bytes[start..span.end.clamp(start, bytes.len())]
1843}
1844
1845/// A fast, allocation-free content hash (FNV-1a) for a block's bytes. Weak by
1846/// design — the bytes are compared on a hit — so its only job is to spread
1847/// blocks across buckets cheaply. SipHash over every block's bytes on every
1848/// keystroke would cost more than it saves, the same lesson the shape cache
1849/// learned when it stopped hashing through the standard hasher.
1850fn block_hash(bytes: &[u8]) -> u64 {
1851    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
1852    for &x in bytes {
1853        h ^= x as u64;
1854        h = h.wrapping_mul(0x0000_0100_0000_01b3);
1855    }
1856    h
1857}
1858
1859/// Clone a cached row with every source offset advanced by `delta` — the whole
1860/// cost of reusing an unchanged block: integer adds where a rebuild would
1861/// re-shape every glyph.
1862fn shift_row(row: &VRow, delta: isize) -> VRow {
1863    let shift = |off: usize| (off as isize + delta) as usize;
1864    VRow {
1865        glyphs: row
1866            .glyphs
1867            .iter()
1868            .map(|g| Glyph {
1869                ch: g.ch,
1870                style: g.style,
1871                src: shift(g.src),
1872                stop: g.stop,
1873            })
1874            .collect(),
1875        end_src: shift(row.end_src),
1876        decoration: row.decoration,
1877        code: row.code,
1878        code_lang: row.code_lang.clone(),
1879        directive: row.directive,
1880        directive_label: row.directive_label.clone(),
1881        media: row.media.clone(),
1882        // A tick, not an offset — reuse carries it as-is, like `code_lang`.
1883        task: row.task,
1884        leaf_directive: row.leaf_directive.clone(),
1885        heading: row.heading,
1886        // Structure, not offsets: a reused block's rows divide the same blocks
1887        // wherever the edit above moved them to.
1888        boundary: row.boundary,
1889    }
1890}
1891
1892/// Advance a row's source offsets by `delta` in place — the suffix half of
1893/// [`build_spliced`], where the rows are already owned and only need shifting,
1894/// not copying.
1895fn shift_row_in_place(row: &mut VRow, delta: isize) {
1896    for g in &mut row.glyphs {
1897        g.src = (g.src as isize + delta) as usize;
1898    }
1899    row.end_src = (row.end_src as isize + delta) as usize;
1900}
1901
1902/// Whether every source offset a block's rows carry falls inside the block's own
1903/// span — the precondition for reusing the block by a uniform offset shift. It
1904/// holds for well-formed blocks (their glyphs and row ends address bytes within
1905/// the block, synthetic glyphs point at the block start). It fails when a node
1906/// renders *outside* its block, which today means a malformed Markdown inline
1907/// node twig leaves with a degenerate `0..0` span: that content lands at a fixed
1908/// offset that doesn't move with the block. Such a block is re-rendered every
1909/// build instead of shifted, so the incremental map still matches a fresh one —
1910/// see [`build_cached`] and [`build_spliced`].
1911fn rows_within(rows: &[VRow], span: &Range<usize>) -> bool {
1912    rows.iter().all(|r| {
1913        r.end_src >= span.start
1914            && r.end_src <= span.end
1915            && r.glyphs
1916                .iter()
1917                .all(|g| g.src >= span.start && g.src <= span.end)
1918    })
1919}
1920
1921/// Where the rendered document begins when a leading `metadata` block is all
1922/// there is — the end of that hidden frontmatter, past the newline that closes
1923/// its last line so the floor sits at the start of the (empty) body rather than
1924/// on the closing `---`.
1925///
1926/// With a real block after it the frontmatter's end is never needed: the floor
1927/// is that block's start, and the rows begin there. With nothing after it, both
1928/// the caret floor and the trailing-blank-line count would otherwise fall back
1929/// to offset 0 — inside the hidden frontmatter — which put the caret *before*
1930/// the metadata and made typing land ahead of the opening `---`.
1931fn hidden_prefix_end(source: &str, meta_end: Option<usize>) -> usize {
1932    let Some(end) = meta_end else { return 0 };
1933    let end = end.min(source.len());
1934    let rest = &source[end..];
1935    if rest.starts_with("\r\n") {
1936        end + 2
1937    } else if rest.starts_with('\n') {
1938        end + 1
1939    } else {
1940        end
1941    }
1942}
1943
1944/// The end of the document's hidden frontmatter: the last `metadata` child of
1945/// `doc`, which is what [`top_level`] and [`Builder::blocks`] drop. `None` when
1946/// there is none.
1947fn metadata_end_of(nodes: &[FlatNode], doc: usize) -> Option<usize> {
1948    let mut end = None;
1949    let mut child = nodes[doc].first_child;
1950    while let Some(cid) = child {
1951        let n = &nodes[cid.0 as usize];
1952        if n.kind == Kind::Metadata {
1953            end = Some(n.span.end);
1954        }
1955        child = n.next_sibling;
1956    }
1957    end
1958}
1959
1960/// The document's rendered top-level blocks, as node indices in source order.
1961///
1962/// Not simply `doc`'s children, for two reasons. Frontmatter (a leading
1963/// `metadata` block) is document metadata rather than prose and is dropped, the
1964/// way [`Builder::blocks`] drops it. And a **footnote definition** (`[^1]: …`)
1965/// is not a child of `doc` at all: twig parses it as a root of its own, a
1966/// *sibling* of the document node with `parent == None`. A walk that starts at
1967/// `doc` therefore never reaches one, which is why a definition — and every
1968/// byte of its body — used to render as nothing at all. Merging the roots back
1969/// in by `span.start` puts each definition on screen exactly where it was
1970/// written, which is what keeps rows, stops, and offsets monotonic.
1971///
1972/// Only `footnote` roots are merged. twig also leaves stray orphan `str` nodes
1973/// parented to nothing (the `*` of an emphasis run, for one); those are already
1974/// rendered as part of the subtree that owns their bytes, and re-emitting them
1975/// here would double them.
1976fn top_level(nodes: &[FlatNode], doc: usize) -> Vec<usize> {
1977    let mut out = Vec::new();
1978    let mut child = nodes[doc].first_child;
1979    while let Some(cid) = child {
1980        let n = &nodes[cid.0 as usize];
1981        if n.kind != Kind::Metadata {
1982            out.push(cid.0 as usize);
1983        }
1984        child = n.next_sibling;
1985    }
1986    out.extend(
1987        nodes
1988            .iter()
1989            .enumerate()
1990            .filter(|(_, n)| n.kind == Kind::Footnote && n.parent.is_none())
1991            .map(|(i, _)| i),
1992    );
1993    out.sort_by_key(|&i| nodes[i].span.start);
1994    out
1995}
1996
1997/// The top-level blocks to hand [`build_cached`] / [`build_spliced`] — the
1998/// incremental path's twin of [`top_level`], which the two must agree with block
1999/// for block or the render paths diverge.
2000///
2001/// `child_spans(None)` gives `doc`'s children, which is all of them for an
2002/// ordinary document. A **footnote definition** is not one: twig parses `[^1]: …`
2003/// as a root beside `doc` with no parent, and indexes it at no offset either —
2004/// `node_at` inside its bytes answers `doc`, and a `query("footnote")` selector
2005/// finds nothing. Leaf used to discover them by marshalling the whole arena with
2006/// `nodes()` — the very cost the incremental path exists to avoid — behind a
2007/// byte-scan gate that gave documents with no `[^…]:` line a substring search
2008/// instead. twig 3.0's `definitions()` asks the library the question directly,
2009/// so both the marshal and the gate are gone.
2010///
2011/// Filtered to [`Kind::Footnote`]: `definitions()` also reports the *link*
2012/// reference definitions (`[foo]: /url`), which leaf has never rendered as
2013/// blocks and which are not this change's business to start rendering.
2014///
2015/// This is the one part of the render that needs an [`Editor`] rather than a
2016/// marshalled node array. The builders themselves stay editor-free; this only
2017/// prepares their input.
2018pub(crate) fn top_blocks(editor: &mut Editor) -> Vec<QueryMatch> {
2019    let mut top = editor.child_spans(None).unwrap_or_default();
2020    let notes = footnote_definitions(editor);
2021    if notes.is_empty() {
2022        return top;
2023    }
2024    top.extend(notes);
2025    // Source order — what every offset-keyed thing downstream (rows, stops, the
2026    // splice path's block-for-block match) is built to assume.
2027    top.sort_by_key(|m| m.span.start);
2028    top
2029}
2030
2031/// Every `[^label]: …` definition in the document, in whatever order twig
2032/// reports them.
2033///
2034/// Filtered to [`Kind::Footnote`]: `definitions()` also reports the *link*
2035/// reference definitions (`[foo]: /url`), which leaf has never rendered as
2036/// blocks and which are not this function's business.
2037///
2038/// Empty when the document can't be walked, which leaves [`top_blocks`] with
2039/// the ordinary top-level children and [`crate::Doc::footnote_at_caret`] with an
2040/// undefined reference — in both cases the same answer as a document that has
2041/// no definitions, which is the right way to degrade.
2042pub(crate) fn footnote_definitions(editor: &mut Editor) -> Vec<QueryMatch> {
2043    let Ok(mut doc) = editor.document() else {
2044        return Vec::new();
2045    };
2046    doc.definitions()
2047        .unwrap_or_default()
2048        .into_iter()
2049        .filter(|m| m.kind == Kind::Footnote)
2050        .collect()
2051}
2052
2053/// The label of the footnote definition starting at `start` — the `1` in
2054/// `[^1]: …`. twig gives the `footnote` node no label of its own (no `text`, no
2055/// `name`), and the bytes that spell it belong to no child node either — the
2056/// body `para` starts its *content* past them — so the source is the only place
2057/// to read it from. `None` when what's there isn't a definition after all.
2058pub(crate) fn footnote_label(source: &str, start: usize) -> Option<&str> {
2059    let rest = source.get(start..)?.strip_prefix("[^")?;
2060    let end = rest.find("]:")?;
2061    Some(&rest[..end])
2062}
2063
2064/// Where the body of the footnote definition spanning `span` sits in `source` —
2065/// everything past the `[^1]:` marker, which is the part a reader actually wants
2066/// when they follow a reference.
2067///
2068/// Source bytes, verbatim but for the whitespace trimmed off each end: a note
2069/// that says `see *later*` answers with the asterisks in. Rendering that body is
2070/// a frontend's business the same way painting a [`Role`] is, and a caller that
2071/// wants it laid out already has the definition on screen where it was written.
2072///
2073/// The trim is what makes the common case read right — `[^1]: text` has a space
2074/// after the colon that belongs to the marker, not the note, and a definition's
2075/// span runs to the newline ending it.
2076///
2077/// The span is taken at its word, which it has only been safe to do since twig
2078/// 3.1: a djot definition's span used to run *past* its own last line, through
2079/// the blank line separating it from the next block and into that block's first
2080/// byte, so `[^2a]: a note.` came back as `"a note.\n\n["` and the offsets named
2081/// the following note's rows as well as this one's — a reader asking about one
2082/// footnote was shown two. leaf measured the body itself to get around that, and
2083/// paid for it: the scan stopped at the first blank line, so a note with a second
2084/// indented paragraph lost it. Both halves go away with the fix, since a blank
2085/// line *inside* a definition was always interior to the span and still is.
2086///
2087/// A range rather than a slice because "go to note" needs the *position* as much
2088/// as the text, and it needs the position of the body specifically: a
2089/// definition's `[^1]:` marker is decoration the caret can't occupy (the rich
2090/// view draws it as `[1] ` and gives it no stop), so aiming a caret at the
2091/// definition's first byte lands it on the nearest real stop instead — which is
2092/// up in the paragraph *above* the note. The body's first byte is a stop, and is
2093/// where a reader following a reference wants to arrive anyway.
2094pub(crate) fn footnote_body_span(source: &str, span: Range<usize>) -> Option<Range<usize>> {
2095    let rest = source.get(span.clone())?.strip_prefix("[^")?;
2096    let marker = rest.find("]:")?;
2097    // `span.start` + `[^` + the label + `]:`.
2098    let after_marker = span.start + 2 + marker + 2;
2099    let raw = source.get(after_marker..span.end)?;
2100    // Written as a start plus a length so an all-whitespace body lands on an
2101    // empty range at the end rather than an inverted one.
2102    let start = after_marker + (raw.len() - raw.trim_start().len());
2103    Some(start..start + raw.trim().len())
2104}
2105
2106/// The label of the footnote *reference* spanning `span` — the `1` in `[^1]`.
2107///
2108/// The peer of [`footnote_label`] for the other half of the pair, and needed for
2109/// the same reason: a reference whose node carries neither a `content_span` nor
2110/// a `text` still spells its label plainly in the source. `None` when the bytes
2111/// aren't a reference after all.
2112pub(crate) fn footnote_reference_label(source: &str, span: Range<usize>) -> Option<&str> {
2113    let rest = source.get(span)?.strip_prefix("[^")?;
2114    let end = rest.find(']')?;
2115    Some(&rest[..end])
2116}
2117
2118/// Where a heading's *content* starts — past the `#`s and the space the rich
2119/// view hides, for an ATX heading; the block's own start for a setext one (which
2120/// has no leading marker) and for a format that spells headings some other way.
2121///
2122/// Only an empty heading needs asking: with any content at all, the row ends on
2123/// its last glyph. Bounded to the heading's own first line so a marker-less
2124/// heading can't scan into the text under it.
2125fn heading_content_start(source: &str, span: &Range<usize>) -> usize {
2126    let end = span.end.min(source.len());
2127    let Some(line) = source.get(span.start..end) else {
2128        return span.start;
2129    };
2130    let line = line.split('\n').next().unwrap_or("");
2131    let hashes = line.len() - line.trim_start_matches('#').len();
2132    if hashes == 0 {
2133        return span.start;
2134    }
2135    let after = &line[hashes..];
2136    span.start + hashes + (after.len() - after.trim_start_matches([' ', '\t']).len())
2137}
2138
2139struct Builder<'a> {
2140    nodes: &'a [FlatNode],
2141    /// The document source, consulted to place blank-line rows at the source
2142    /// offsets the caret should occupy on them (the AST drops blank lines).
2143    source: &'a str,
2144    /// The word-wrap column budget, or `None` to emit each block as a single
2145    /// unwrapped row (the frontend wraps).
2146    wrap: Option<usize>,
2147    rows: Vec<VRow>,
2148    /// Built alongside `rows`, never instead of them — see [`TableInfo`].
2149    tables: Vec<TableInfo>,
2150    /// The end offset of the last content emitted — the anchor for blank
2151    /// separator rows so the caret never snaps onto one.
2152    last_off: usize,
2153    /// How many rows each block image reserves, keyed by its destination — the
2154    /// frontend's per-image height, threaded in from [`crate::Doc::set_media_rows`]
2155    /// so [`Builder::block_media`] can size the placeholder without core doing any
2156    /// I/O. A destination absent from the map (or a `0`/`1` entry) reserves the
2157    /// bare one-row placeholder, which is the whole-document default and what
2158    /// every existing test — passing an empty map — still gets.
2159    media_rows: &'a HashMap<String, usize>,
2160    /// The glyph a hard break renders as while the current inline run is built:
2161    /// a space in prose (a break folds into the flow the frontend wraps), but a
2162    /// newline (`\n`) inside a table cell, where a row is one source line and the
2163    /// only break it can carry is an explicit one that must show as a line of its
2164    /// own. Set around [`Builder::row_cells`] and otherwise left at `' '`.
2165    break_glyph: Cell<char>,
2166    /// Render a soft break (a bare newline inside a paragraph) as a line break
2167    /// where it was written, rather than folding it into the reflowed paragraph
2168    /// — the `LineFlow::Preserve` behaviour. A soft break emits a `'\n'` glyph
2169    /// (like a hard break in a cell), which [`Builder::emit_wrapped`] turns into
2170    /// a fresh visual row. `false` is the flowing-prose default. Inside a table
2171    /// cell (where `break_glyph` is already `'\n'`) it has no effect: a cell is
2172    /// one line and folds its own soft breaks regardless.
2173    preserve_soft: bool,
2174    /// The source byte range of the one line that should render its markup
2175    /// *raw* — the caret's line under `MarkupMode::Full` (see
2176    /// [`crate::Doc::reveal_line`]). `None` in every other mode and view, which
2177    /// is the delimiters-always-hidden behaviour every build had before the
2178    /// preference existed.
2179    ///
2180    /// Read only by [`Builder::revealed`], which every delimiter-bearing arm of
2181    /// [`Builder::inline`] consults. A range rather than a bare caret offset
2182    /// because the decision is per-*node*, not per-caret: a node is revealed
2183    /// when its span meets this line, so `*em*` shows both its asterisks even
2184    /// with the caret at one end of it.
2185    reveal: Option<Range<usize>>,
2186}
2187
2188impl Builder<'_> {
2189    /// Whether `span` belongs to the line that is showing its raw markup. True
2190    /// only when a reveal line is set (`MarkupMode::Full`) and the two ranges
2191    /// actually meet.
2192    ///
2193    /// Touching at an endpoint counts: an emphasis ending exactly where the line
2194    /// does is on that line, and a zero-length reveal range (the caret alone on
2195    /// a blank line) still meets a node that starts there. The test is
2196    /// deliberately generous — the failure it avoids is revealing one delimiter
2197    /// of a pair while hiding the other, which looks like corruption rather than
2198    /// like markup.
2199    fn revealed(&self, span: &Range<usize>) -> bool {
2200        self.reveal
2201            .as_ref()
2202            .is_some_and(|r| span.start <= r.end && r.start <= span.end)
2203    }
2204
2205    /// The `(opening, closing)` source byte ranges of a node's delimiters — the
2206    /// bytes its `span` holds that its `content_span` doesn't.
2207    ///
2208    /// This is how *every* inline delimiter is recovered, rather than a table of
2209    /// spellings per kind: twig gives `*em*` a span of `13..17` and a content
2210    /// span of `14..16`, so the gaps at each end are the delimiters, whatever
2211    /// they happen to be. That matters because one kind has many spellings —
2212    /// `*em*` and `_em_` are both emphasis, `` `x` `` and ``` ``x`` ``` both
2213    /// verbatim — and re-deriving the text from the source is the only way to
2214    /// show back what the author actually typed. It also gets a link's
2215    /// asymmetric `[` / `](dest)` right for free.
2216    ///
2217    /// `None` when the node has no content span, or when content and span
2218    /// coincide (nothing was elided, so there is nothing to reveal).
2219    fn delims(&self, id: usize) -> Option<(Range<usize>, Range<usize>)> {
2220        let node = &self.nodes[id];
2221        let content = node.content_span.clone()?;
2222        let span = node.span.clone();
2223        // A content span that escapes its own node's span means the two are
2224        // describing different things; reveal nothing rather than slice wildly.
2225        if content.start < span.start || content.end > span.end {
2226            return None;
2227        }
2228        let (open, close) = (span.start..content.start, content.end..span.end);
2229        // A delimiter that spans a newline isn't this line's to reveal — a setext
2230        // heading's `\n=====` underline is the case that arises in practice. It
2231        // would also inject a `'\n'` glyph, which `emit_wrapped` reads as a hard
2232        // row break, so the row would split where the author wrote no break.
2233        let multiline =
2234            |r: &Range<usize>| self.source.get(r.clone()).is_some_and(|s| s.contains('\n'));
2235        if multiline(&open) || multiline(&close) {
2236            return None;
2237        }
2238        (!open.is_empty() || !close.is_empty()).then_some((open, close))
2239    }
2240
2241    /// Emit the source bytes of `range` as revealed markup — real glyphs, each
2242    /// mapped to its own source byte and each a caret stop, so a delimiter shown
2243    /// is a delimiter that can be selected, edited and deleted like any other
2244    /// text. Styled [`Role::Delimiter`] on top of the run's own style, which is
2245    /// how a frontend tells scaffolding from prose and dims it.
2246    ///
2247    /// Deliberately *not* [`push_escaped_text`]: this is raw source, not parsed
2248    /// text, so there is no escape-driven drift between the two to correct.
2249    fn push_delim(&self, out: &mut Vec<Glyph>, range: &Range<usize>, base: Style) {
2250        let Some(text) = self.source.get(range.clone()) else {
2251            return;
2252        };
2253        push_text(out, text, range.start, base.role(Role::Delimiter));
2254    }
2255
2256    /// Render an inline node's children wrapped in its raw delimiters when the
2257    /// node is on the revealed line, and bare (delimiters resolved away) when it
2258    /// isn't — the shared body of every delimiter-bearing arm of
2259    /// [`inline`](Self::inline).
2260    ///
2261    /// `style` is the resolved styling the content still gets in *both* modes:
2262    /// revealing `*em*` shows the asterisks *and* keeps the text italic, the
2263    /// live-preview behaviour. Showing the markup is not the same as turning the
2264    /// rendering off — that is what [`crate::View::Source`] is for.
2265    fn inline_delimited(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
2266        let show = self
2267            .revealed(&self.nodes[id].span)
2268            .then(|| self.delims(id))
2269            .flatten();
2270        if let Some((open, _)) = &show {
2271            self.push_delim(out, open, style);
2272        }
2273        self.recurse(id, style, out);
2274        if let Some((_, close)) = &show {
2275            self.push_delim(out, close, style);
2276        }
2277    }
2278
2279    fn children(&self, id: usize) -> Vec<usize> {
2280        let mut out = Vec::new();
2281        let mut c = self.nodes[id].first_child;
2282        while let Some(cid) = c {
2283            out.push(cid.0 as usize);
2284            c = self.nodes[cid.0 as usize].next_sibling;
2285        }
2286        out
2287    }
2288
2289    /// Render a node's block children, a blank separator between each. `tight`
2290    /// suppresses the *fabricated* separator between adjacent children that share
2291    /// a source line boundary — a tight list item and the sub-list nested in it —
2292    /// while a real blank source line between them still opens a gap.
2293    fn blocks(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph], tight: bool) {
2294        // Frontmatter (a leading `metadata` block) is document metadata, not
2295        // prose: hide it entirely in the rich-text view. Skipping it here means
2296        // no phantom blank rows for its lines and no separator before the first
2297        // real block — the document opens straight into its content.
2298        let kids: Vec<usize> = self
2299            .children(id)
2300            .into_iter()
2301            .filter(|&c| self.nodes[c].kind != Kind::Metadata)
2302            .collect();
2303        let mut above: Option<BlockClass> = None;
2304        for (i, child) in kids.into_iter().enumerate() {
2305            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
2306            if let Some(above) = above {
2307                self.emit_separators_before(
2308                    self.nodes[child].span.start,
2309                    pc,
2310                    !tight,
2311                    Boundary { above, below },
2312                );
2313            }
2314            let first = if i == 0 { pf } else { pc };
2315            self.block(child, first, pc);
2316            above = Some(below);
2317        }
2318    }
2319
2320    /// Render an explicit, ordered list of top-level blocks — [`Builder::blocks`]
2321    /// for a walk that isn't "the children of one node". The document's top level
2322    /// no longer is: a footnote definition is a root beside `doc`, not under it,
2323    /// and [`top_level`] merges it into this list by source position.
2324    ///
2325    /// The separator between blocks is spelled by the same
2326    /// [`Builder::emit_separators_before`] the incremental top-level walk in
2327    /// [`build_cached`] uses, so the two paths can't drift on how a boundary
2328    /// looks.
2329    fn top_blocks(&mut self, ids: &[usize]) {
2330        for (i, &child) in ids.iter().enumerate() {
2331            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
2332            if i > 0 {
2333                let above = BlockClass::from_node_kind(&self.nodes[ids[i - 1]].kind);
2334                self.emit_separators_before(
2335                    self.nodes[child].span.start,
2336                    &[],
2337                    true,
2338                    Boundary { above, below },
2339                );
2340            }
2341            self.block(child, &[], &[]);
2342        }
2343    }
2344
2345    /// Emit the blank separator row(s) that sit between a block ending at the
2346    /// current `last_off` and the next block starting at `next_start`, wearing
2347    /// the continuation prefix `pc`. Shared by [`Builder::blocks`] and the
2348    /// incremental top-level walk so the two can't drift on how a boundary is
2349    /// spelled.
2350    ///
2351    /// The blank line(s) between two blocks are real caret stops, each needing
2352    /// its *own* source offset — one strictly past the previous block's content,
2353    /// else it collides with that block's last row and `pos_of_offset`
2354    /// (first-match-wins) would resolve the caret onto the wrong row, pinning
2355    /// downward motion there.
2356    ///
2357    /// One row *per* blank source line, not a single collapsed separator: an
2358    /// empty paragraph opened between two blocks (Enter in the gap,
2359    /// `…\n\n\n\n…`) must be a navigable empty row, not vanish — else the caret
2360    /// in it snaps onto the *next* block's start and Enter looks like it did
2361    /// nothing.
2362    fn emit_separators_before(
2363        &mut self,
2364        next_start: usize,
2365        pc: &[Glyph],
2366        synthetic: bool,
2367        boundary: Boundary,
2368    ) {
2369        let mut offs = self.blank_rows_between(self.last_off, next_start);
2370        if offs.is_empty() {
2371            if !synthetic {
2372                // A tight list item's own text sits directly above the sub-list
2373                // nested in it — no fabricated gap. The "breathe" row belongs
2374                // between free-standing blocks, not between an item and its
2375                // child list, which the source writes on the very next line. A
2376                // real blank source line (a loose list) still lands a gap below,
2377                // because `blank_rows_between` found it and we never reach here.
2378                return;
2379            }
2380            // A tight gap with no blank line (e.g. a heading directly above its
2381            // text): keep the one conventional separator row so blocks still
2382            // breathe, as they always have.
2383            offs.push(self.blank_line_offset(self.last_off, next_start));
2384        }
2385        let last = offs.len() - 1;
2386        for (k, end_src) in offs.into_iter().enumerate() {
2387            // Only the drawn-only rows carry the boundary: the navigable blank
2388            // lines between them (and every blank line under preserve-soft flow)
2389            // are somewhere text can go, not a gap between blocks, and a frontend
2390            // that shrank one would be shrinking a line the author is typing on.
2391            let drawn = !self.preserve_soft && (k == 0 || k == last);
2392            // The blank line a boundary is *drawn* with isn't a place text can
2393            // go. The first one closes the block above and the last one opens the
2394            // block below — with a single blank line, the usual case, doing both
2395            // at once. Typing on either just continues the paragraph it abuts,
2396            // since the blank line it would need to be a paragraph of its own is
2397            // the very line being typed on. So they're a gap, like a table's
2398            // border: drawn, clickable, never a caret's home.
2399            //
2400            // The lines *between* them are the real ones. That's what Enter
2401            // opens: it inserts a paragraph break (`\n\n`), which leaves a blank
2402            // line spare on each side and the caret on the navigable line
2403            // between them.
2404            //
2405            // Preserve flow is the exception: there a bare `\n` is a visible line
2406            // break the author edits directly, so a lone blank line *is* a caret
2407            // home — typing on it makes the soft break the mode exists to show,
2408            // and Enter at a line's end lands the caret on exactly this row. So no
2409            // separator is drawn-only; every blank line is navigable.
2410            self.rows.push(VRow {
2411                glyphs: pc.to_vec(),
2412                end_src,
2413                decoration: drawn,
2414                code: false,
2415                code_lang: None,
2416                directive: false,
2417                directive_label: None,
2418                media: None,
2419                task: None,
2420                leaf_directive: None,
2421                heading: None,
2422                boundary: drawn.then_some(boundary),
2423            });
2424        }
2425    }
2426
2427    fn block(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
2428        let node = &self.nodes[id];
2429        match node.kind.as_str() {
2430            "doc" | "section" => self.blocks(id, pf, pc, false),
2431            "heading" => {
2432                // A heading whose only visible content is a single image — a
2433                // banner set in an `<h1>` (`<h1><picture><img></picture></h1>`),
2434                // or `# ![](banner.png)` — is a block picture, not text. Render
2435                // it as one; anything with real heading text falls through.
2436                if let Some((m, kind)) = self.media_only(id) {
2437                    self.block_media(m, kind, id, pf);
2438                    return;
2439                }
2440                let level = node.level.unwrap_or(1);
2441                let style = heading_style(level);
2442                let mut glyphs = Vec::new();
2443                // On the revealed line the `# ` comes back as real, editable
2444                // text in front of the heading. Only the opening marker: a
2445                // closing `#`-run (`## title ##`) is covered by the same
2446                // `delims` pair, and a setext underline is excluded there for
2447                // being on another line entirely.
2448                if let Some((open, close)) =
2449                    self.revealed(&node.span).then(|| self.delims(id)).flatten()
2450                {
2451                    self.push_delim(&mut glyphs, &open, style);
2452                    glyphs.extend(self.inline_children_with_trailing(id, style));
2453                    self.push_delim(&mut glyphs, &close, style);
2454                } else {
2455                    glyphs = self.inline_children_with_trailing(id, style);
2456                }
2457                // An *empty* heading — `# ` with nothing typed after it, which is
2458                // what the toolbar's H1 leaves on a blank line — has no glyph for
2459                // its row to end on, so the fallback below is the row's whole
2460                // extent: its only caret stop, and the offset every row after it
2461                // is measured from. The block's start is the wrong answer for
2462                // both, because it sits *in front of* the `# ` the rich view
2463                // hides: the caret drew (and typed) before the hashes, and the
2464                // rows below inherited an offset short by the marker's length,
2465                // which put the caret on one of them the moment the heading grew
2466                // text. Its content's start is where the caret belongs.
2467                let home = heading_content_start(self.source, &node.span);
2468                let first = self.rows.len();
2469                self.emit_wrapped(glyphs, home, pf, pc);
2470                // Stamp the level on every row the heading just emitted — a
2471                // wrapped heading's continuation rows as much as its first, and
2472                // an empty one's single glyphless row, which is the whole point
2473                // (see [`VRow::heading`]).
2474                for row in &mut self.rows[first..] {
2475                    row.heading = Some(level.min(255) as u8);
2476                }
2477            }
2478            "block_quote" => {
2479                let (start, end) = (node.span.start, node.span.end);
2480                let gutter = synth("│ ", Role::QuoteGutter, start);
2481                let f = concat(pf, &gutter);
2482                let c = concat(pc, &gutter);
2483                // A childless quote — a bare `> ` on an otherwise blank line,
2484                // which is what the toolbar's Quote button leaves there — has no
2485                // inner block to carry the gutter or a caret home, so `blocks`
2486                // emitted *nothing at all*: the quote didn't merely draw
2487                // unstyled, it disappeared, and a document that was only `> `
2488                // rendered zero rows with the caret nowhere to stand. Emit the
2489                // gutter row itself, ending just past the marker, exactly as an
2490                // empty `list_item` emits its bare bullet.
2491                if self.children(id).is_empty() {
2492                    self.push_row_at(f, end.min(self.source.len()));
2493                } else {
2494                    self.blocks(id, &f, &c, false);
2495                    self.emit_quote_trailing_lines(&c, end);
2496                }
2497            }
2498            // A generic `:::name{.class}` fenced-div container (twig's
2499            // `directive`, container form). Core is agnostic of `name` — it's
2500            // the host app's vocabulary (diaryx's `vis` for audience
2501            // visibility, say) and isn't available here regardless: twig only
2502            // threads an `element`'s tag name through `FlatNode::name`, not a
2503            // directive's own identifier. Every row gets marked `directive` (a
2504            // frontend draws a tinted panel around each maximal run, the
2505            // `code`/`code_block` recipe) and the first row carries a label —
2506            // the way a code fence's language rides only its first row.
2507            //
2508            // The label reads BOTH attribute conventions diaryx content
2509            // actually uses: twig's own dot-prefixed classes (`{.public
2510            // .family}`, one combined `class` attr) and bare pandoc-style
2511            // words with no leading dot (`{public family}` — the syntax
2512            // `diaryx_core::visibility`'s hand-rolled publish-time filter and
2513            // apps/web's directive serializer both write; twig parses each
2514            // bare word as its own attribute with an empty value, per
2515            // `languages/markdown/attributes.zig`). Reading only `.class`
2516            // would leave every *existing* diaryx `:::vis{...}` block
2517            // unlabeled.
2518            // Only the *container* form is the panel below. A `text` directive
2519            // is inline and never reaches the block walker (see `is_inline`); a
2520            // `leaf` one is a standalone block with no body, drawn as a
2521            // placeholder the way an image is.
2522            "container"
2523                if container_is_directive(node)
2524                    && node.directive_form == Some(DirectiveForm::Leaf) =>
2525            {
2526                self.block_directive(id, pf);
2527            }
2528            "container" if container_is_directive(node) => {
2529                let label = directive_attr_label(&node.attrs);
2530                let start_row = self.rows.len();
2531                self.blocks(id, pf, pc, false);
2532                for (i, row) in self.rows[start_row..].iter_mut().enumerate() {
2533                    row.directive = true;
2534                    if i == 0 {
2535                        row.directive_label = label.clone();
2536                    }
2537                }
2538                // Anchor the block's end past its closing `:::` fence, exactly as
2539                // the code-block arm anchors past its ```` ``` ````. A container's
2540                // last content row ends at its last *child*, before the fence and
2541                // the blank line under it, so the separator logic counted the
2542                // fence line as a blank row of its own and drew a second boundary
2543                // — one gap's worth of margin twice, under every fenced div.
2544                self.last_off = node.span.end;
2545            }
2546            "bullet_list" | "ordered_list" | "task_list" => {
2547                let ordered = node.kind == Kind::OrderedList;
2548                let mut item_no = 0usize;
2549                let kids = self.children(id);
2550                for (i, child) in kids.iter().copied().enumerate() {
2551                    let kind = &self.nodes[child].kind;
2552                    if *kind == Kind::ListItem || *kind == Kind::TaskListItem {
2553                        let start = self.nodes[child].span.start;
2554                        item_no += 1;
2555                        // A task item's box replaces the bullet rather than
2556                        // joining it. The `[ ] ` that spells it is markup twig
2557                        // has already consumed — the item's paragraph *content*
2558                        // starts past it — so without a drawn box a task item
2559                        // was indistinguishable from a plain bullet, ticked or
2560                        // not. `☐`/`☑` is the marker for the same reason `•` is:
2561                        // it stands where the source's own marker stands. Which
2562                        // way it faces is `checked`, straight off the node.
2563                        let checked = self.nodes[child].checked;
2564                        let marker = match (checked, ordered) {
2565                            (Some(true), _) => "☑ ".to_string(),
2566                            (Some(false), _) => "☐ ".to_string(),
2567                            (None, true) => format!("{item_no}. "),
2568                            (None, false) => "• ".to_string(),
2569                        };
2570                        let bullet = synth(&marker, Role::ListMarker, start);
2571                        let indent = synth(&" ".repeat(text_width(&marker)), Role::Body, start);
2572                        let first_row = self.rows.len();
2573                        self.block(child, &concat(pc, &bullet), &concat(pc, &indent));
2574                        // On the item's first row, the way `code_lang` rides the
2575                        // first row of its block.
2576                        if let (Some(c), Some(row)) = (checked, self.rows.get_mut(first_row)) {
2577                            row.task = Some(c);
2578                        }
2579                    } else {
2580                        // twig can nest a *following* top-level block as a direct
2581                        // child of the list rather than a sibling of it — e.g.
2582                        // `- item\n\n> quote` parses the block quote under the
2583                        // `bullet_list`. It isn't a list item, so render it de-nested:
2584                        // no bullet, at the list's own prefix, with the usual block
2585                        // separator — never `• │ quote`.
2586                        if i > 0 {
2587                            self.emit_separators_before(
2588                                self.nodes[child].span.start,
2589                                pc,
2590                                true,
2591                                Boundary {
2592                                    above: BlockClass::from_node_kind(
2593                                        &self.nodes[kids[i - 1]].kind,
2594                                    ),
2595                                    below: BlockClass::from_node_kind(&self.nodes[child].kind),
2596                                },
2597                            );
2598                        }
2599                        self.block(child, pc, pc);
2600                    }
2601                }
2602            }
2603            "list_item" | "task_list_item" => {
2604                // A childless item — the empty bullet you get the instant you
2605                // press Enter to open a new one — has no inner block to carry the
2606                // marker prefix or a caret home, so `blocks` would emit nothing
2607                // and the new bullet simply wouldn't appear until something was
2608                // typed into it. Emit the prefixed row itself, ending at a caret
2609                // stop just past the marker (the item's `span.end`), the way an
2610                // empty paragraph emits its one prefixed row via `emit_wrapped`.
2611                if self.children(id).is_empty() {
2612                    let home = self.nodes[id].span.end.min(self.source.len());
2613                    self.push_row_at(pf.to_vec(), home);
2614                } else {
2615                    // Tight: an item's text and the list nested under it butt
2616                    // together (`• a` / `  • b`), no fabricated blank row between —
2617                    // a loose item's real blank line still parts them.
2618                    self.blocks(id, pf, pc, true);
2619                }
2620            }
2621            // A footnote *definition* (`[^1]: the note`). It reaches this walker
2622            // only because [`top_level`] merges it back in — twig hangs it off no
2623            // parent at all, so a walk from `doc` never sees one and every byte
2624            // of its body used to render as nothing.
2625            //
2626            // Drawn as a hanging-indent item, the way a list item is: the marker
2627            // reads `[1] `, matching the `[1]` its references render as, so the
2628            // two can be paired by eye, and the body wraps under it. The marker
2629            // is synthetic decoration (one shared offset, never a caret stop) —
2630            // the `[^1]: ` that spells it in the source is markup, hidden like a
2631            // heading's `# `.
2632            "footnote" => {
2633                let (start, end) = (node.span.start, node.span.end);
2634                let source = self.source;
2635                let marker = format!("[{}] ", footnote_label(source, start).unwrap_or(""));
2636                let indent = " ".repeat(text_width(&marker));
2637                let f = concat(pf, &synth(&marker, Role::ListMarker, start));
2638                let c = concat(pc, &synth(&indent, Role::Body, start));
2639                if self.children(id).is_empty() {
2640                    // A definition with no body yet — the instant `[^1]: ` has
2641                    // been typed and nothing after it. `blocks` would emit
2642                    // nothing and the definition simply wouldn't appear, so emit
2643                    // the marker row itself with a caret home just past it,
2644                    // exactly as an empty list item does.
2645                    self.push_row_at(f, end.min(source.len()));
2646                } else {
2647                    self.blocks(id, &f, &c, false);
2648                }
2649            }
2650            "table" => self.table(id, pf, pc),
2651            "code_block" => {
2652                let style = Style::default().role(Role::Code);
2653                let text = node.text.clone().unwrap_or_default();
2654                let lines: Vec<&str> = text.trim_end_matches('\n').split('\n').collect();
2655                // Each line at its own source offset, so the caret can walk the
2656                // code a character at a time like any other text. Where the
2657                // lines can't be lined up with the source there's no honest
2658                // offset to give, so the block maps coarsely to its start (and
2659                // stays a source-view job, as all of it once was).
2660                let offs = node
2661                    .content_span
2662                    .as_ref()
2663                    .and_then(|c| self.code_line_offsets(c, &lines));
2664                // The fence's info string, carried on the block's first row as
2665                // its language label (`None` for an indented block or a bare
2666                // fence). Kept on the row so it rides the block cache.
2667                let lang = code_language(self.source, node.span.start);
2668                for (i, raw) in lines.iter().enumerate() {
2669                    let at = offs.as_ref().map_or(node.span.start, |o| o[i]);
2670                    // No gutter glyph: the block is set apart by the border and
2671                    // tint a frontend draws around the whole run of `code` rows,
2672                    // not by a per-line mark. Just the block prefix (a list
2673                    // indent, a quote gutter) and the code text.
2674                    let mut glyphs: Vec<Glyph> = pf.to_vec();
2675                    push_text(&mut glyphs, raw, at, style);
2676                    // Explicitly past the line's *text*: a blank code line has no
2677                    // glyph, and any prefix's offset would put the row's end
2678                    // inside the next line.
2679                    self.push_row_at(glyphs, at + raw.len());
2680                    if let Some(row) = self.rows.last_mut() {
2681                        row.code = true;
2682                        if i == 0 {
2683                            row.code_lang = lang.clone();
2684                        }
2685                    }
2686                }
2687                // Anchor the block's end past its closing fence. Its last content
2688                // row ends at the last code line, before the ``` and the blank
2689                // line under it; without this the separator logic would count the
2690                // closing-fence line as its own blank row and open a phantom
2691                // second gap below the block.
2692                self.last_off = node.span.end;
2693            }
2694            "thematic_break" => {
2695                let full = self.wrap.unwrap_or(UNWRAPPED_RULE_WIDTH);
2696                let w = full.saturating_sub(prefix_width(pf)).max(4);
2697                let mut glyphs = pf.to_vec();
2698                for _ in 0..w {
2699                    glyphs.push(Glyph {
2700                        ch: '─',
2701                        style: Style::default().role(Role::Rule),
2702                        src: node.span.start,
2703                        // A rule is a block the caret can sit on, as it always
2704                        // has; it maps coarsely to the block's start.
2705                        stop: true,
2706                    });
2707                }
2708                // The dashes share one caret home in front of the atomic block,
2709                // while the row's end is the second home just past its source.
2710                // Without that trailing stop a final rule made the document end
2711                // unreachable: Right could not cross it and a click in the
2712                // empty space below it snapped back before the rule.
2713                let after_line = node.span.end
2714                    + self.source[node.span.end..]
2715                        .strip_prefix("\r\n")
2716                        .map_or_else(
2717                            || usize::from(self.source[node.span.end..].starts_with('\n')),
2718                            |_| 2,
2719                        );
2720                self.push_row_at(glyphs, after_line);
2721            }
2722            // A block-level image node with no wrapping paragraph — a promoted
2723            // top-level HTML `<img>` lands as a direct `doc` child like this
2724            // (a Markdown `![](…)` comes wrapped in a `para`, handled below).
2725            "image" => self.block_media(id, MediaKind::Image, id, pf),
2726            // The same case for a promoted top-level `<video>`/`<audio>`, which
2727            // arrives as a generic `container` rather than a node kind of its
2728            // own. It can't be found by the `media_only` scan below the way a
2729            // wrapped one is: that scan looks at a wrapper's *children*, and here
2730            // the media element is itself the block.
2731            "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
2732                let kind = match element_tag(node) {
2733                    Some("audio") => MediaKind::Audio,
2734                    _ => MediaKind::Video,
2735                };
2736                self.block_media(id, kind, id, pf);
2737            }
2738            _ => {
2739                // A container of blocks, or an inline-bearing paragraph.
2740                let kids = self.children(id);
2741                // A block-level image: a paragraph (or other wrapper — a
2742                // `<picture>`, an `<h1>` banner) whose only visible content is a
2743                // single `image` node. Render it as a placeholder row + record an
2744                // [`MediaInfo`] a capable frontend replaces. An image mixed with
2745                // real text or other images on the line isn't block-level and
2746                // falls through to the inline path below, still as its alt text.
2747                if let Some((m, kind)) = self.media_only(id) {
2748                    self.block_media(m, kind, id, pf);
2749                    return;
2750                }
2751                let inline = !kids.is_empty() && kids.iter().all(|&c| is_inline(&self.nodes[c]));
2752                if inline || kids.is_empty() {
2753                    let glyphs = self.inline_children_with_trailing(id, Style::default());
2754                    if !glyphs.is_empty() {
2755                        self.emit_wrapped(glyphs, node.span.start, pf, pc);
2756                    }
2757                } else {
2758                    self.blocks(id, pf, pc, false);
2759                }
2760            }
2761        }
2762    }
2763
2764    /// Render a table as a box-drawn grid: every column as wide as its widest
2765    /// cell, the header bold and ruled off, each cell padded to its column's
2766    /// alignment. This is the *default* monospace rendering (see
2767    /// [`VisualMap::rows`]); the same cells are also published structurally as
2768    /// [`TableInfo`], so a frontend that lays the grid out in its own units draws
2769    /// from there and skips the picture built here.
2770    ///
2771    /// The alignment comes from twig's `cell.alignment` — the delimiter row
2772    /// (`|:--|--:|`) that spells it out is consumed by the parser and leaves no
2773    /// node, so the snapshot is the only source for it.
2774    ///
2775    /// Borders and padding are *decoration*: they carry the source offset of the
2776    /// text they surround, so a click lands in that cell, but they're never
2777    /// caret stops — the caret steps cell-to-cell instead of into the box art.
2778    fn table(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
2779        let node_end = self.nodes[id].span.end;
2780        // twig's shape is `[caption, row, row, …]`: the caption is always
2781        // present (usually empty in Markdown) and is not part of the grid.
2782        let row_ids: Vec<usize> = self
2783            .children(id)
2784            .into_iter()
2785            .filter(|&c| self.nodes[c].kind == Kind::Row)
2786            .collect();
2787        if row_ids.is_empty() {
2788            return;
2789        }
2790        // Lay every cell out first — the column widths depend on all of them.
2791        let grid: Vec<Vec<TableCell>> = row_ids.iter().map(|&r| self.row_cells(r)).collect();
2792        let heads: Vec<bool> = row_ids
2793            .iter()
2794            .map(|&r| self.nodes[r].head.unwrap_or(false))
2795            .collect();
2796        let cols = grid.iter().map(|r| r.len()).max().unwrap_or(0);
2797        if cols == 0 {
2798            return;
2799        }
2800        let mut widths = vec![0usize; cols];
2801        for row in &grid {
2802            for (c, cell) in row.iter().enumerate() {
2803                widths[c] = widths[c].max(cell_width(&cell.glyphs));
2804            }
2805        }
2806        // Every column at its widest cell is only the *wish*; a grid wider than
2807        // the surface has its far side hanging off the edge where no amount of
2808        // caret motion can reach it. Cut it down to what's actually there, and
2809        // let the cells wrap into the space they're given.
2810        if let Some(w) = self.wrap {
2811            fit_widths(&mut widths, w.saturating_sub(prefix_width(pc)));
2812        }
2813
2814        // Where the picture starts, so a frontend drawing its own grid knows
2815        // which rows to skip. Recorded before the first border goes down.
2816        let rows_start = self.rows.len();
2817
2818        let anchor = grid[0].first().map(|c| c.start).unwrap_or(node_end);
2819        self.push_rule(&rule_text(&widths, '┌', '┬', '┐'), anchor, pf);
2820        for (ri, row) in grid.iter().enumerate() {
2821            self.push_table_row(row, &widths, pc);
2822            // The rule under the header: only where the head actually ends.
2823            let ends_head = heads[ri] && heads.get(ri + 1) == Some(&false);
2824            if ends_head {
2825                let next = grid[ri + 1].first().map(|c| c.start).unwrap_or(node_end);
2826                self.push_rule(&rule_text(&widths, '├', '┼', '┤'), next, pc);
2827            }
2828        }
2829        self.push_rule(&rule_text(&widths, '└', '┴', '┘'), node_end, pc);
2830
2831        // The same cells the picture above was drawn from, published unwrapped
2832        // and unpadded for a frontend that lays them out in pixels.
2833        self.tables.push(TableInfo {
2834            rows_span: rows_start..self.rows.len(),
2835            end_src: node_end,
2836            // The *continuation* prefix: `pf` opens the block and only its first
2837            // row wears it, but every row of a grid is a continuation of the
2838            // block the table sits in.
2839            prefix: pc.to_vec(),
2840            grid: grid
2841                .into_iter()
2842                .zip(heads)
2843                .map(|(cells, head)| TableRow { head, cells })
2844                .collect(),
2845        });
2846        // The table's own end anchors whatever separator follows it; the border
2847        // rows deliberately don't move `last_off` (they hold no content).
2848        self.last_off = node_end;
2849    }
2850
2851    /// One row of laid-out cells, in column order.
2852    fn row_cells(&self, row: usize) -> Vec<TableCell> {
2853        // A cell is one source line, so a break within it is an explicit line
2854        // break (an inline `<br>`) that must render as a line of its own — not the
2855        // flow-folding space a break is in prose.
2856        self.break_glyph.set('\n');
2857        let cells = self
2858            .children(row)
2859            .into_iter()
2860            .filter(|&c| self.nodes[c].kind == Kind::Cell)
2861            .enumerate()
2862            .map(|(col, c)| {
2863                let n = &self.nodes[c];
2864                let style = if n.head.unwrap_or(false) {
2865                    Style::default().bold()
2866                } else {
2867                    Style::default()
2868                };
2869                // A cell's own `span` is the whole row; only `content_span` bounds
2870                // its text. An EMPTY cell has no `content_span` at all — twig
2871                // records no interior for it — so both offsets would fall back to
2872                // the row's start (before its first `│`), where every empty cell
2873                // in the row collapses onto the same spot and a click or caret
2874                // there types *before* the table. Derive the cell's own interior
2875                // from the row source and this cell's column instead, so each
2876                // empty cell has a distinct, editable caret home.
2877                let span = n.content_span.clone().unwrap_or_else(|| {
2878                    let off = empty_cell_offset(
2879                        &self.source[n.span.start.min(self.source.len())
2880                            ..n.span.end.min(self.source.len())],
2881                        n.span.start,
2882                        col,
2883                    );
2884                    off..off
2885                });
2886                TableCell {
2887                    glyphs: self.inline_children(c, style),
2888                    start: span.start,
2889                    end: span.end,
2890                    align: n.alignment.unwrap_or(Alignment::Default),
2891                }
2892            })
2893            .collect();
2894        self.break_glyph.set(' ');
2895        cells
2896    }
2897
2898    /// A horizontal rule between/around rows — entirely decoration.
2899    fn push_rule(&mut self, text: &str, src: usize, prefix: &[Glyph]) {
2900        let glyphs = concat(prefix, &synth(text, Role::Rule, src));
2901        self.rows.push(VRow {
2902            glyphs,
2903            end_src: src,
2904            decoration: true,
2905            code: false,
2906            code_lang: None,
2907            directive: false,
2908            directive_label: None,
2909            media: None,
2910            task: None,
2911            leaf_directive: None,
2912            heading: None,
2913            boundary: None,
2914        });
2915    }
2916
2917    /// One `│ a │ b │` row of the grid: real cell text between decoration.
2918    ///
2919    /// A row of cells is not a row of the screen — a cell wrapped to its column
2920    /// spans several, each one `│`-divided across the full width so the grid
2921    /// stays square. Cells in the same row are laid out independently and run
2922    /// out at their own heights; a column that has run dry pads out as
2923    /// decoration while its neighbours keep going.
2924    fn push_table_row(&mut self, cells: &[TableCell], widths: &[usize], prefix: &[Glyph]) {
2925        let fallback = cells.last().map(|c| c.end).unwrap_or(0);
2926        let laid: Vec<Vec<Vec<Glyph>>> = cells
2927            .iter()
2928            .enumerate()
2929            .map(|(ci, c)| wrap_glyphs(&c.glyphs, widths.get(ci).copied().unwrap_or(0)))
2930            .collect();
2931        let height = laid.iter().map(|l| l.len()).max().unwrap_or(1).max(1);
2932
2933        for j in 0..height {
2934            let mut glyphs = prefix.to_vec();
2935            for (ci, &w) in widths.iter().enumerate() {
2936                let cell = cells.get(ci);
2937                let line = laid.get(ci).and_then(|l| l.get(j));
2938                // The divider before this column belongs to the cell it
2939                // introduces, so clicking it lands in that cell — on this line
2940                // of it, which is what's next to the divider being clicked.
2941                let at = line
2942                    .and_then(|l| l.first().map(|g| g.src))
2943                    .or_else(|| cell.map(|c| c.start))
2944                    .unwrap_or(fallback);
2945                glyphs.extend(synth("│", Role::Rule, at));
2946                match (cell, line) {
2947                    (Some(cell), Some(line)) => {
2948                        let pad = w.saturating_sub(glyphs_width(line));
2949                        let (lead, trail) = match cell.align {
2950                            Alignment::Right => (pad, 0),
2951                            Alignment::Center => (pad / 2, pad - pad / 2),
2952                            Alignment::Left | Alignment::Default => (0, pad),
2953                        };
2954                        // Every line renders at least one space after its text
2955                        // (the gutter before `│`), so there is always somewhere
2956                        // to put the "after the last character" caret a line
2957                        // needs. It's the one padding glyph that is a stop: on
2958                        // the cell's last line that's the cell's end, and on any
2959                        // other it's the space the wrap consumed.
2960                        let last = laid[ci].len() == j + 1;
2961                        let end = match last {
2962                            true => cell.end,
2963                            false => line
2964                                .last()
2965                                .map(|g| g.src + g.ch.len_utf8())
2966                                .unwrap_or(cell.end),
2967                        };
2968                        glyphs.extend(synth(&" ".repeat(lead + 1), Role::Body, at));
2969                        glyphs.extend(line.iter().cloned());
2970                        glyphs.push(Glyph {
2971                            ch: ' ',
2972                            style: Style::default(),
2973                            src: end,
2974                            stop: true,
2975                        });
2976                        glyphs.extend(synth(&" ".repeat(trail), Role::Body, end));
2977                    }
2978                    // A ragged row, or a column whose cell ended higher up: pad
2979                    // it out so the grid stays square.
2980                    _ => {
2981                        let at = cell.map(|c| c.end).unwrap_or(fallback);
2982                        glyphs.extend(synth(&" ".repeat(w + 2), Role::Body, at));
2983                    }
2984                }
2985            }
2986            glyphs.extend(synth("│", Role::Rule, fallback));
2987            // The row ends where its last stop does. A table row has no gap
2988            // between its final cell and the border, so inventing an end past
2989            // that would be a stop with nothing under it.
2990            let end_src = glyphs
2991                .iter()
2992                .rev()
2993                .find(|g| g.stop)
2994                .map_or(fallback, |g| g.src);
2995            self.rows.push(VRow {
2996                glyphs,
2997                end_src,
2998                decoration: false,
2999                code: false,
3000                code_lang: None,
3001                directive: false,
3002                directive_label: None,
3003                media: None,
3004                task: None,
3005                leaf_directive: None,
3006                heading: None,
3007                boundary: None,
3008            });
3009        }
3010    }
3011
3012    /// Render a block-level image, video, or audio as one placeholder row: the
3013    /// `🖼 alt` / `🎬 alt` / `🔊 alt` label styled [`Role::Image`], every glyph
3014    /// mapped to the media's start offset and a caret stop there (they share the
3015    /// offset, so the stop table dedups them to a single home in front of it, as
3016    /// a rule's dashes do), and the row's end stop set past it so the caret can
3017    /// also rest after it. The row carries a [`MediaMark`] so [`media_spans`]
3018    /// publishes it as a [`MediaInfo`] a capable frontend replaces with the real
3019    /// picture or player; a plain surface paints the label as-is. `pf` is the
3020    /// block prefix (a list indent, a quote gutter) the row opens with, exactly
3021    /// as every other block honours it.
3022    fn block_media(&mut self, img: usize, kind: MediaKind, wrapper: usize, pf: &[Glyph]) {
3023        let node = &self.nodes[img];
3024        let start = node.span.start;
3025        let end = node.span.end;
3026        // An `image`'s URL is twig's `destination`; a `<video>`/`<audio>` is a
3027        // generic element, so its URL is the `src` attribute — and may be absent
3028        // entirely, the element naming its candidates in child `<source>`s.
3029        let destination = match kind {
3030            MediaKind::Image => node.destination.clone().unwrap_or_default(),
3031            MediaKind::Video | MediaKind::Audio => attr_of(node, "src").unwrap_or_default(),
3032        };
3033        let poster = match kind {
3034            MediaKind::Video => attr_of(node, "poster").unwrap_or_default(),
3035            MediaKind::Image | MediaKind::Audio => String::new(),
3036        };
3037        // The `<source>`s under the media element itself, not under `wrapper`: a
3038        // `<video>` is its own container, unlike an `<img>`, whose `<picture>`
3039        // alternatives are its *siblings* and so only reachable from the wrapper.
3040        let sources = match kind {
3041            MediaKind::Image => self.media_sources(wrapper),
3042            MediaKind::Video | MediaKind::Audio => self.media_sources(img),
3043        };
3044        let alt = self.image_alt(img);
3045        let sigil = kind.sigil();
3046        let label = if alt.is_empty() {
3047            // With no alt, name the file — but a `<video>` with neither `src` nor
3048            // alt has only its `<source>`s to be named by, so fall back to the
3049            // first candidate rather than labelling the row a bare sigil.
3050            let named = if destination.is_empty() {
3051                sources
3052                    .first()
3053                    .map(|s| s.srcset.as_str())
3054                    .unwrap_or_default()
3055            } else {
3056                &destination
3057            };
3058            format!("{sigil} {}", media_label(named))
3059        } else {
3060            format!("{sigil} {alt}")
3061        };
3062        let style = Style::default().role(Role::Image);
3063        let mut glyphs = pf.to_vec();
3064        for ch in label.chars() {
3065            glyphs.push(Glyph {
3066                ch,
3067                style,
3068                src: start,
3069                stop: true,
3070            });
3071        }
3072        // How many rows the frontend wants for this picture: the label row plus
3073        // the blank fillers below it. Absent (a GUI that lays images out in
3074        // pixels, an image that didn't resolve, or a plain surface) means the
3075        // bare one-row placeholder.
3076        let rows = self
3077            .media_rows
3078            .get(&destination)
3079            .copied()
3080            .unwrap_or(1)
3081            .max(1);
3082        // End past the image so the caret has a stop after it: the last glyph's
3083        // offset is the image *start*, not its extent, so `push_row`'s
3084        // last-glyph rule would strand the end stop inside the markup.
3085        self.push_row_at(glyphs, end);
3086        if let Some(row) = self.rows.last_mut() {
3087            row.media = Some(MediaMark {
3088                kind,
3089                destination,
3090                sources,
3091                alt,
3092                poster,
3093                rows,
3094            });
3095        }
3096        // Reserve the picture's remaining height as blank `decoration` rows: drawn
3097        // (so the frontend has the vertical room to paint the raster over them),
3098        // but holding no caret and contributing no stops — vertical motion steps
3099        // over them and the caret's only homes stay the stop in front of the image
3100        // and the one just past it, both on the label row above. They anchor at the
3101        // image's end offset so a click on the picture's lower half lands after it,
3102        // the nearest caret home. Mirrors how a table's box-rule rows reserve space
3103        // without ever holding the caret.
3104        for _ in 1..rows {
3105            self.rows.push(VRow {
3106                glyphs: Vec::new(),
3107                end_src: end,
3108                decoration: true,
3109                code: false,
3110                code_lang: None,
3111                directive: false,
3112                directive_label: None,
3113                media: None,
3114                task: None,
3115                leaf_directive: None,
3116                heading: None,
3117                boundary: None,
3118            });
3119        }
3120        self.last_off = end;
3121    }
3122
3123    /// The `<picture>` alternatives inside block-image `wrapper`, in document
3124    /// order — every `<source>` element in its subtree. Empty when there's no
3125    /// `<picture>`. Each is a `<source>`'s `media` + `srcset`; core keeps them
3126    /// verbatim and picks none (see [`MediaSource`]). A `<source>` with no
3127    /// `srcset` is dropped (nothing to load); its `media` may be empty (an
3128    /// unconditional override), which a frontend treats as always-matching.
3129    ///
3130    /// It scans the wrapper's whole subtree (via the forward `first_child` /
3131    /// `next_sibling` links, the reliable ones) rather than the `<img>`'s parent,
3132    /// for two reasons. A `<picture>` reaches core in two shapes: twig promotes a
3133    /// block `<picture>` to an `element(picture)` wrapping `[source, img]`, but
3134    /// leaves an inline one's tags as raw siblings — `[raw "<picture>", source,
3135    /// img, raw "</picture>"]` — so the `<source>`s sit at different depths in
3136    /// the two. And the editor's flat arena leaves a promoted inline node's
3137    /// `parent` back-pointer dangling on a phantom root, so only the wrapper
3138    /// (known at the call site) is a trustworthy anchor. A block image is the
3139    /// sole visible content of its wrapper, so every `<source>` under it is its
3140    /// picture's.
3141    fn media_sources(&self, wrapper: usize) -> Vec<MediaSource> {
3142        let mut out = Vec::new();
3143        self.collect_sources(wrapper, &mut out);
3144        out
3145    }
3146
3147    fn collect_sources(&self, id: usize, out: &mut Vec<MediaSource>) {
3148        for c in self.children(id) {
3149            let node = &self.nodes[c];
3150            if node.name.as_deref() == Some("source") {
3151                // `<picture>` spells its candidate `srcset`, `<video>`/`<audio>`
3152                // spell it `src`. Both mean "the URL to load", so they normalise
3153                // onto one field; `srcset` wins where (illegally) both appear.
3154                let url = attr_of(node, "srcset").or_else(|| attr_of(node, "src"));
3155                if let Some(srcset) = url {
3156                    out.push(MediaSource {
3157                        media: attr_of(node, "media").unwrap_or_default(),
3158                        srcset,
3159                        mime: attr_of(node, "type").unwrap_or_default(),
3160                    });
3161                }
3162            }
3163            self.collect_sources(c, out);
3164        }
3165    }
3166
3167    /// The single block-level media `id`'s subtree resolves to, or `None`.
3168    ///
3169    /// A wrapper is a block picture when the only *visible* thing under it is one
3170    /// image: whitespace-only text and structure-only elements (a `<picture>`'s
3171    /// `<source>`, which declares an alternate but paints nothing) don't count,
3172    /// and the search descends through wrapping elements (`<picture>`, a linking
3173    /// `<a>`). This is what makes `<p><img></p>`, a bare `<img>`, and
3174    /// `<h1><picture>…<img></picture></h1>` all render as one framed picture.
3175    /// Any real text, or a second image, means it isn't image-only — it falls
3176    /// back to inline rendering, where the image still shows as its alt text.
3177    ///
3178    /// [`FlatNode`]'s snapshot doesn't carry an element's tag name, so a
3179    /// `<source>` can't be skipped by name — but it needs no special case:
3180    /// contributing no image and no text, it's simply invisible to the scan.
3181    fn media_only(&self, id: usize) -> Option<(usize, MediaKind)> {
3182        let mut found = None;
3183        let mut count = 0usize;
3184        let mut has_text = false;
3185        self.scan_visual(id, &mut found, &mut count, &mut has_text);
3186        (count == 1 && !has_text).then(|| found.unwrap())
3187    }
3188
3189    /// Walk `id`'s subtree tallying visible leaves for [`media_only`]: each
3190    /// image, `<video>`, or `<audio>` (remembering the last, counting the total)
3191    /// and whether any non-whitespace text appears. Media isn't descended into —
3192    /// an image's inline children are alt text, and a `<video>`'s are its
3193    /// no-support fallback and its `<source>` declarations, none of which is
3194    /// document content.
3195    ///
3196    /// [`media_only`]: Self::media_only
3197    fn scan_visual(
3198        &self,
3199        id: usize,
3200        found: &mut Option<(usize, MediaKind)>,
3201        count: &mut usize,
3202        has_text: &mut bool,
3203    ) {
3204        for c in self.children(id) {
3205            let node = &self.nodes[c];
3206            match node.kind.as_str() {
3207                "image" => {
3208                    *found = Some((c, MediaKind::Image));
3209                    *count += 1;
3210                }
3211                // A `<video>`/`<audio>` reaches core as a generic `container`
3212                // (twig gives neither a semantic node, so `html_elements`
3213                // promotion leaves the tag name on `name`). Counted as media and
3214                // *not* descended into, so its `<source>` children and its
3215                // "your browser does not support…" fallback text neither add a
3216                // second count nor make the block look like text.
3217                "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
3218                    let kind = match element_tag(node) {
3219                        Some("audio") => MediaKind::Audio,
3220                        _ => MediaKind::Video,
3221                    };
3222                    *found = Some((c, kind));
3223                    *count += 1;
3224                }
3225                // Text leaves: only non-whitespace counts as visible content.
3226                // (Twig keeps the whitespace `str`s between HTML tags — the
3227                // newlines and indentation inside a `<picture>` — as real nodes.)
3228                "str" | "smart_punctuation" | "verbatim" | "inline_math" => {
3229                    if node.text.as_deref().is_some_and(|t| !t.trim().is_empty()) {
3230                        *has_text = true;
3231                    }
3232                }
3233                // Structural breaks carry no visible glyph of their own.
3234                "soft_break" | "hard_break" | "non_breaking_space" => {}
3235                // Any other wrapper (emphasis, a link, a `<picture>`) is
3236                // transparent to the scan — descend into it.
3237                _ => self.scan_visual(c, found, count, has_text),
3238            }
3239        }
3240    }
3241
3242    /// A leaf directive (`::name{…}`) as one placeholder row — the
3243    /// [`block_media`](Self::block_media) recipe, for the same reason: it is a
3244    /// block that renders as *a thing*, not as text, and the frontend paints
3245    /// whatever the host app's vocabulary makes of it.
3246    ///
3247    /// The row's glyphs are a `⧉ label` (or `⧉ name`) stand-in a plain surface
3248    /// paints as-is, every glyph anchored at the directive's start with a caret
3249    /// stop there, and the row ending past it so the caret can also rest after
3250    /// it. It carries a [`DirectiveMark`] for [`directive_spans`], and is marked
3251    /// [`directive`](VRow::directive) so a frontend already drawing the
3252    /// container form's panel frames this one identically for free.
3253    ///
3254    /// Before this, a leaf directive emitted no rows at all: it was invisible,
3255    /// held no caret, and vertical motion crossed a void where it stood.
3256    fn block_directive(&mut self, id: usize, pf: &[Glyph]) {
3257        let node = &self.nodes[id];
3258        let (start, end) = (node.span.start, node.span.end);
3259        let name = node.name.clone().unwrap_or_default();
3260        let attrs = node.attrs.clone();
3261        let label = self.image_alt(id); // its `[label]` children, flattened
3262        let shown = if label.is_empty() { &name } else { &label };
3263        let style = Style::default().role(Role::Image);
3264        let mut glyphs = pf.to_vec();
3265        for ch in format!("⧉ {shown}").chars() {
3266            glyphs.push(Glyph {
3267                ch,
3268                style,
3269                src: start,
3270                stop: true,
3271            });
3272        }
3273        // End past the directive so the caret has a stop after it — the same
3274        // reason `block_media` anchors its row at the image's end.
3275        self.push_row_at(glyphs, end);
3276        if let Some(row) = self.rows.last_mut() {
3277            row.directive = true;
3278            row.leaf_directive = Some(DirectiveMark {
3279                name,
3280                attrs,
3281                label,
3282                rows: 1,
3283            });
3284        }
3285        self.last_off = end;
3286    }
3287
3288    /// An image's alt text: the flattened text of its inline descendants (an
3289    /// image's children *are* its alt content), empty when it has none. Also a
3290    /// leaf directive's `[label]`, which is the same shape — inline children
3291    /// standing for the block.
3292    fn image_alt(&self, id: usize) -> String {
3293        let mut out = String::new();
3294        self.collect_text(id, &mut out);
3295        out
3296    }
3297
3298    /// Append every descendant's `text` to `out`, in document order. Inline text
3299    /// (`str`) nodes are leaves, so a node never contributes both its own text and
3300    /// a child's — no double counting.
3301    fn collect_text(&self, id: usize, out: &mut String) {
3302        for c in self.children(id) {
3303            if let Some(t) = &self.nodes[c].text {
3304                out.push_str(t);
3305            }
3306            self.collect_text(c, out);
3307        }
3308    }
3309
3310    fn inline_children(&self, id: usize, base: Style) -> Vec<Glyph> {
3311        let mut out = Vec::new();
3312        for c in self.children(id) {
3313            self.inline(c, base, &mut out);
3314        }
3315        out
3316    }
3317
3318    /// [`inline_children`](Self::inline_children) plus any trailing whitespace the
3319    /// block carries past its inline content (see [`trailing_ws_glyphs`]). Used
3320    /// for the leaf inline blocks — paragraphs and headings — whose own `span`
3321    /// bounds exactly one line of text, so the trailing gap is theirs. *Not* for
3322    /// a table cell, whose `span` is the whole row and would swallow the
3323    /// delimiters and neighbours between it and the row's end.
3324    ///
3325    /// [`trailing_ws_glyphs`]: Self::trailing_ws_glyphs
3326    fn inline_children_with_trailing(&self, id: usize, base: Style) -> Vec<Glyph> {
3327        let mut out = self.inline_children(id, base);
3328        out.extend(self.trailing_ws_glyphs(id, base));
3329        out
3330    }
3331
3332    /// Glyphs for whatever trailing whitespace a block's source carries past its
3333    /// last inline node — the space(s) at the end of `hello ` that Markdown and
3334    /// Djot drop from the `str` node as insignificant. twig still records them:
3335    /// a block's `content_span` ends at its last meaningful character while its
3336    /// `span` runs to the end of the line's text (before the terminating
3337    /// newline), so the gap between the two *is* that trailing whitespace.
3338    ///
3339    /// Emitting it as real caret-stop glyphs is what lets the caret be drawn
3340    /// past the last visible character. Without it, typing a space at the end of
3341    /// a paragraph moved the caret in the source but not on screen — the caret
3342    /// stuck on the last glyph until the next visible character reparsed the
3343    /// space into an interior `str` node that finally carried it.
3344    ///
3345    /// Restricted to spaces: only they are safe to synthesize one-cell-per-byte,
3346    /// and only they are what the parser silently strips. Anything else in the
3347    /// gap means the span accounting isn't what this assumes, so it's left alone.
3348    fn trailing_ws_glyphs(&self, id: usize, style: Style) -> Vec<Glyph> {
3349        let node = &self.nodes[id];
3350        let Some(content) = &node.content_span else {
3351            return Vec::new();
3352        };
3353        let (from, to) = (content.end, node.span.end);
3354        let Some(slice) = (from < to).then(|| self.source.get(from..to)).flatten() else {
3355            return Vec::new();
3356        };
3357        if slice.is_empty() || slice.bytes().any(|b| b != b' ') {
3358            return Vec::new();
3359        }
3360        slice
3361            .bytes()
3362            .enumerate()
3363            .map(|(i, _)| Glyph {
3364                ch: ' ',
3365                style,
3366                src: from + i,
3367                stop: true,
3368            })
3369            .collect()
3370    }
3371
3372    fn inline(&self, id: usize, base: Style, out: &mut Vec<Glyph>) {
3373        let node = &self.nodes[id];
3374        match node.kind.as_str() {
3375            "str" | "smart_punctuation" => push_escaped_text(
3376                out,
3377                node.text.as_deref().unwrap_or(""),
3378                node.span.clone(),
3379                self.source,
3380                base,
3381            ),
3382            "soft_break" | "hard_break" | "non_breaking_space" => {
3383                // A break renders as a real, caret-navigable glyph — but twig
3384                // gives it no span of its own (`0..0`), so the offset comes from
3385                // the text in front of it: one *past* the last glyph, which is
3386                // the newline the break stands for. Past, not on: sharing the
3387                // previous glyph's offset would put two stops on one byte, and a
3388                // caret that can't change offset can't move.
3389                let src = if node.span.start != 0 {
3390                    node.span.start
3391                } else {
3392                    out.last().map(|g| g.src + g.ch.len_utf8()).unwrap_or(0)
3393                };
3394                // A *hard* break renders as this run's break glyph — a newline
3395                // inside a table cell (its own line), the same space in prose the
3396                // frontend re-wraps. A soft break normally folds into a space;
3397                // under `LineFlow::Preserve` it renders as a `'\n'` too, so the
3398                // author's line break shows where it was written. Never inside a
3399                // cell (`break_glyph` is `'\n'` there): a cell is one line and
3400                // folds its own soft breaks regardless.
3401                let ch = if node.kind == Kind::HardBreak {
3402                    self.break_glyph.get()
3403                } else if node.kind == Kind::SoftBreak
3404                    && self.preserve_soft
3405                    && self.break_glyph.get() == ' '
3406                {
3407                    '\n'
3408                } else {
3409                    ' '
3410                };
3411                out.push(Glyph {
3412                    ch,
3413                    style: base,
3414                    src,
3415                    stop: true,
3416                });
3417            }
3418            // A cell's only spelling for an in-line break is a raw `<br>`; read it
3419            // back as one (outside a cell it stays the literal text it falls to
3420            // below). The tag's bytes carry no stop of their own — the line it
3421            // ends stops just before it, the next just after.
3422            "raw_inline" if self.break_glyph.get() == '\n' && is_br(node.text.as_deref()) => {
3423                out.push(Glyph {
3424                    ch: '\n',
3425                    style: base,
3426                    src: node.span.start,
3427                    stop: true,
3428                });
3429            }
3430            "emph" => self.inline_delimited(id, base.italic(), out),
3431            "strong" => self.inline_delimited(id, base.bold(), out),
3432            // A coloured highlight's emoji is spelling, not content: twig strips
3433            // it and records the colour on the node, so the glyphs are the
3434            // author's words and the colour rides the role. Revealed markup
3435            // still shows the emoji, because `delims` reads the source bytes
3436            // between the span and the content span — which is exactly the
3437            // `==🔴 ` the author typed.
3438            "mark" => {
3439                let color = MarkColor::from_attrs(&node.attrs);
3440                self.inline_delimited(id, base.role(Role::Mark(color)), out)
3441            }
3442            "insert" => self.inline_delimited(id, base.underline(), out),
3443            "delete" => self.inline_delimited(id, base.strikethrough(), out),
3444            // The one pair whose whole meaning is *where the glyphs sit*. Drawn
3445            // in the surrounding style otherwise, so `^**2**^` stays bold and a
3446            // superscript inside a heading keeps the heading's role — which is
3447            // exactly why this is a `Baseline` and not a `Role`.
3448            "superscript" => self.inline_delimited(id, base.baseline(Baseline::Super), out),
3449            "subscript" => self.inline_delimited(id, base.baseline(Baseline::Sub), out),
3450            "verbatim" | "inline_math" => {
3451                // The interior begins at `content_span.start` — past however many
3452                // backticks the fence used, which `span.start + 1` only guessed
3453                // right for a single one. Fall back to that guess if it's absent.
3454                let at = node
3455                    .content_span
3456                    .as_ref()
3457                    .map_or(node.span.start + 1, |c| c.start);
3458                let style = base.role(Role::Code);
3459                // Not `inline_delimited`: verbatim has no child nodes to recurse
3460                // into — its content is its own `text` — so the fences bracket a
3461                // `push_text` instead. The fences themselves keep `Role::Code`'s
3462                // sibling treatment via `push_delim`'s role override.
3463                let show = self.revealed(&node.span).then(|| self.delims(id)).flatten();
3464                if let Some((open, _)) = &show {
3465                    self.push_delim(out, open, style);
3466                }
3467                push_text(out, node.text.as_deref().unwrap_or(""), at, style);
3468                if let Some((_, close)) = &show {
3469                    self.push_delim(out, close, style);
3470                }
3471            }
3472            // A text directive (`:name[label]{…}`) — the inline form of a generic
3473            // directive. Its `[label]` children are the visible text; the name and
3474            // the `{…}` attributes are the host app's vocabulary (diaryx's
3475            // `:vis[…]`) and stay hidden markup, exactly as a link's `](dest)` is.
3476            // Drawn in the surrounding style: a role of its own would need one
3477            // every frontend maps, and the bug this fixes is that the text was
3478            // invisible, not that it was unstyled.
3479            "container" if container_is_directive(node) && !self.children(id).is_empty() => {
3480                self.recurse(id, base, out)
3481            }
3482            // No `[label]`, so there are no children to render and recursing
3483            // emitted *nothing*: the directive's bytes vanished from the document
3484            // and left no caret stop behind. What to draw instead turns on
3485            // whether the syntax looks deliberate.
3486            //
3487            // Bare `:word` almost never is. twig matches a colon followed by any
3488            // letter-led word (`scanTextDirective`, deliberately matching remark),
3489            // so ordinary prose is full of them — `:see below`, a `:smile:`
3490            // shortcode, a stray colon before a word. Those are prose, and prose
3491            // renders as itself: every byte visible, every byte a caret stop, so a
3492            // colon typed by accident can be seen and deleted. Hiding them behind
3493            // a placeholder would be the invisible-and-unreachable failure this
3494            // arm exists to fix, just wearing a nicer glyph.
3495            "container" if container_is_directive(node) && node.attrs.is_empty() => {
3496                let span = node.span.clone();
3497                push_text(
3498                    out,
3499                    self.source.get(span.clone()).unwrap_or(""),
3500                    span.start,
3501                    base,
3502                );
3503            }
3504            // `{…}` attributes, though, are unmistakably deliberate — nobody
3505            // types `:vis{.family}` by accident, and diaryx writes exactly that
3506            // inline. So an attribute-bearing directive with no label draws as a
3507            // chip on `block_directive`'s recipe (`⧉ name attrs`, `Role::Image`),
3508            // the inline peer of the leaf form's placeholder row.
3509            //
3510            // Only the first glyph is a caret stop, and the whole chip shares the
3511            // directive's start offset: the caret treats it as one atomic thing
3512            // rather than walking hidden markup a byte at a time, and a paragraph
3513            // holding nothing but a chip still has a stop to be navigated to.
3514            "container" if container_is_directive(node) => {
3515                let start = node.span.start;
3516                let name = node.name.clone().unwrap_or_default();
3517                let shown = match directive_attr_label(&node.attrs) {
3518                    Some(attrs) if !name.is_empty() => format!("⧉ {name} {attrs}"),
3519                    Some(attrs) => format!("⧉ {attrs}"),
3520                    None => format!("⧉ {name}"),
3521                };
3522                let style = base.role(Role::Image);
3523                for (i, ch) in shown.chars().enumerate() {
3524                    out.push(Glyph {
3525                        ch,
3526                        style,
3527                        src: start,
3528                        stop: i == 0,
3529                    });
3530                }
3531            }
3532            // A footnote reference (`[^1]`). The label bracketed is what a reader
3533            // needs — bare, `note1` reads as a typo rather than a reference — so
3534            // the `^` is hidden as the spelling artefact it is (a link's
3535            // `](dest)` goes the same way) and the brackets are kept as
3536            // decoration: one shared offset, never a caret stop, like a table's
3537            // borders, so the caret walks the label alone.
3538            //
3539            // Styled `Role::Link`: a reference *is* a link to its definition, and
3540            // every frontend already paints that role. A role of its own would
3541            // need one in each of them, and what a frontend needs to tell the two
3542            // apart is not a paint colour but an answer to "what does clicking
3543            // here do" — which is [`Doc::footnote_at_caret`]'s job, not a glyph's.
3544            //
3545            // Raised, though, because that a reference is *set* differently from
3546            // the prose it interrupts is exactly what makes it read as a
3547            // reference. `[1]` at body size reads as bracketed text.
3548            "footnote_reference" => {
3549                let style = base.role(Role::Link);
3550                // Revealed, the reference is just its source bytes: the `^` that
3551                // is normally elided comes back and every byte becomes a real
3552                // stop, so the brackets stop being decoration and start being
3553                // text. That's the whole point of the mode, and it replaces the
3554                // hand-built chip below rather than decorating it — including the
3555                // raised baseline, since what's on screen there is source, and
3556                // source is set as prose.
3557                if self.revealed(&node.span) {
3558                    self.push_delim(out, &node.span, style);
3559                    return;
3560                }
3561                let style = style.baseline(Baseline::Super);
3562                // The label's own span, so its glyphs map to their true bytes.
3563                // Absent one, it starts past the `[^` that opens the reference.
3564                let (label, at) = match &node.content_span {
3565                    Some(c) => (self.source.get(c.clone()).unwrap_or(""), c.start),
3566                    None => (node.text.as_deref().unwrap_or(""), node.span.start + 2),
3567                };
3568                out.push(Glyph {
3569                    ch: '[',
3570                    style,
3571                    src: node.span.start,
3572                    stop: false,
3573                });
3574                push_text(out, label, at, style);
3575                out.push(Glyph {
3576                    ch: ']',
3577                    style,
3578                    src: node.span.end.saturating_sub(1),
3579                    stop: false,
3580                });
3581            }
3582            "link" | "url" | "email" => {
3583                let style = base.role(Role::Link);
3584                if self.children(id).is_empty() {
3585                    // A bare autolink (`<a@b.c>`, a naked URL): the destination
3586                    // *is* the visible text, so there is nothing elided to
3587                    // reveal and both modes draw the same thing.
3588                    push_text(
3589                        out,
3590                        node.destination
3591                            .as_deref()
3592                            .or(node.text.as_deref())
3593                            .unwrap_or("link"),
3594                        node.span.start,
3595                        style,
3596                    );
3597                } else {
3598                    // An inline link reveals asymmetrically — `[` before the
3599                    // label, `](dest)` after it — which the generic
3600                    // span-minus-content derivation already produces.
3601                    self.inline_delimited(id, style, out);
3602                }
3603            }
3604            _ => {
3605                if self.children(id).is_empty() {
3606                    if let Some(t) = &node.text {
3607                        push_text(out, t, node.span.start, base);
3608                    }
3609                } else {
3610                    self.recurse(id, base, out);
3611                }
3612            }
3613        }
3614    }
3615
3616    fn recurse(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
3617        for c in self.children(id) {
3618            self.inline(c, style, out);
3619        }
3620    }
3621
3622    /// Lay a block's inline `glyphs` into visual rows, prefixing the first with
3623    /// `pf` and the rest with `pc`. A preserved soft break arrives as a `'\n'`
3624    /// glyph (see the `soft_break` arm): a hard row boundary that splits the
3625    /// glyphs so each run lays out on its own and the author's line structure
3626    /// shows on screen. The `'\n'` is dropped from the row it closes and its
3627    /// source offset becomes that row's end stop — exactly how a table cell's
3628    /// in-line `<br>` is handled — so the caret can rest at the line's end
3629    /// without a zero-width control char leaking into what the frontends render.
3630    /// With no `'\n'` present (the folding default, and every build that isn't
3631    /// `LineFlow::Preserve`) there is one run and this is byte-identical to
3632    /// laying the glyphs out directly.
3633    fn emit_wrapped(&mut self, glyphs: Vec<Glyph>, block_start: usize, pf: &[Glyph], pc: &[Glyph]) {
3634        if !glyphs.iter().any(|g| g.ch == '\n') {
3635            self.emit_line(glyphs, block_start, pf, pc, None);
3636            return;
3637        }
3638        // Each run up to a '\n' is a line of its own: the first wears the block's
3639        // opening prefix, every later one the continuation prefix, and the break's
3640        // own offset ends the run's last row. The break glyph is dropped. A
3641        // trailing '\n' flushes its run and leaves nothing behind, so no spurious
3642        // blank row follows it.
3643        let mut run: Vec<Glyph> = Vec::new();
3644        let mut first = true;
3645        for g in glyphs {
3646            if g.ch == '\n' {
3647                let lead = if first { pf } else { pc };
3648                self.emit_line(std::mem::take(&mut run), block_start, lead, pc, Some(g.src));
3649                first = false;
3650            } else {
3651                run.push(g);
3652            }
3653        }
3654        if !run.is_empty() {
3655            let lead = if first { pf } else { pc };
3656            self.emit_line(run, block_start, lead, pc, None);
3657        }
3658    }
3659
3660    /// Word-wrap a single line of `glyphs` (no interior line breaks) to the
3661    /// available width and push the visual rows, prefixing the first with `pf`
3662    /// and the rest with `pc`. `end`, when set, is the source offset that ends
3663    /// the line's final row — the offset of the break that terminated it, which
3664    /// the caller has already stripped from `glyphs`; when `None` the row ends
3665    /// just past its last glyph, as an unbroken block's does.
3666    fn emit_line(
3667        &mut self,
3668        glyphs: Vec<Glyph>,
3669        block_start: usize,
3670        pf: &[Glyph],
3671        pc: &[Glyph],
3672        end: Option<usize>,
3673    ) {
3674        // The line's final row ends at `end` when a break gave one, else just
3675        // past its last glyph (`push_row`'s default).
3676        let push_last = |b: &mut Self, row: Vec<Glyph>| match end {
3677            Some(e) => b.push_row_at(row, e),
3678            None => b.push_row(row, block_start),
3679        };
3680
3681        // No column budget: emit the whole line as one row and let the frontend
3682        // wrap it at its own (pixel) width.
3683        let Some(width) = self.wrap else {
3684            let row = if glyphs.is_empty() {
3685                pf.to_vec()
3686            } else {
3687                concat(pf, &glyphs)
3688            };
3689            push_last(self, row);
3690            return;
3691        };
3692
3693        // Split into words (maximal non-space runs), each carrying the space
3694        // glyph that followed it (so its source offset is preserved).
3695        let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
3696        let mut word: Vec<Glyph> = Vec::new();
3697        for g in glyphs {
3698            if g.ch == ' ' {
3699                words.push((std::mem::take(&mut word), Some(g)));
3700            } else {
3701                word.push(g);
3702            }
3703        }
3704        if !word.is_empty() {
3705            words.push((word, None));
3706        }
3707        if words.is_empty() {
3708            // An empty block (or an empty preserved line) still occupies one
3709            // (prefixed) row.
3710            push_last(self, pf.to_vec());
3711            return;
3712        }
3713
3714        let mut line: Vec<Glyph> = Vec::new();
3715        let mut used = 0usize;
3716        let mut first = true;
3717        for (w, space) in words {
3718            let avail = width
3719                .saturating_sub(prefix_width(if first { pf } else { pc }))
3720                .max(1);
3721            let cells = glyphs_width(&w);
3722            if used > 0 && used + cells > avail {
3723                let row = concat(if first { pf } else { pc }, &line);
3724                self.push_row(row, block_start);
3725                line = Vec::new();
3726                used = 0;
3727                first = false;
3728            }
3729            used += cells;
3730            line.extend(w);
3731            if let Some(sp) = space {
3732                used += 1;
3733                line.push(sp);
3734            }
3735        }
3736        let row = concat(if first { pf } else { pc }, &line);
3737        push_last(self, row);
3738    }
3739
3740    /// The source offset of each line of a code block's `text`.
3741    ///
3742    /// `content` is the block's `content_span` — where twig says the body lives
3743    /// in the source, fences already excluded. Its lines run 1:1 with the
3744    /// rendered `text` lines, so no search is needed; each is anchored at the
3745    /// *end* of its source line, which places it past whatever indent `text` had
3746    /// stripped (a fenced block's fences, an indented one's leading spaces)
3747    /// without having to know how much there was.
3748    ///
3749    /// `None` when the body and the rendered lines don't line up — a coarse
3750    /// fallback the caller turns into the block's start offset.
3751    fn code_line_offsets(&self, content: &Range<usize>, lines: &[&str]) -> Option<Vec<usize>> {
3752        let mut src_lines: Vec<(usize, &str)> = Vec::new();
3753        let mut at = content.start;
3754        for l in self.source.get(content.start..content.end)?.split('\n') {
3755            src_lines.push((at, l));
3756            at += l.len() + 1;
3757        }
3758        if src_lines.len() != lines.len() {
3759            return None;
3760        }
3761        Some(
3762            lines
3763                .iter()
3764                .zip(&src_lines)
3765                .map(|(l, (start, sl))| start + sl.len().saturating_sub(l.len()))
3766                .collect(),
3767        )
3768    }
3769
3770    fn push_row(&mut self, glyphs: Vec<Glyph>, fallback: usize) {
3771        // Step past the character the *source* holds at the last glyph's offset,
3772        // not past the glyph's own `ch`. The two agree for ordinary text, but a
3773        // glyph is not always the character it stands on: `synth` decoration and
3774        // a substituted run (an image's `⧉ label`) share one offset by design.
3775        // Trusting `ch` there yields an offset inside a multi-byte character,
3776        // which every later slice of `source` panics on.
3777        let end_src = glyphs
3778            .last()
3779            .map(|g| {
3780                let at = g.src.min(self.source.len());
3781                at + self.source[at..].chars().next().map_or(0, char::len_utf8)
3782            })
3783            .unwrap_or(fallback);
3784        self.push_row_at(glyphs, end_src);
3785    }
3786
3787    /// Push a row with an explicit end stop, for content that knows its own
3788    /// extent better than its last glyph does.
3789    fn push_row_at(&mut self, glyphs: Vec<Glyph>, end_src: usize) {
3790        self.last_off = end_src;
3791        self.rows.push(VRow {
3792            glyphs,
3793            end_src,
3794            decoration: false,
3795            code: false,
3796            code_lang: None,
3797            directive: false,
3798            directive_label: None,
3799            media: None,
3800            task: None,
3801            leaf_directive: None,
3802            heading: None,
3803            boundary: None,
3804        });
3805    }
3806
3807    /// The quote's own trailing marker lines: the `>` / `> ` lines that lie past
3808    /// its last child but inside its span, one gutter row each.
3809    ///
3810    /// Pressing Enter at the end of `> a` writes `> a\n>\n> \n` — twig's
3811    /// spelling, and the right one. Those last two lines hold no block (a
3812    /// `block_quote`'s `content_span` still stops at its last child) so the
3813    /// children walk never reaches them, and they used to fall all the way to
3814    /// the document-level [`Builder::emit_trailing_blank_lines`], which knows no
3815    /// prefix: the gutter simply stopped, and a writer adding a line to a quote
3816    /// watched it draw as plain prose.
3817    ///
3818    /// This is only answerable since twig 3.2.0, where a Markdown `block_quote`'s
3819    /// span covers its own trailing marker lines (it reported `0..3` for that
3820    /// source and now reports `0..8`). Before that the lines belonged to no node
3821    /// at any level, and the only way to draw them was to sniff `>` off the raw
3822    /// source and re-derive the nesting depth by counting markers — format
3823    /// inference this crate exists to keep out of the render path.
3824    ///
3825    /// Each row is a real caret home rather than a decoration gap: the writer
3826    /// spelled every one of these lines with a marker of its own, so each is a
3827    /// line of the quote to stand on, not the spacing between two blocks (which
3828    /// is [`Builder::emit_separators_before`]'s, and falls *between* children
3829    /// where this never looks).
3830    fn emit_quote_trailing_lines(&mut self, pc: &[Glyph], end: usize) {
3831        let end = end.min(self.source.len());
3832        let mut at = self.rows.last().map_or(0, |r| r.end_src);
3833        // Walk line by line from the last child's end to the quote's, taking each
3834        // line's *end* as the row's offset — the caret home at the end of a line
3835        // is where one on an empty quoted line belongs, and it keeps every row's
3836        // offset distinct from its neighbours'.
3837        while at < end {
3838            let Some(k) = self.source[at..end].find('\n') else {
3839                break;
3840            };
3841            let line_start = at + k + 1;
3842            let line_end = self.source[line_start..end]
3843                .find('\n')
3844                .map_or(end, |i| line_start + i);
3845            self.push_row_at(pc.to_vec(), line_end);
3846            at = line_end;
3847        }
3848    }
3849
3850    /// The source offset the caret rests at on the blank line separating a block
3851    /// that ends at `prev_end` from the next block starting at `next_start`:
3852    /// just past the newline that terminates the previous block, but kept
3853    /// strictly before the next block so the offset is unique to this row.
3854    fn blank_line_offset(&self, prev_end: usize, next_start: usize) -> usize {
3855        let after_nl = self.source[prev_end..]
3856            .find('\n')
3857            .map_or(prev_end, |p| prev_end + p + 1);
3858        after_nl.min(next_start.saturating_sub(1)).max(prev_end)
3859    }
3860
3861    /// The source offset of each blank row between a block ending at `prev_end`
3862    /// and content starting at `next_start` — one per blank source line. The
3863    /// first newline terminates the previous block's line; every line it opens up
3864    /// to (but not including) the line that holds `next_start` is a blank row the
3865    /// caret can occupy. Offsets are unique and ascending so `pos_of_offset`
3866    /// resolves each to its own row. Empty when the two blocks are tight (no
3867    /// blank line between them).
3868    fn blank_rows_between(&self, prev_end: usize, next_start: usize) -> Vec<usize> {
3869        // Spans aren't always in tidy source order (e.g. a block after
3870        // frontmatter can start *before* the previous block's rendered content
3871        // ends). There's no blank line to place then — fall back to the clamped
3872        // single separator (an empty return) rather than slicing an inverted
3873        // range.
3874        if next_start <= prev_end {
3875            return Vec::new();
3876        }
3877        let gap = &self.source[prev_end..next_start];
3878        let Some(nl) = gap.find('\n') else {
3879            return Vec::new();
3880        };
3881        // The line holding `next_start` belongs to the next block; blank rows
3882        // stop before it.
3883        let next_line_start = self.source[..next_start].rfind('\n').map_or(0, |p| p + 1);
3884        let mut offs = Vec::new();
3885        let mut start = prev_end + nl + 1;
3886        while start < next_line_start {
3887            offs.push(start);
3888            match self.source[start..next_start].find('\n') {
3889                Some(k) => start += k + 1,
3890                None => break,
3891            }
3892        }
3893        offs
3894    }
3895
3896    /// Blank lines the user typed past the end of the last block (e.g. two
3897    /// `Enter`s to open a fresh paragraph) leave no AST node, so nothing renders
3898    /// and the caret appears stuck on the old line. Reconstruct one empty row
3899    /// per extra trailing newline from the source, each at its own offset, so
3900    /// the caret rides down onto the new line the moment it's created.
3901    ///
3902    /// `above` is the class of the last block in the document — the one this gap
3903    /// closes. A document with no blocks at all has nothing above these rows, and
3904    /// [`BlockClass::Paragraph`] is the honest answer there too: what they are is
3905    /// empty paragraphs, on both sides of the gap.
3906    fn emit_trailing_blank_lines(&mut self, above: BlockClass, hidden_end: usize) {
3907        // With no rows at all the count starts past any hidden frontmatter, not
3908        // at 0: its newlines are not trailing blank lines, and counting them
3909        // opened phantom rows *inside* the metadata for a frontmatter-only file.
3910        let last_end = self.rows.last().map_or(hidden_end, |r| r.end_src);
3911        if last_end >= self.source.len() {
3912            return;
3913        }
3914        // The first newline after the last content just terminates that line, so
3915        // a lone trailing `\n` (an ordinary file ending) opens no blank row. A
3916        // *second* newline opens an empty paragraph: render it the way a block
3917        // boundary is rendered — a blank spacer row, then the empty paragraph row
3918        // the caret rests on — so the just-pressed-Enter view already shows the
3919        // gap it will keep once text is typed, and typing doesn't shift the line
3920        // down. One row per trailing newline (each its own caret offset), the
3921        // last landing at the document end where the caret sits.
3922        let extra = self.source[last_end..].matches('\n').count();
3923        if extra < 2 {
3924            return;
3925        }
3926        for k in 1..=extra {
3927            self.rows.push(VRow {
3928                glyphs: Vec::new(),
3929                end_src: last_end + k,
3930                // As between two blocks: the first blank row is the gap that
3931                // closes the block above, not somewhere to type. Nothing follows
3932                // to need a gap of its own, though, so every row after it is a
3933                // real empty paragraph — the end of the document bounds the last
3934                // one the way a following block would. Preserve flow makes even
3935                // that first row navigable, as it does every blank line.
3936                decoration: !self.preserve_soft && k == 1,
3937                code: false,
3938                code_lang: None,
3939                directive: false,
3940                directive_label: None,
3941                media: None,
3942                task: None,
3943                leaf_directive: None,
3944                heading: None,
3945                // The one drawn row here is a block boundary like any other —
3946                // "rendered the way a block boundary is rendered" is the whole
3947                // point of it — so it says so, and a frontend spacing boundaries
3948                // spaces this one the same. The rows below it are navigable empty
3949                // paragraphs, not gaps.
3950                boundary: (!self.preserve_soft && k == 1).then_some(Boundary {
3951                    above,
3952                    below: BlockClass::Paragraph,
3953                }),
3954            });
3955        }
3956    }
3957}
3958
3959// ── display width ────────────────────────────────────────────────────────────
3960//
3961// Two things a row can be counted in, and they are not the same number:
3962//
3963//   *glyphs*, one per codepoint — how the text is stored here, and what an
3964//   index into `VRow::glyphs` means; and
3965//   *columns*, one per terminal cell — where the text is drawn, and what every
3966//   `col` in this crate means.
3967//
3968// `你` is one glyph in two columns. Counting columns with `glyphs.len()` (or,
3969// in the source view, `chars().count()`) is the same number only for the ASCII
3970// that most fixtures are written in, and drifts one cell per wide character
3971// everywhere else — the caret drawn a column short of the text it types into.
3972// Everything below converts between the two; nothing else should have to.
3973
3974/// The display width of `s` in terminal cells.
3975///
3976/// Measured per grapheme cluster, because that is the unit a surface advances
3977/// by: `👨‍👩‍👧` is five codepoints measuring 2 + 0 + 2 + 0 + 2 cells one at a
3978/// time, but the character they spell is drawn in 2. Both frontends already
3979/// measure it that way — ratatui asks `unicode-width` per cluster, and the GUI
3980/// asks its own text system — so the caret only lands where the text is if this
3981/// agrees with them.
3982pub fn text_width(s: &str) -> usize {
3983    UnicodeWidthStr::width(s)
3984}
3985
3986/// One grapheme cluster of a laid-out row: the glyphs that spell it, and the
3987/// cells it is drawn in.
3988///
3989/// The cluster, not the glyph, is what has a width. A row's glyphs are one per
3990/// codepoint, so an accented letter or an emoji is several of them drawn in one
3991/// character's worth of cells — the glyph that opens the cluster claims those
3992/// cells, and the ones continuing it are drawn *inside* them rather than beside
3993/// them. It's the same cluster the stop table is built on: the opening glyph is
3994/// the one a caret can rest on, and so the only one whose column it can be
3995/// drawn at.
3996struct Cluster {
3997    /// Index of the glyph that opens it.
3998    glyph: usize,
3999    /// The display column it starts at.
4000    col: usize,
4001    /// How many cells it is drawn in. Zero for a cluster with no width of its
4002    /// own (a lone joiner), which therefore sits at no column at all.
4003    cells: usize,
4004}
4005
4006/// Walk a row's glyphs as the clusters they spell, in column order.
4007fn clusters(glyphs: &[Glyph]) -> Vec<Cluster> {
4008    let text: String = glyphs.iter().map(|g| g.ch).collect();
4009    let mut out = Vec::new();
4010    let (mut glyph, mut col) = (0, 0);
4011    for cluster in text.graphemes(true) {
4012        let cells = text_width(cluster);
4013        out.push(Cluster { glyph, col, cells });
4014        // One glyph per codepoint, so a cluster spans exactly its own.
4015        glyph += cluster.chars().count();
4016        col += cells;
4017    }
4018    out
4019}
4020
4021/// The display width of a run of glyphs.
4022fn glyphs_width(glyphs: &[Glyph]) -> usize {
4023    clusters(glyphs).last().map_or(0, |c| c.col + c.cells)
4024}
4025
4026/// A cell's display width — the widest of its lines, since an in-cell `\n` break
4027/// splits it into several. Sizes the column that must hold every line.
4028fn cell_width(glyphs: &[Glyph]) -> usize {
4029    glyphs
4030        .split(|g| g.ch == '\n')
4031        .map(glyphs_width)
4032        .max()
4033        .unwrap_or(0)
4034}
4035
4036/// Whether a raw inline HTML tag is a line break (`<br>`, `<br/>`, `<br />`,
4037/// case-insensitively) — the one tag a table cell reads as an in-cell break.
4038fn is_br(text: Option<&str>) -> bool {
4039    let Some(t) = text else { return false };
4040    matches!(
4041        t.trim().to_ascii_lowercase().replace(' ', "").as_str(),
4042        "<br>" | "<br/>"
4043    )
4044}
4045
4046impl VRow {
4047    /// The row's width in display columns — and so the column of the caret
4048    /// placed past its last glyph, which is the rightmost column it can occupy.
4049    fn width(&self) -> usize {
4050        glyphs_width(&self.glyphs)
4051    }
4052
4053    /// The display column glyph `i` is drawn at. Glyphs continuing a cluster
4054    /// report the column of the glyph that opened it, since that is where they
4055    /// are drawn; none of them is ever a stop, so no caret is placed by it.
4056    fn col_of_glyph(&self, i: usize) -> usize {
4057        clusters(&self.glyphs)
4058            .iter()
4059            .rev()
4060            .find(|c| c.glyph <= i)
4061            .map_or(0, |c| c.col)
4062    }
4063
4064    /// The glyph drawn at display column `col`, or `None` past the row's last
4065    /// cell.
4066    ///
4067    /// A column landing on the *second* cell of a wide glyph resolves to that
4068    /// glyph: half a character is not a place to be, so clicking either cell of
4069    /// `你` means `你`, and the caret comes to rest at its start — the column it
4070    /// would be drawn at anyway. That rule is what makes the mapping invertible:
4071    /// every offset has one column, and every column has one offset.
4072    fn glyph_at_col(&self, col: usize) -> Option<usize> {
4073        clusters(&self.glyphs)
4074            .into_iter()
4075            .find(|c| col < c.col + c.cells)
4076            .map(|c| c.glyph)
4077    }
4078}
4079
4080// ── helpers ──────────────────────────────────────────────────────────────────
4081
4082/// The caret home inside an *empty* table cell (`col`, 0-based) of a row whose
4083/// source is `row_src` starting at byte `row_start`. twig gives an empty cell no
4084/// `content_span`, so its interior is read from the pipes: cell `col` lies
4085/// between the `col`-th and `col+1`-th unescaped `│`/`|`, and the home is one
4086/// space past the opening one — mimicking the `| ` padding a filled cell has,
4087/// and never at or past the closing pipe. So `|  |  |` gives the two cells
4088/// distinct, editable homes instead of both collapsing onto the row's start.
4089fn empty_cell_offset(row_src: &str, row_start: usize, col: usize) -> usize {
4090    let bytes = row_src.as_bytes();
4091    let mut pipes = Vec::new();
4092    for (i, &b) in bytes.iter().enumerate() {
4093        if b == b'|' && (i == 0 || bytes[i - 1] != b'\\') {
4094            pipes.push(i);
4095        }
4096    }
4097    match (pipes.get(col).copied(), pipes.get(col + 1).copied()) {
4098        (Some(open), Some(close)) => {
4099            let lo = open + 1; // just inside the opening pipe
4100            let hi = close.saturating_sub(1); // just inside the closing pipe
4101            let inside = if hi < lo {
4102                lo
4103            } else {
4104                (open + 2).clamp(lo, hi)
4105            };
4106            row_start + inside
4107        }
4108        (Some(open), None) => row_start + open + 1,
4109        _ => row_start,
4110    }
4111}
4112
4113/// One laid-out table cell: its rendered text, the source range that text
4114/// occupies (`start`/`end` are the caret anchors decoration points at), and the
4115/// column alignment its padding honours.
4116///
4117/// `glyphs` is the cell's inline content *unwrapped* — the box-drawn rows wrap
4118/// it to a column width, but a frontend laying the grid out itself needs the
4119/// text before that decision was made.
4120#[derive(Clone)]
4121pub struct TableCell {
4122    pub glyphs: Vec<Glyph>,
4123    pub start: usize,
4124    pub end: usize,
4125    pub align: Alignment,
4126}
4127
4128/// One row of a table's grid, as the document spells it — not as it's drawn.
4129#[derive(Clone)]
4130pub struct TableRow {
4131    /// A header row: drawn bold, and ruled off from the body below it.
4132    pub head: bool,
4133    pub cells: Vec<TableCell>,
4134}
4135
4136/// A table's structure, published alongside the box-drawn rows that spell it.
4137///
4138/// The rows in [`VisualMap::rows`] are the *default monospace* picture of a
4139/// table: every border a `│`, every column a whole number of character cells.
4140/// That picture is exactly right on any monospace surface, and unfixable off one
4141/// — in a proportional font the `│`s of two rows land at different x and the grid
4142/// shears. So a frontend that draws its own geometry reads this instead: the
4143/// cells, their alignment, and which rows are the head, with no opinion about
4144/// how wide a column is or what a border looks like.
4145///
4146/// Both are always built. The TUI paints `rows` and ignores this; the GUI skips
4147/// `rows` for the span in `rows_span` and draws from here. They describe the
4148/// same cells, so the caret lands on the same offsets either way.
4149#[derive(Clone)]
4150pub struct TableInfo {
4151    /// The `VisualMap::rows` this table's picture occupies, borders included —
4152    /// what a frontend drawing its own table skips over.
4153    pub rows_span: Range<usize>,
4154    /// The source span of the table node, and the offset its trailing caret
4155    /// stop sits at.
4156    pub end_src: usize,
4157    /// The block prefix every row of this table carries — a blockquote's `│ `
4158    /// gutter, a list item's indent. Empty for a table at the top level.
4159    ///
4160    /// A frontend drawing its own grid has to render this and start the table
4161    /// past it, exactly as the picture does; a table nested in a quote that
4162    /// draws flush at the left margin has left the quote.
4163    pub prefix: Vec<Glyph>,
4164    pub grid: Vec<TableRow>,
4165}
4166
4167/// A fenced or indented code block, named by the [`VisualMap::rows`] it occupies.
4168///
4169/// Unlike a table, the rows *are* the block's content — a frontend still paints
4170/// them, it just draws a border and a tinted background around the whole span
4171/// and lets the code inside scroll horizontally instead of wrapping. So this
4172/// carries only the row range; there's no structural alternative to the picture
4173/// the way [`TableInfo`] is one. Derived from [`VRow::code`] — see
4174/// [`code_block_spans`].
4175#[derive(Clone, Debug, PartialEq, Eq)]
4176pub struct CodeBlockInfo {
4177    /// The contiguous run of [`VisualMap::rows`] this code block spans, blank
4178    /// code lines included.
4179    pub rows_span: Range<usize>,
4180    /// The block's language, from a fenced block's info string — what a frontend
4181    /// paints as a small label on the box (`` ```rust `` → `Some("rust")`).
4182    /// `None` for a fence written without one, or an indented block. Editing it
4183    /// goes through [`crate::Doc::set_code_language`], which re-finds the fence
4184    /// in the AST, so this stays a display string.
4185    pub lang: Option<String>,
4186}
4187
4188/// A block-level image (`![alt](url)` on its own line), named by the single
4189/// [`VisualMap::rows`] row it occupies.
4190///
4191/// Like [`CodeBlockInfo`], the row *is* the block's default rendering — a plain
4192/// surface paints the `🖼 alt` placeholder glyphs as-is. An image-capable
4193/// frontend instead **skips the row in `rows_span`** and paints the resolved
4194/// picture there, exactly as it skips a [`TableInfo`]'s box-drawn rows. Derived
4195/// from [`VRow::media`] by [`media_spans`], so it survives the row reuse of
4196/// [`BlockCache`] and [`build_spliced`].
4197#[derive(Clone, Debug, PartialEq, Eq)]
4198pub struct MediaInfo {
4199    /// The [`VisualMap::rows`] rows this media's placeholder occupies — what a
4200    /// capable frontend replaces with the picture or player.
4201    pub rows_span: Range<usize>,
4202    /// Whether this is a picture, a movie, or a sound — which widget the
4203    /// frontend builds over [`rows_span`](MediaInfo::rows_span). A frontend that
4204    /// handles only some kinds leaves the rest as core's placeholder rows, which
4205    /// already read sensibly on their own.
4206    pub kind: MediaKind,
4207    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
4208    /// the AST. A frontend resolves a relative path against the document's own
4209    /// directory; core does no I/O. For a `<picture>` this is the `<img>`
4210    /// fallback — the source used when no [`sources`](MediaInfo::sources) media
4211    /// query matches (or the frontend has no theme). Empty when a `<video>`/
4212    /// `<audio>` carries no `src` and names its candidates in `<source>`s
4213    /// instead; [`resolve`](MediaInfo::resolve) already accounts for that.
4214    pub destination: String,
4215    /// The `<source>` alternatives in document order, or empty for a plain
4216    /// image. See [`MediaSource`]; a theme- or codec-aware frontend picks one and
4217    /// otherwise loads [`destination`](MediaInfo::destination).
4218    pub sources: Vec<MediaSource>,
4219    /// The media's alt text, flattened from its inline children (empty when it
4220    /// has none).
4221    pub alt: String,
4222    /// A `<video poster="…">`'s still frame, or empty when there is none — an
4223    /// image destination, resolved exactly as [`destination`] is.
4224    ///
4225    /// [`destination`]: MediaInfo::destination
4226    pub poster: String,
4227}
4228
4229/// One leaf directive (`::name{…}`) as a frontend sees it: which rows its
4230/// placeholder occupies, its type, and its attributes. A plain surface paints
4231/// the `⧉ name` placeholder glyphs as-is; a frontend that knows the host app's
4232/// vocabulary **skips the rows in `rows_span`** and paints the real thing there,
4233/// exactly as an image-capable one does with [`MediaInfo`]. Derived from
4234/// [`VRow::leaf_directive`] by [`directive_spans`].
4235///
4236/// Core resolves nothing here — it has no idea what an `embed` or a `toc` is,
4237/// and deliberately so: the directive vocabulary belongs to the app on top.
4238#[derive(Clone, Debug, PartialEq, Eq)]
4239pub struct DirectiveInfo {
4240    /// The [`VisualMap::rows`] rows this directive's placeholder occupies — the
4241    /// label row plus any blank fillers under it.
4242    pub rows_span: Range<usize>,
4243    /// The directive's type (`embed`, `toc`, `vis`), no leading colons.
4244    pub name: String,
4245    /// Its `{…}` attributes in source order; a bare one has a `None` value.
4246    pub attrs: Vec<(String, Option<String>)>,
4247    /// Its `[label]` text, flattened from its inline children (empty when it has
4248    /// none) — what the placeholder row shows.
4249    pub label: String,
4250}
4251
4252impl DirectiveInfo {
4253    /// The value of attribute `key`, if it has one with a value. The convenience
4254    /// a frontend reaches for first (`info.attr("src")`), since almost every
4255    /// directive that draws as something real is pointed at by one attribute.
4256    pub fn attr(&self, key: &str) -> Option<&str> {
4257        self.attrs
4258            .iter()
4259            .find(|(k, _)| k == key)
4260            .and_then(|(_, v)| v.as_deref())
4261    }
4262}
4263
4264impl MediaInfo {
4265    /// The image URL to load under `scheme`: the first [`sources`] `<source>`
4266    /// whose media query matches, else the [`destination`] `<img>` fallback. The
4267    /// pick is a `<source>`'s first `srcset` URL or the destination — a frontend
4268    /// resolves whichever it gets against the document directory exactly as it
4269    /// resolves `destination`, and reserves/keys the picture under `destination`
4270    /// regardless, so a theme switch just re-picks without disturbing the layout.
4271    ///
4272    /// Only `prefers-color-scheme` is understood (that's what a light/dark banner
4273    /// uses); a `<source>` with any other media query is skipped, and one with no
4274    /// media at all always matches (an unconditional override). With no matching
4275    /// source — including every frontend that can't/doesn't theme and passes
4276    /// [`ColorScheme::Light`] to a dark-only picture — it's the plain `<img>`.
4277    ///
4278    /// [`sources`]: MediaInfo::sources
4279    /// [`destination`]: MediaInfo::destination
4280    pub fn resolve(&self, scheme: ColorScheme) -> &str {
4281        if let Some(url) = self
4282            .sources
4283            .iter()
4284            .find(|s| media_matches(&s.media, scheme))
4285            .and_then(|s| first_srcset_url(&s.srcset))
4286        {
4287            return url;
4288        }
4289        // A `<video>`/`<audio>` may carry no `src` of its own, naming its
4290        // candidates only in child `<source>`s — none of which matched above,
4291        // because a codec-typed `<source>` has no media query and core judges no
4292        // MIME types. Falling through to an empty destination would hand the
4293        // frontend nothing to load, so take the first candidate URL instead and
4294        // let the frontend reject it if it can't decode it. An `<img>` never
4295        // reaches this: its `src` is the picture.
4296        if self.destination.is_empty()
4297            && let Some(url) = self
4298                .sources
4299                .iter()
4300                .find_map(|s| first_srcset_url(&s.srcset))
4301        {
4302            return url;
4303        }
4304        &self.destination
4305    }
4306
4307    /// The **still picture** that stands for this media under `scheme`, for a
4308    /// frontend that can rasterize an image but not play a movie — a terminal, or
4309    /// a GUI still growing its player. `None` when there is no picture to draw,
4310    /// which is the honest answer for audio and for a poster-less video: the
4311    /// caller leaves core's labelled placeholder row, which already reads as
4312    /// *a thing that isn't text*.
4313    ///
4314    /// This exists so those frontends never hand a `.mp4` to an image decoder.
4315    /// That fails harmlessly today (a failed decode falls back to the same
4316    /// placeholder), but it spends a file read and a decode attempt per frame to
4317    /// arrive where this gets in one match.
4318    pub fn still(&self, scheme: ColorScheme) -> Option<&str> {
4319        match self.kind {
4320            MediaKind::Image => Some(self.resolve(scheme)),
4321            // A `poster` is an image destination, so it resolves the same way —
4322            // but it is named directly and has no `<source>` alternatives of its
4323            // own, so it needs no theme matching.
4324            MediaKind::Video if !self.poster.is_empty() => Some(&self.poster),
4325            MediaKind::Video | MediaKind::Audio => None,
4326        }
4327    }
4328}
4329
4330/// A frontend's active color scheme — what a `<picture>`'s `prefers-color-scheme`
4331/// `<source>`s are matched against by [`MediaInfo::resolve`]. A frontend with no
4332/// notion of theme passes [`Light`](ColorScheme::Light), the web's own default.
4333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4334pub enum ColorScheme {
4335    Light,
4336    Dark,
4337}
4338
4339/// Whether a `<source media="…">` query applies under `scheme`. Empty media is
4340/// an unconditional `<source>` (always matches); otherwise only a
4341/// `prefers-color-scheme: dark|light` feature is understood — anything else
4342/// (a width query, `print`, …) doesn't match, so resolution falls through to the
4343/// next source or the `<img>`. Deliberately lax about the surrounding syntax
4344/// (`(prefers-color-scheme: dark)`, `screen and (prefers-color-scheme:dark)`):
4345/// it keys off the feature and its value, which is all the theme case needs.
4346fn media_matches(media: &str, scheme: ColorScheme) -> bool {
4347    let media = media.trim();
4348    if media.is_empty() {
4349        return true;
4350    }
4351    let lower = media.to_ascii_lowercase();
4352    let Some(after) = lower
4353        .split_once("prefers-color-scheme")
4354        .map(|(_, rest)| rest)
4355    else {
4356        return false;
4357    };
4358    // Skip the `:` and any spaces to reach the value word.
4359    let value = after.trim_start_matches([':', ' ', '\t']);
4360    let wanted = match scheme {
4361        ColorScheme::Light => "light",
4362        ColorScheme::Dark => "dark",
4363    };
4364    value.starts_with(wanted)
4365}
4366
4367/// The first URL in a `srcset`: its first comma-separated candidate, before any
4368/// `1x`/`2x`/width descriptor. The theme case only ever puts one URL per
4369/// `<source>`, so the first candidate is the picture.
4370fn first_srcset_url(srcset: &str) -> Option<&str> {
4371    let first = srcset.split(',').next()?.trim();
4372    first.split_whitespace().next().filter(|u| !u.is_empty())
4373}
4374
4375/// The narrowest a column may be squeezed. Below a few characters a column
4376/// stops carrying text and just shreds it one letter per line, which is worse
4377/// than letting the grid run wide.
4378const MIN_COL_WIDTH: usize = 3;
4379
4380/// Shrink `widths` until the grid fits `avail` screen columns, taking from the
4381/// widest column each time so the loss is shared out rather than falling on
4382/// whichever column happens to be last. No column goes below
4383/// [`MIN_COL_WIDTH`]; a table with more columns than the surface has room for
4384/// still overflows, which is the honest outcome — there's nothing left to give.
4385fn fit_widths(widths: &mut [usize], avail: usize) {
4386    // Chrome: each column is its content plus a gutter either side, and every
4387    // column is closed by a `│` — with one more opening the row.
4388    let budget = avail.saturating_sub(3 * widths.len() + 1);
4389    while widths.iter().sum::<usize>() > budget {
4390        let Some(w) = widths.iter_mut().filter(|w| **w > MIN_COL_WIDTH).max() else {
4391            return;
4392        };
4393        *w -= 1;
4394    }
4395}
4396
4397/// Word-wrap `glyphs` into lines of at most `width` columns, hard-breaking any
4398/// single word too long to fit.
4399///
4400/// Unlike a paragraph — where an overlong word just trails off the end of the
4401/// line — a table column is a hard boundary: a glyph past it lands on top of
4402/// the border, or on the next cell. So the width here is a promise, and a word
4403/// that won't keep it is broken.
4404///
4405/// The space at a break is dropped rather than hung past the edge. Its offset
4406/// isn't lost: the caller gives every line an end stop just past its last
4407/// glyph, which is exactly where that space was.
4408///
4409/// `width` is in display columns, and a break only ever falls between grapheme
4410/// clusters. Both matter to more than the picture: the caller anchors each
4411/// line's end stop just past its last glyph, so a line cut mid-cluster would
4412/// put a caret stop inside a character — reachable by Down or a click, and the
4413/// next Backspace would take the cluster apart from the middle.
4414///
4415/// An explicit in-cell break (a `\n` glyph, from a `<br>`) is a hard boundary:
4416/// each run between the breaks wraps on its own and the results stack. The break
4417/// glyphs are dropped — the caller's per-line end stop already sits exactly where
4418/// each break was, so no offset is lost.
4419fn wrap_glyphs(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
4420    if glyphs.iter().any(|g| g.ch == '\n') {
4421        return glyphs
4422            .split(|g| g.ch == '\n')
4423            .flat_map(|seg| wrap_segment(seg, width))
4424            .collect();
4425    }
4426    wrap_segment(glyphs, width)
4427}
4428
4429/// [`wrap_glyphs`] for a run with no explicit breaks — the word-wrap proper.
4430fn wrap_segment(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
4431    let width = width.max(1);
4432    // Words are maximal non-space runs, each carrying the space that followed it
4433    // — which survives only if the next word joins it on this line.
4434    let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
4435    let mut word: Vec<Glyph> = Vec::new();
4436    for g in glyphs {
4437        if g.ch == ' ' {
4438            words.push((std::mem::take(&mut word), Some(g.clone())));
4439        } else {
4440            word.push(g.clone());
4441        }
4442    }
4443    if !word.is_empty() {
4444        words.push((word, None));
4445    }
4446
4447    let mut lines: Vec<Vec<Glyph>> = Vec::new();
4448    let mut line: Vec<Glyph> = Vec::new();
4449    let mut used = 0usize;
4450    let mut gap: Option<Glyph> = None;
4451    for (word, space) in words {
4452        for chunk in hard_break(&word, width) {
4453            let sep = gap.is_some() as usize;
4454            let cells = glyphs_width(chunk);
4455            if !line.is_empty() && used + sep + cells > width {
4456                lines.push(std::mem::take(&mut line));
4457                used = 0;
4458                gap = None; // the break swallows the space
4459            }
4460            if let Some(sp) = gap.take() {
4461                line.push(sp);
4462                used += 1;
4463            }
4464            line.extend_from_slice(chunk);
4465            used += cells;
4466        }
4467        gap = space;
4468    }
4469    // An empty cell is still one (empty) line — it has an end the caret can
4470    // sit at, which is how you type into it.
4471    if !line.is_empty() || lines.is_empty() {
4472        lines.push(line);
4473    }
4474    lines
4475}
4476
4477/// Break a single word into pieces of at most `width` columns, cutting only
4478/// between grapheme clusters — the replacement for slicing it into fixed runs
4479/// of glyphs, which measures a wide character as one column and can cut an
4480/// emoji in half.
4481///
4482/// A cluster wider than the whole column still gets a piece to itself: there is
4483/// nowhere legal to cut it, and overflowing by a cell is better than splitting a
4484/// character. An empty word yields no pieces at all, which is what keeps a
4485/// double space from opening a line of its own.
4486fn hard_break(word: &[Glyph], width: usize) -> Vec<&[Glyph]> {
4487    let mut out = Vec::new();
4488    if word.is_empty() {
4489        return out;
4490    }
4491    let (mut start, mut used) = (0usize, 0usize);
4492    for c in clusters(word) {
4493        if used > 0 && used + c.cells > width {
4494            out.push(&word[start..c.glyph]);
4495            start = c.glyph;
4496            used = 0;
4497        }
4498        used += c.cells;
4499    }
4500    out.push(&word[start..]);
4501    out
4502}
4503
4504/// A table rule spanning `widths`, e.g. `┌──────┬─────┐`. Each column is its
4505/// content width plus the one-space gutter on either side.
4506fn rule_text(widths: &[usize], left: char, mid: char, right: char) -> String {
4507    let mut s = String::new();
4508    s.push(left);
4509    for (i, w) in widths.iter().enumerate() {
4510        if i > 0 {
4511            s.push(mid);
4512        }
4513        for _ in 0..w + 2 {
4514            s.push('─');
4515        }
4516    }
4517    s.push(right);
4518    s
4519}
4520
4521/// Push real document text: each glyph maps to its own source byte, and the one
4522/// that opens a grapheme cluster is the caret stop for the whole cluster.
4523///
4524/// Per cluster rather than per codepoint because a cluster is the character the
4525/// user sees, and it's the unit backspace and delete already step by. A stop
4526/// inside 👨‍👩‍👧 — five codepoints strung together with joiners — is a caret
4527/// parked in the middle of a character: one press of Right lands there, and the
4528/// next Backspace severs a joiner from what it joined, leaving a dangling ZWJ in
4529/// the source. The rest of the cluster still gets its glyph (it has to be
4530/// drawn); it just isn't somewhere to stand.
4531fn push_text(out: &mut Vec<Glyph>, text: &str, base_src: usize, style: Style) {
4532    for (gi, cluster) in text.grapheme_indices(true) {
4533        for (ci, ch) in cluster.char_indices() {
4534            out.push(Glyph {
4535                ch,
4536                style,
4537                src: base_src + gi + ci,
4538                stop: ci == 0,
4539            });
4540        }
4541    }
4542}
4543
4544/// Emit an inline `str`/`smart_punctuation` run, mapping every visible char back
4545/// to its *true* source byte even when the source carries backslash escapes the
4546/// parsed `text` dropped (`\*` → `*`). The naive `span.start + text_offset`
4547/// mapping [`push_text`] uses drifts by one byte after each escape, so a caret or
4548/// click past an escaped `*` would land on the wrong character; walking the text
4549/// against its source keeps them aligned, and the hidden escape backslash gets no
4550/// glyph of its own (it is a spelling artefact, not something the caret lands on).
4551fn push_escaped_text(
4552    out: &mut Vec<Glyph>,
4553    text: &str,
4554    span: Range<usize>,
4555    source: &str,
4556    style: Style,
4557) {
4558    let end = span.end.min(source.len());
4559    let src = source.get(span.start..end).unwrap_or("");
4560    // Fast path — no dropped bytes, so text and source align 1:1 (the common
4561    // case: prose with no escapes). Byte lengths equal ⇒ no backslash was eaten.
4562    if src.len() == text.len() {
4563        push_text(out, text, span.start, style);
4564        return;
4565    }
4566    // Slow path: some `\` was consumed. Walk char-by-char, skipping a backslash
4567    // in the source exactly when it escapes the next visible char (a real escape),
4568    // never when it is a literal backslash the parse kept (that case has equal
4569    // lengths and takes the fast path above).
4570    let sb = src.as_bytes();
4571    let mut si = 0usize;
4572    'text: for (_, cluster) in text.grapheme_indices(true) {
4573        for (ci, ch) in cluster.char_indices() {
4574            // The text outlasted the source it is being mapped onto. In a
4575            // consistent document that cannot happen on this path: the slow path
4576            // is only entered when the two lengths differ, and everything that
4577            // makes them differ makes the *source* the longer one — an escape
4578            // backslash the parse ate, or source folded into a neighbouring node.
4579            // A `smart_punctuation` node reports its canonical ASCII spelling
4580            // (`--`, `...`, `"`), which is never longer than what was written.
4581            //
4582            // So reaching here means `span` was measured against a document that
4583            // `source` is no longer, and there is no honest offset left to give
4584            // the remaining characters. Stop: the row comes out short, which is
4585            // a wrong picture of a document that is already inconsistent. The
4586            // alternative was `si` stepping past the end and the slice below
4587            // panicking — which is what it did, in a paint loop.
4588            if si >= sb.len() {
4589                break 'text;
4590            }
4591            // Advance to the source character this one came from, stepping over
4592            // whatever the parse dropped on the way. An escape backslash is the
4593            // common case, but not the only one: a span can cover source that
4594            // was folded into a neighbouring node (smart punctuation next to a
4595            // bracket gives `text: "]"` over a source span of `"…]"`). Advancing
4596            // by the *text* character's length assumed escapes were the only
4597            // divergence, so one dropped multi-byte character desynchronized
4598            // every glyph after it — placing `]` inside the `…` before it.
4599            while si < sb.len() && !src[si..].starts_with(ch) {
4600                si += src[si..].chars().next().map_or(1, char::len_utf8);
4601            }
4602            out.push(Glyph {
4603                ch,
4604                style,
4605                src: span.start + si.min(src.len()),
4606                stop: ci == 0,
4607            });
4608            si += src[si..]
4609                .chars()
4610                .next()
4611                .map_or(ch.len_utf8(), char::len_utf8);
4612        }
4613    }
4614}
4615
4616/// Build synthetic decoration glyphs (a bullet, a gutter) all pointing at `src`,
4617/// each carrying `role` so the frontend can style it (`Role::Body` for plain
4618/// padding). Synthetic glyphs are never caret stops — they share one offset, so
4619/// the caret steps over them (a click still lands at `src`).
4620fn synth(text: &str, role: Role, src: usize) -> Vec<Glyph> {
4621    let style = Style::default().role(role);
4622    text.chars()
4623        .map(|ch| Glyph {
4624            ch,
4625            style,
4626            src,
4627            stop: false,
4628        })
4629        .collect()
4630}
4631
4632fn concat(a: &[Glyph], b: &[Glyph]) -> Vec<Glyph> {
4633    let mut v = a.to_vec();
4634    v.extend_from_slice(b);
4635    v
4636}
4637
4638/// The columns a row's prefix (a bullet, a quote gutter, an indent) takes up
4639/// before the text it introduces — what the wrap budget has left to spend.
4640fn prefix_width(prefix: &[Glyph]) -> usize {
4641    glyphs_width(prefix)
4642}
4643
4644/// The label shown for an image with no alt text: the final path segment of its
4645/// destination (`img/cat.png` → `cat.png`), the whole destination when it has no
4646/// separator, and `"image"` when it's empty. A `data:` URI (which has no useful
4647/// tail) shows its scheme so the placeholder isn't a wall of base64.
4648fn media_label(dest: &str) -> String {
4649    if dest.is_empty() {
4650        return "image".to_string();
4651    }
4652    if dest.starts_with("data:") {
4653        return "data:…".to_string();
4654    }
4655    // Trim a query/fragment so a URL's `?v=2#frag` doesn't ride along.
4656    let clean = dest.split(['?', '#']).next().unwrap_or(dest);
4657    let tail = clean
4658        .trim_end_matches('/')
4659        .rsplit(['/', '\\'])
4660        .next()
4661        .unwrap_or(clean);
4662    if tail.is_empty() {
4663        dest.to_string()
4664    } else {
4665        tail.to_string()
4666    }
4667}
4668
4669/// A directive's attributes read as a human label — what a frontend puts on a
4670/// container's tinted panel, and what an attribute-bearing inline directive
4671/// shows in its chip.
4672///
4673/// Reads BOTH conventions diaryx content actually uses: twig's own dot-prefixed
4674/// classes (`{.public .family}`, arriving as one combined `class` attr) and bare
4675/// pandoc-style words with no leading dot (`{public family}` — what
4676/// `diaryx_core::visibility`'s publish-time filter and apps/web's directive
4677/// serializer both write, and which twig parses as one valueless attribute
4678/// each). Reading only `.class` would leave every *existing* diaryx `:::vis{…}`
4679/// block unlabeled. A `key=value` attr is configuration rather than a name, so
4680/// it contributes nothing. `None` when nothing readable is left.
4681fn directive_attr_label(attrs: &[(String, Option<String>)]) -> Option<String> {
4682    let mut parts: Vec<String> = Vec::new();
4683    for (k, v) in attrs {
4684        if k == "class" {
4685            if let Some(v) = v
4686                && !v.is_empty()
4687            {
4688                parts.push(v.clone());
4689            }
4690        } else if v.as_deref().unwrap_or("").is_empty() {
4691            parts.push(k.clone());
4692        }
4693    }
4694    (!parts.is_empty()).then(|| parts.join(" "))
4695}
4696
4697fn heading_style(level: u32) -> Style {
4698    // Just the role — a frontend decides how a heading of this level *looks*
4699    // (the terminal cycles a color and bolds it, the GUI scales the font). The
4700    // author wrote no emphasis here, so core records none. `level as u8` is safe:
4701    // Markdown/Djot cap headings at 6.
4702    Style::default().role(Role::Heading(level.min(255) as u8))
4703}
4704
4705/// Is this `container` node a *directive* (`:::note{…}`, `::embed{…}`,
4706/// `:vis[…]`) rather than an HTML element (`<video>`, `<picture>`, `<div>`)?
4707///
4708/// twig 2.8 folded `div`/`span`/`directive`/`element` into one `container` kind,
4709/// and left nothing that separated them: `kind`, `name` and `directive_form` all
4710/// agree, field for field, on an HTML `<div>` and a Markdown `:::div`. Leaf
4711/// answered it by sniffing the span for whichever of `:` or `<` came first.
4712/// twig 3.0 records the answer at parse time as [`ContainerOrigin`], so this is
4713/// now the parser's own knowledge rather than a guess rebuilt from the bytes it
4714/// consumed.
4715pub(crate) fn container_is_directive(node: &FlatNode) -> bool {
4716    node.origin == Some(ContainerOrigin::Directive)
4717}
4718
4719/// The tag a `container` node carries when it is an HTML element rather than a
4720/// directive — `Some("video")` for a promoted `<video>`, `None` for a `:::note`
4721/// or for any node that is not a container at all.
4722pub(crate) fn element_tag(node: &FlatNode) -> Option<&str> {
4723    (node.origin == Some(ContainerOrigin::Element))
4724        .then_some(node.name.as_deref())
4725        .flatten()
4726}
4727
4728pub(crate) fn is_inline(node: &FlatNode) -> bool {
4729    // A directive is inline only in its `text` form (`:name[label]{…}`); the
4730    // `leaf` and `container` forms are blocks. All three report the same `kind`,
4731    // so the form is the only thing telling them apart — and getting it wrong
4732    // costs a whole paragraph: a text directive misread as a block makes its
4733    // paragraph fail the "all children inline" test in `block`, and the line is
4734    // then walked as a container of blocks, rendering as empty rows with no
4735    // caret home at all.
4736    //
4737    // An HTML element shares the `container` kind but never the `text` form, so
4738    // it answers `false` here and is walked as the block it is.
4739    if node.kind == Kind::Container {
4740        return container_is_directive(node) && node.directive_form == Some(DirectiveForm::Text);
4741    }
4742    is_inline_kind(&node.kind)
4743}
4744
4745/// [`is_inline`] by kind alone — for the ancestor walks, whose `QueryMatch`es
4746/// carry no `directive_form`. It answers `false` for every directive, which its
4747/// callers must (and do) reconcile: they pair it with `is_block_container`,
4748/// which claims every directive, so the pair's verdict is the same one a form
4749/// would have given. Anything looking at a *directive itself* wants [`is_inline`]
4750/// and a real node.
4751pub(crate) fn is_inline_kind(kind: &Kind) -> bool {
4752    matches!(
4753        kind,
4754        Kind::Str
4755            | Kind::SoftBreak
4756            | Kind::HardBreak
4757            | Kind::NonBreakingSpace
4758            | Kind::Emph
4759            | Kind::Strong
4760            | Kind::Mark
4761            | Kind::Insert
4762            | Kind::Delete
4763            | Kind::Verbatim
4764            | Kind::InlineMath
4765            | Kind::DisplayMath
4766            | Kind::Url
4767            | Kind::Email
4768            | Kind::Link
4769            | Kind::Image
4770            | Kind::SmartPunctuation
4771            | Kind::Superscript
4772            | Kind::Subscript
4773            | Kind::FootnoteReference
4774    )
4775}
4776
4777/// Assert two maps are identical down to every glyph, stop, and table span — the
4778/// contract `build_cached` and `build_spliced` must hold against `build`. Lives
4779/// at module scope (not in `mod tests`) so the Doc-driven differential test in
4780/// `doc.rs` can reach it and the private `stops` field it compares.
4781#[cfg(test)]
4782pub(crate) fn assert_maps_eq(a: &VisualMap, b: &VisualMap, ctx: &str) {
4783    assert_eq!(a.rows.len(), b.rows.len(), "row count ({ctx})");
4784    for (i, (ra, rb)) in a.rows.iter().zip(&b.rows).enumerate() {
4785        assert_eq!(ra.end_src, rb.end_src, "row {i} end_src ({ctx})");
4786        assert_eq!(ra.decoration, rb.decoration, "row {i} decoration ({ctx})");
4787        // The incremental walk labels a boundary from a query match's kind
4788        // string and the whole-arena walk from a `FlatNode`'s; this is what says
4789        // the two doors reach the same answer.
4790        assert_eq!(ra.boundary, rb.boundary, "row {i} boundary ({ctx})");
4791        assert_eq!(ra.code, rb.code, "row {i} code ({ctx})");
4792        assert_eq!(ra.code_lang, rb.code_lang, "row {i} code_lang ({ctx})");
4793        assert_eq!(
4794            ra.glyphs.len(),
4795            rb.glyphs.len(),
4796            "row {i} glyph count ({ctx})"
4797        );
4798        for (j, (ga, gb)) in ra.glyphs.iter().zip(&rb.glyphs).enumerate() {
4799            assert_eq!(
4800                (ga.ch, ga.src, ga.stop, ga.style),
4801                (gb.ch, gb.src, gb.stop, gb.style),
4802                "row {i} glyph {j} ({ctx})"
4803            );
4804        }
4805    }
4806    assert_eq!(a.content_start, b.content_start, "content_start ({ctx})");
4807    assert_eq!(a.stops, b.stops, "stops ({ctx})");
4808    assert_eq!(a.tables.len(), b.tables.len(), "table count ({ctx})");
4809    for (i, (ta, tb)) in a.tables.iter().zip(&b.tables).enumerate() {
4810        assert_eq!(ta.rows_span, tb.rows_span, "table {i} rows_span ({ctx})");
4811        assert_eq!(ta.end_src, tb.end_src, "table {i} end_src ({ctx})");
4812    }
4813    assert_eq!(a.code_blocks, b.code_blocks, "code_blocks ({ctx})");
4814    assert_eq!(a.media, b.media, "images ({ctx})");
4815}
4816
4817#[cfg(test)]
4818mod tests {
4819    use super::*;
4820    use twig::{Editor, Format, NodeId};
4821
4822    fn map(src: &str) -> VisualMap {
4823        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
4824        build_t(&ed.nodes().unwrap(), src, Some(80))
4825    }
4826
4827    /// [`map`] over a Djot source. Djot is the format that spells superscript
4828    /// and subscript at all — Markdown has no syntax for either.
4829    fn map_djot(src: &str) -> VisualMap {
4830        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
4831        build_t(&ed.nodes().unwrap(), src, Some(80))
4832    }
4833
4834    /// The baseline every glyph spelling `ch` was built with, in row order —
4835    /// how a test reads a raised or lowered run off the map without caring
4836    /// which row it landed on.
4837    fn baselines_of(m: &VisualMap, ch: char) -> Vec<Baseline> {
4838        m.rows
4839            .iter()
4840            .flat_map(|r| r.glyphs.iter())
4841            .filter(|g| g.ch == ch)
4842            .map(|g| g.style.baseline)
4843            .collect()
4844    }
4845
4846    /// [`map`] at a chosen wrap width.
4847    fn map_at(src: &str, wrap: Option<usize>) -> VisualMap {
4848        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
4849        build_t(&ed.nodes().unwrap(), src, wrap)
4850    }
4851
4852    /// [`map`], but with twig's `directives` extension on (off by twig's own
4853    /// default) — the `:::name{.class}` fenced-div containers leaf-core's
4854    /// `"directive"` wysiwyg arm renders.
4855    fn map_directives(src: &str) -> VisualMap {
4856        let mut ed = Editor::new_ext(
4857            src.as_bytes(),
4858            Format::Markdown,
4859            twig::MarkdownExtensions {
4860                directives: true,
4861                ..Default::default()
4862            },
4863        )
4864        .unwrap();
4865        build_t(&ed.nodes().unwrap(), src, Some(80))
4866    }
4867
4868    /// [`map`] with soft breaks preserved (`LineFlow::Preserve`).
4869    fn map_preserve(src: &str, wrap: Option<usize>) -> VisualMap {
4870        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
4871        build(&ed.nodes().unwrap(), src, wrap, true, &HashMap::new(), None)
4872    }
4873
4874    /// The cache-free reference [`build`], with no per-image height overrides —
4875    /// every block image stays its default one-row placeholder. The tests that
4876    /// need a taller image drive it through [`crate::Doc::set_media_rows`] instead.
4877    fn build_t(nodes: &[FlatNode], src: &str, wrap: Option<usize>) -> VisualMap {
4878        build(nodes, src, wrap, false, &HashMap::new(), None)
4879    }
4880
4881    /// An arena and a string that disagree — spans reaching past the source they
4882    /// are built against.
4883    ///
4884    /// [`crate::Doc`] keeps the two in step, so this is a "cannot happen" that
4885    /// nonetheless *did*: `examples/bench` timed a loop of `edit_range` and then
4886    /// went on handing the grown editor's spans to a builder holding the string
4887    /// from before it, and every run ended in a slice panic rather than a
4888    /// number. `push_escaped_text` was already written to survive the mismatch —
4889    /// it clamps the span's end and falls back to an empty slice — and this is
4890    /// the half of that intent it did not carry through.
4891    ///
4892    /// Rendering the wrong thing is the acceptable answer here; panicking in a
4893    /// paint loop is not.
4894    #[test]
4895    fn a_source_shorter_than_the_arena_built_over_it_renders_rather_than_panicking() {
4896        // An escape puts the run on `push_escaped_text`'s slow path — the fast
4897        // path is a length comparison that a truncated source fails anyway.
4898        let src = "alpha \\*beta\\* gamma delta epsilon\n";
4899        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
4900        let nodes = ed.nodes().unwrap();
4901
4902        // Every truncation of it, so the cut lands before, inside and after the
4903        // escaped run rather than only where one hand-picked index put it.
4904        for cut in 0..=src.len() {
4905            if !src.is_char_boundary(cut) {
4906                continue;
4907            }
4908            let map = build_t(&nodes, &src[..cut], Some(80));
4909            for row in &map.rows {
4910                for g in &row.glyphs {
4911                    assert!(
4912                        g.src <= src.len(),
4913                        "cut {cut}: glyph {:?} points past the source at {}",
4914                        g.ch,
4915                        g.src
4916                    );
4917                }
4918            }
4919        }
4920    }
4921
4922    fn rendered(m: &VisualMap) -> String {
4923        m.rows
4924            .iter()
4925            .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
4926            .collect::<Vec<_>>()
4927            .join("\n")
4928    }
4929
4930    /// Render a source both ways: `build` over the whole marshalled arena (the
4931    /// reference), and `build_cached` driven the way [`crate::Doc`] drives it —
4932    /// top-level blocks from `child_spans`, per-block subtrees on a miss.
4933    fn render_both(
4934        ed: &mut Editor,
4935        src: &str,
4936        wrap: Option<usize>,
4937        cache: &mut BlockCache,
4938    ) -> (VisualMap, VisualMap) {
4939        let all = ed.nodes().unwrap();
4940        let media_rows = HashMap::new();
4941        let plain = build(&all, src, wrap, false, &media_rows, None);
4942        let top = top_blocks(ed);
4943        let cached = build_cached(&top, src, wrap, false, &media_rows, None, cache, |id| {
4944            ed.subtree(NodeId(id)).unwrap_or_default()
4945        });
4946        (plain, cached)
4947    }
4948
4949    /// The whole correctness claim of the block cache: `build_cached` produces a
4950    /// byte-identical map to `build`, on a fresh cache *and* — the case that
4951    /// actually exercises reuse-and-shift plus per-block subtree marshalling — on
4952    /// a warm cache after the source has been edited underneath it.
4953    /// **Every glyph must stand on the character it claims.** A row's source
4954    /// extent is computed from its last glyph's offset, so a glyph carrying an
4955    /// offset that is not its own character's start yields a row end inside a
4956    /// multi-byte character — and every later slice of the source panics on it.
4957    ///
4958    /// Reproduces a real crash from a journal entry: a bracketed elision inside
4959    /// a blockquote (`[…]`) gave the closing bracket a `text` of `"]"` over a
4960    /// source span covering `"…]"`, because the parse folded the ellipsis into a
4961    /// neighbouring node. `push_escaped_text` walked that span assuming a
4962    /// dropped backslash was the only way text and source could diverge, so the
4963    /// `]` landed on the `…`'s first byte:
4964    /// `byte index 1236 is not a char boundary; it is inside '…'`.
4965    #[test]
4966    fn a_glyph_never_lands_inside_the_character_before_it() {
4967        let src = "> engage with it rather than look away. […]\n>\n> The through-line\n";
4968        let vmap = map(src);
4969        for (r, row) in vmap.rows.iter().enumerate() {
4970            assert!(
4971                src.is_char_boundary(row.end_src.min(src.len())),
4972                "row {r} ends at {} — inside a character",
4973                row.end_src
4974            );
4975            for g in &row.glyphs {
4976                assert!(
4977                    src.is_char_boundary(g.src.min(src.len())),
4978                    "row {r} has {:?} at {}, which is inside a character",
4979                    g.ch,
4980                    g.src
4981                );
4982            }
4983        }
4984        // The elision survives, and its bracket sits on the real `]`.
4985        let text: String = vmap
4986            .rows
4987            .iter()
4988            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
4989            .collect();
4990        assert!(text.contains("[…]"), "the elision should render: {text:?}");
4991        let close = vmap
4992            .rows
4993            .iter()
4994            .flat_map(|r| r.glyphs.iter())
4995            .find(|g| g.ch == ']')
4996            .expect("a closing bracket");
4997        assert_eq!(
4998            src[close.src..].chars().next(),
4999            Some(']'),
5000            "the bracket glyph should stand on the source's own `]`"
5001        );
5002    }
5003
5004    #[test]
5005    fn build_cached_matches_build() {
5006        let docs = [
5007            "# Title\n\nThe quick brown fox.\n\nAnother paragraph here.\n",
5008            "## H\n\n- one\n- two\n- three\n\n> a quote\n> continued\n",
5009            "para one\n\n```\ncode\nlines\n```\n\nafter code\n",
5010            "| a | b |\n|---|---|\n| 1 | 2 |\n\ntext after a table\n",
5011            "line\n- \nsetext?\n\nreal para\n\n\n\ntrailing blanks\n",
5012            "> quote with **bold** and a [link](https://x.dev)\n>\n> - item\n> - item2\n\ntail\n",
5013            "intro\n\n![a cat](img/cat.png)\n\nbetween\n\n![](https://x.dev/logo.svg)\n\nend\n",
5014            "- text item\n- ![alt](pic.png)\n- more text\n",
5015            // Footnotes: twig parses each definition as a root beside `doc`, so
5016            // these are the docs where the reference build and the incremental
5017            // one could disagree about what the top-level blocks even are.
5018            "A claim[^1] and another[^src].\n\n[^1]: First note.\n\n[^src]: Second.\n\ntail\n",
5019            "note[^a]\n\n[^a]: body **bold**\n    wrapped on\n    three lines\n\nafter\n",
5020            // No trailing newline. twig closes the document's last block on the
5021            // virtual newline it supplies at EOF, so that block's `span.end` is
5022            // `source.len() + 1` — a range that slices no bytes at all. Keying
5023            // the block cache off such a slice made every last block hash alike;
5024            // see [`block_bytes`].
5025            "# Title\n\nThe quick brown fox.\n\nA tail with no newline",
5026            "A claim[^1] and another[^src].\n\n[^1]: First note.\n[^src]: Second, ending the file.",
5027        ];
5028        for wrap in [None, Some(80usize), Some(20)] {
5029            for src in docs {
5030                let ctx = format!("wrap={wrap:?} src={src:?}");
5031                let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
5032                let mut cache = BlockCache::default();
5033
5034                // 1) Fresh cache equals the cache-free build.
5035                let (plain, cached) = render_both(&mut ed, src, wrap, &mut cache);
5036                assert_maps_eq(&plain, &cached, &format!("fresh {ctx}"));
5037
5038                // 2) Type a char mid-document, reparse, rebuild with the now-warm
5039                //    cache: the edited block is re-marshalled and re-rendered,
5040                //    every block below it is reused shifted, and the result must
5041                //    still match a from-scratch build.
5042                let at = (src.len() / 2..=src.len())
5043                    .find(|&i| src.is_char_boundary(i))
5044                    .unwrap();
5045                ed.edit_range(at, at, "Z").unwrap();
5046                let src2 = ed.source_str().unwrap();
5047                let (plain2, cached2) = render_both(&mut ed, &src2, wrap, &mut cache);
5048                assert_maps_eq(&plain2, &cached2, &format!("after insert {ctx}"));
5049
5050                // 3) Delete it again: offsets shift back the other way, and the
5051                //    warm cache must not hand back stale shifted rows.
5052                ed.edit_range(at, at + 1, "").unwrap();
5053                let src3 = ed.source_str().unwrap();
5054                let (plain3, cached3) = render_both(&mut ed, &src3, wrap, &mut cache);
5055                assert_maps_eq(&plain3, &cached3, &format!("after delete {ctx}"));
5056            }
5057        }
5058    }
5059
5060    /// A document that does not end in a newline is the one place twig hands
5061    /// leaf a top-level span that addresses no source: the last block is closed
5062    /// on the virtual newline the parser supplies at EOF, so its `span.end` is
5063    /// `source.len() + 1`. The block cache keys on the bytes under that span, and
5064    /// reading the out-of-range slice as *no bytes* broke it two ways at once —
5065    /// [`block_bytes`] has the full account. Both ways are checked here, because
5066    /// they fail independently.
5067    #[test]
5068    fn a_block_running_past_the_last_byte_still_keys_the_cache_by_its_own_bytes() {
5069        // One: two overrunning blocks collide. A footnote definition is a root
5070        // beside `doc` that [`top_blocks`] merges into the top level, while the
5071        // `section` above it spans the definition's bytes too — so when the
5072        // definition ends the file, both blocks end past it. The second was
5073        // served the first's rows, and the definition rendered as a copy of the
5074        // heading.
5075        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.";
5076        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
5077        let (plain, cached) = render_both(&mut ed, src, Some(80), &mut BlockCache::default());
5078        assert_maps_eq(&plain, &cached, "a definition ending the file");
5079        let text = rendered(&cached);
5080        assert!(
5081            text.ends_with("[note] A note with a word for a label."),
5082            "the last definition should render itself: {text:?}"
5083        );
5084        assert_eq!(
5085            text.matches("A heading with a reference").count(),
5086            1,
5087            "the heading should render exactly once: {text:?}"
5088        );
5089
5090        // Two: one overrunning block goes stale. Its bytes are its cache key, so
5091        // a block that keeps hashing the same however it is edited is served the
5092        // rows built before the edit — the whole last line frozen as the user
5093        // types in it.
5094        let mut cache = BlockCache::default();
5095        let first = "first para\n\n# A heading\n\nlast para with no newline";
5096        let mut ed = Editor::new_str(first, Format::Djot).unwrap();
5097        let (_, warm) = render_both(&mut ed, first, Some(80), &mut cache);
5098        assert!(rendered(&warm).ends_with("last para with no newline"));
5099
5100        let second = "first para\n\n# A heading\n\nDIFFERENT text without a newline";
5101        let mut ed = Editor::new_str(second, Format::Djot).unwrap();
5102        let (plain, cached) = render_both(&mut ed, second, Some(80), &mut cache);
5103        assert_maps_eq(&plain, &cached, "edited last block, warm cache");
5104        let text = rendered(&cached);
5105        assert!(
5106            text.ends_with("DIFFERENT text without a newline"),
5107            "the warm cache served the pre-edit rows: {text:?}"
5108        );
5109    }
5110
5111    #[test]
5112    fn resolves_markup_to_plain_text() {
5113        let text = rendered(&map("# Title\n\na **bold** word\n"));
5114        assert!(!text.contains('#'), "heading marker shown: {text:?}");
5115        assert!(!text.contains("**"), "strong delimiters shown: {text:?}");
5116        assert!(text.contains("Title") && text.contains("bold word"));
5117    }
5118
5119    #[test]
5120    fn every_glyph_points_at_its_source_byte() {
5121        let src = "a **bold** c\n";
5122        let m = map(src);
5123        for row in &m.rows {
5124            for g in &row.glyphs {
5125                // A real (non-synthetic) glyph's source byte is the glyph's char.
5126                if g.src < src.len()
5127                    && src.is_char_boundary(g.src)
5128                    && let Some(sc) = src[g.src..].chars().next()
5129                    && sc == g.ch
5130                {
5131                    continue;
5132                }
5133                // Synthetic prefixes (none here) would be the only exceptions.
5134                panic!("glyph {:?} at src {} doesn't match source", g.ch, g.src);
5135            }
5136        }
5137    }
5138
5139    #[test]
5140    fn offset_and_position_round_trip_on_visible_text() {
5141        let m = map("hello world\n");
5142        let (r, c) = m.pos_of_offset(6); // the 'w'
5143        assert_eq!(m.offset_of_pos(r, c), 6);
5144    }
5145
5146    #[test]
5147    fn visible_utf16_indices_count_the_text_the_system_sees() {
5148        // Hidden delimiters, a two-unit emoji, and a block gap — every way the
5149        // visible text's UTF-16 length parts company with a source byte count.
5150        let src = "a **b\u{1F600}** c\n\nd\n";
5151        let m = map(src);
5152        let end = m.snap_to_stop(src.len());
5153        let text = m.visible_text(0, end);
5154        assert_eq!(text, "a b\u{1F600} c\nd");
5155
5156        // Forward: the index of each offset is where that character sits in
5157        // the visible string, in UTF-16 units.
5158        for (i, (src_off, _)) in m.visible_items(0, end).iter().enumerate() {
5159            let expect: usize = text.chars().take(i).map(char::len_utf16).sum();
5160            assert_eq!(
5161                m.visible_utf16_len(0, *src_off),
5162                expect,
5163                "utf16 index of source offset {src_off}"
5164            );
5165            // And back: the index resolves to the offset it came from.
5166            assert_eq!(m.offset_at_visible_utf16(end, expect), Some(*src_off));
5167        }
5168        // Inside the emoji's surrogate pair resolves to the emoji.
5169        let emoji_src = src.find('\u{1F600}').unwrap();
5170        let emoji_idx = m.visible_utf16_len(0, emoji_src);
5171        assert_eq!(
5172            m.offset_at_visible_utf16(end, emoji_idx + 1),
5173            Some(emoji_src)
5174        );
5175        // At or past the end is nobody's character.
5176        let total = m.visible_utf16_len(0, end);
5177        assert_eq!(total, text.encode_utf16().count());
5178        assert_eq!(m.offset_at_visible_utf16(end, total), None);
5179    }
5180
5181    #[test]
5182    fn unwrapped_mode_emits_one_row_per_paragraph() {
5183        // A long paragraph that would wrap under a column budget stays a single
5184        // row when wrap is None (the GUI wraps it at pixel width instead).
5185        let long = "one two three four five six seven eight nine ten eleven twelve\n";
5186        let mut ed = Editor::new_str(long, Format::Markdown).unwrap();
5187        let wrapped = build_t(&ed.nodes().unwrap(), long, Some(12));
5188        let unwrapped = build_t(&ed.nodes().unwrap(), long, None);
5189        assert!(wrapped.num_rows() > 1, "narrow column should wrap");
5190        assert_eq!(unwrapped.num_rows(), 1, "no budget should keep it one row");
5191        // Every glyph's source byte is preserved in the single row.
5192        let text: String = unwrapped.rows[0].glyphs.iter().map(|g| g.ch).collect();
5193        assert_eq!(text.trim_end(), long.trim_end());
5194    }
5195
5196    fn line_texts(m: &VisualMap) -> Vec<String> {
5197        m.rows
5198            .iter()
5199            .map(|r| {
5200                // Trim the trailing whitespace a row may carry — the zero-width
5201                // '\n' that closes a preserved line, and any space glyph left at
5202                // a wrap boundary (both real caret stops, neither visible text).
5203                r.glyphs
5204                    .iter()
5205                    .map(|g| g.ch)
5206                    .collect::<String>()
5207                    .trim_end()
5208                    .to_string()
5209            })
5210            .collect()
5211    }
5212
5213    #[test]
5214    fn preserve_lays_each_soft_break_on_its_own_row() {
5215        // A soft break (a bare newline inside a paragraph) folds into a space by
5216        // default — the whole paragraph is one reflowed row...
5217        let src = "one two\nthree four\n";
5218        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
5219        let folded = build_t(&ed.nodes().unwrap(), src, None);
5220        assert_eq!(folded.num_rows(), 1, "fold: one reflowed row");
5221        assert_eq!(
5222            line_texts(&folded),
5223            vec!["one two three four"],
5224            "break folded to a space"
5225        );
5226
5227        // ...and under Preserve it renders where it was written, a row per line.
5228        let kept = map_preserve(src, None);
5229        assert_eq!(
5230            line_texts(&kept),
5231            vec!["one two", "three four"],
5232            "preserve: a row per line"
5233        );
5234    }
5235
5236    #[test]
5237    fn a_preserved_break_keeps_the_newline_offset_as_a_caret_stop() {
5238        // The break must leave a caret stop at the newline byte, or the caret
5239        // could not rest at the end of the first line. The '\n' glyph is dropped
5240        // from the row (so nothing stray renders); its offset (7 here) becomes the
5241        // row's end stop instead — the same offset the folded space would carry.
5242        let src = "one two\nthree four\n";
5243        let m = map_preserve(src, None);
5244        assert!(
5245            !m.rows[0].glyphs.iter().any(|g| g.ch == '\n'),
5246            "the break glyph is dropped"
5247        );
5248        assert_eq!(
5249            m.rows[0].end_src, 7,
5250            "the first row ends at the newline byte"
5251        );
5252        assert!(m.is_stop(7), "the newline offset is a caret stop");
5253        // Row end offsets stay strictly ascending — no two rows pin one offset.
5254        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
5255        assert!(
5256            offs.windows(2).all(|w| w[0] < w[1]),
5257            "offsets not unique: {offs:?}"
5258        );
5259    }
5260
5261    #[test]
5262    fn preserved_lines_wrap_independently() {
5263        // Each preserved line wraps to the column on its own; the break between
5264        // them is hard, so a word never crosses it — "gamma" and "delta" could
5265        // share a row on width alone but the soft break keeps them apart.
5266        let src = "alpha beta gamma\ndelta epsilon\n";
5267        let m = map_preserve(src, Some(12));
5268        assert_eq!(
5269            line_texts(&m),
5270            vec!["alpha beta", "gamma", "delta", "epsilon"],
5271            "each source line wraps on its own"
5272        );
5273    }
5274
5275    #[test]
5276    fn an_empty_paragraph_between_blocks_renders_its_own_rows() {
5277        // "A", then two blank lines (an empty paragraph opened with Enter), then
5278        // "B": the empty paragraph must be navigable rows, not collapsed onto B.
5279        // Rows: "A", spacer, empty-paragraph, spacer, "B" — each blank row a
5280        // distinct source offset.
5281        let m = map("A\n\n\n\nB\n");
5282        let text: Vec<String> = m
5283            .rows
5284            .iter()
5285            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
5286            .collect();
5287        assert_eq!(text, vec!["A", "", "", "", "B"], "got {text:?}");
5288        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
5289        // Strictly ascending — no two rows share an offset (else the caret pins).
5290        assert!(
5291            offs.windows(2).all(|w| w[0] < w[1]),
5292            "offsets not unique: {offs:?}"
5293        );
5294    }
5295
5296    #[test]
5297    fn a_tight_block_boundary_still_gets_one_separator() {
5298        // A heading directly above text (no blank line between) keeps the single
5299        // conventional separator row, as before.
5300        let m = map("# H\ntext\n");
5301        let text: Vec<String> = m
5302            .rows
5303            .iter()
5304            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
5305            .collect();
5306        assert_eq!(text, vec!["H", "", "text"], "got {text:?}");
5307    }
5308
5309    #[test]
5310    fn an_escaped_delimiter_renders_without_its_backslash_and_maps_true_offsets() {
5311        // `a\*b` renders the three visible chars `a * b` — the escape backslash
5312        // is hidden — and every glyph points at its real source byte, so a caret
5313        // past the escape lands right (the `*` at source 2, `b` at source 3, not
5314        // the drifted 1/2 the naive text-offset mapping gave).
5315        let m = map("a\\*b\n");
5316        let row: Vec<(char, usize)> = m.rows[0].glyphs.iter().map(|g| (g.ch, g.src)).collect();
5317        assert_eq!(row, vec![('a', 0), ('*', 2), ('b', 3)], "got {row:?}");
5318    }
5319
5320    #[test]
5321    fn an_escaped_hash_stays_a_paragraph_and_shows_the_hash() {
5322        // `\# hi` is a paragraph beginning with a literal `#`, not a heading —
5323        // the backslash is hidden, the `#` shown at its true offset.
5324        let m = map("\\# hi\n");
5325        let text: String = m.rows[0].glyphs.iter().map(|g| g.ch).collect();
5326        assert_eq!(text, "# hi");
5327        assert_eq!(
5328            m.rows[0].glyphs[0].src, 1,
5329            "the # is at source byte 1, past the \\"
5330        );
5331    }
5332
5333    #[test]
5334    fn a_tight_nested_list_hangs_its_sublist_directly_under_the_item() {
5335        // A list item's own text and the sub-list nested under it are written on
5336        // adjacent source lines, so the rich view butts them together — no
5337        // fabricated blank row. Regression: the synthetic "breathe" separator
5338        // used to open a gap between `• a` and its `  • b`.
5339        assert_eq!(rendered(&map("- a\n  - b\n")), "• a\n  • b");
5340    }
5341
5342    #[test]
5343    fn a_loose_nested_list_keeps_its_real_blank_line() {
5344        // A genuine blank source line (a loose list) still parts the item from
5345        // its sub-list — only the *fabricated* separator is suppressed, never a
5346        // real one the author typed. The gap row wears the item's continuation
5347        // prefix (the two-space indent), so it renders as "  ", not empty.
5348        assert_eq!(rendered(&map("- a\n\n  - b\n")), "• a\n  \n  • b");
5349    }
5350
5351    #[test]
5352    fn frontmatter_is_hidden_and_the_document_opens_into_its_content() {
5353        // Leading YAML frontmatter renders nothing — no phantom blank rows for
5354        // its lines, no leading gap — and `content_start` points at the first
5355        // real block so the caret floor can keep out of the hidden metadata.
5356        let fm = "---\nconfig: prov.yaml\ncontents:\n- '[Sample](sample.md)'\n---\n";
5357        let src = format!("{fm}# leaf\n\nA line.\n");
5358        let m = map(&src);
5359        let text = rendered(&m);
5360        assert!(
5361            !text.contains("config"),
5362            "frontmatter body leaked: {text:?}"
5363        );
5364        assert!(!text.contains("prov"), "frontmatter body leaked: {text:?}");
5365        assert_eq!(
5366            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
5367            "leaf"
5368        );
5369        assert_eq!(
5370            m.content_start,
5371            fm.len(),
5372            "floor should be the first real block"
5373        );
5374    }
5375
5376    #[test]
5377    fn a_frontmatter_only_document_puts_the_floor_after_the_frontmatter() {
5378        // Nothing to render, so the caret floor is the end of the hidden
5379        // frontmatter — not 0, which is *before* the opening `---` and made the
5380        // first keystroke in a fresh metadata-only note land ahead of it. And
5381        // the frontmatter's own newlines are not trailing blank lines: they used
5382        // to open phantom rows at offsets 1..4, inside the metadata.
5383        let src = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
5384        let m = map(src);
5385        assert_eq!(m.content_start, src.len(), "floor must clear the metadata");
5386        assert!(
5387            m.rows.is_empty(),
5388            "frontmatter must render no rows: {:?}",
5389            rendered(&m)
5390        );
5391        assert!(
5392            m.stops.is_empty(),
5393            "no stop may sit inside the metadata: {:?}",
5394            m.stops
5395        );
5396    }
5397
5398    #[test]
5399    fn a_frontmatter_only_document_still_counts_its_real_blank_lines() {
5400        // Two blank lines after the frontmatter are the author's empty paragraph
5401        // and still render, counted from the metadata's end rather than from 0.
5402        let fm = "---\ntitle: n\n---\n";
5403        let m = map(&format!("{fm}\n\n"));
5404        assert_eq!(m.content_start, fm.len());
5405        assert_eq!(m.rows.len(), 2, "the two trailing newlines each open a row");
5406        assert!(
5407            m.rows.iter().all(|r| r.end_src > fm.len()),
5408            "rows must sit past the frontmatter"
5409        );
5410    }
5411
5412    #[test]
5413    fn a_document_without_frontmatter_has_a_zero_floor() {
5414        let m = map("# leaf\n\nbody\n");
5415        assert_eq!(m.content_start, 0);
5416    }
5417
5418    #[test]
5419    fn trailing_spaces_become_caret_stops_so_the_caret_can_be_drawn_past_them() {
5420        // Markdown/Djot drop the trailing space in `hello ` from the `str` node,
5421        // so without help the row would end at `hello` and the caret couldn't be
5422        // drawn past column 5 — typing a space at a line's end wouldn't move it
5423        // on screen until the next visible character reparsed the space into an
5424        // interior node. The builder recovers it from the block's span/content_span
5425        // gap and emits it as a real, caret-stoppable glyph.
5426        let m = map("hello \n");
5427        assert_eq!(
5428            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
5429            "hello "
5430        );
5431        assert_eq!(
5432            m.rows[0].end_src, 6,
5433            "the row now ends past the trailing space"
5434        );
5435        // The caret can rest both on and past the space.
5436        assert_eq!(m.pos_of_offset(5), (0, 5), "between 'o' and the space");
5437        assert_eq!(m.pos_of_offset(6), (0, 6), "past the space");
5438        // Two trailing spaces, both stops.
5439        let m = map("hello  \n");
5440        assert_eq!(
5441            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
5442            "hello  "
5443        );
5444        assert_eq!(m.pos_of_offset(7), (0, 7));
5445    }
5446
5447    #[test]
5448    fn a_headings_trailing_space_is_a_caret_stop_too() {
5449        // The hidden `# ` marker means `# hi ` renders as `hi ` in three columns;
5450        // the caret past the trailing space lands on the third.
5451        let m = map("# hi \n");
5452        assert_eq!(
5453            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
5454            "hi "
5455        );
5456        assert_eq!(m.pos_of_offset(5), (0, 3));
5457    }
5458
5459    #[test]
5460    fn a_table_cells_trailing_padding_is_not_mistaken_for_block_trailing_space() {
5461        // A cell's own `span` is the whole row, so the trailing-whitespace
5462        // recovery must not run for cells or it would swallow the `│` delimiters
5463        // and neighbours between the cell text and the row's end. The grid stays
5464        // exactly as before.
5465        let text = rendered(&map(TABLE));
5466        assert!(
5467            text.contains("│ Pear │   3 │"),
5468            "cell padding disturbed:\n{text}"
5469        );
5470    }
5471
5472    #[test]
5473    fn a_click_below_the_last_row_lands_on_the_last_stop_not_offset_zero() {
5474        // A drag into the empty space under a short document used to resolve to
5475        // offset 0 — the wrong direction, and not even a caret stop when the
5476        // document opens on hidden frontmatter (its `content_start` floor is not
5477        // a stop), which crashed the caret invariant. It now lands on the last
5478        // stop: the end of the document, where dragging downward should reach.
5479        let fm = "---\ntitle: n\n---\n";
5480        let m = map(&format!("{fm}# Hi\n\nbody\n"));
5481        let below = m.num_rows() + 5;
5482        let off = m.offset_of_pos(below, 0);
5483        assert!(
5484            m.is_stop(off),
5485            "offset {off} from a below-content click is not a stop"
5486        );
5487        assert_eq!(
5488            off,
5489            m.stops.last().copied().unwrap(),
5490            "should be the document's last stop"
5491        );
5492        assert!(
5493            off > fm.len(),
5494            "must not fall onto the hidden frontmatter floor"
5495        );
5496    }
5497
5498    #[test]
5499    fn offset_of_pos_is_a_stop_for_every_row_including_past_the_end() {
5500        // The invariant the caret motion asserts: whatever cell a click names,
5501        // the offset it resolves to is one the caret can actually rest at.
5502        for src in [
5503            "hello \n",
5504            "# A heading here \n\nbody text goes on \n",
5505            "---\nk: v\n---\n# Title\n\nprose here that wraps a bit \n",
5506        ] {
5507            let m = map(src);
5508            for row in 0..m.num_rows() + 3 {
5509                for col in 0..30 {
5510                    let off = m.offset_of_pos(row, col);
5511                    assert!(
5512                        m.is_stop(off),
5513                        "row {row} col {col} → {off} is not a stop in {src:?}"
5514                    );
5515                }
5516            }
5517        }
5518    }
5519
5520    /// `| Name | Qty |` with Name left-aligned and Qty right-aligned.
5521    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
5522
5523    #[test]
5524    fn a_table_renders_as_an_aligned_grid() {
5525        let text = rendered(&map(TABLE));
5526        assert_eq!(
5527            text,
5528            "┌──────┬─────┐\n\
5529             │ Name │ Qty │\n\
5530             ├──────┼─────┤\n\
5531             │ Pear │   3 │\n\
5532             │ Fig  │  12 │\n\
5533             └──────┴─────┘",
5534            "got:\n{text}"
5535        );
5536    }
5537
5538    #[test]
5539    fn table_columns_honour_their_alignment() {
5540        // Centre and default(left) come straight from twig's cell.alignment —
5541        // the delimiter row it's spelled in is consumed and has no node.
5542        let text = rendered(&map("| A | Bee |\n| --- | :---: |\n| x | y |\n"));
5543        assert!(text.contains("│ x │  y  │"), "centred column: {text:?}");
5544    }
5545
5546    #[test]
5547    fn table_borders_are_decoration_the_caret_never_lands_on() {
5548        let m = map(TABLE);
5549        // The rules are whole decoration rows.
5550        for r in [0, 2, 5] {
5551            assert!(m.rows[r].decoration, "row {r} should be a decoration rule");
5552            assert!(
5553                !m.rows[r].glyphs.iter().any(|g| g.stop),
5554                "row {r} has a stop"
5555            );
5556        }
5557        // A content row's `│` and padding are decoration; only the cell text
5558        // and each cell's one end-stop are stops.
5559        let header = &m.rows[1];
5560        assert!(!header.decoration);
5561        for g in &header.glyphs {
5562            if g.ch == '│' {
5563                assert!(!g.stop, "a border is not a caret stop");
5564            }
5565        }
5566        let stops: String = header
5567            .glyphs
5568            .iter()
5569            .filter(|g| g.stop)
5570            .map(|g| g.ch)
5571            .collect();
5572        assert_eq!(stops, "Name Qty ", "cell text plus one end-stop space each");
5573    }
5574
5575    #[test]
5576    fn a_cell_maps_to_its_own_source_text() {
5577        let m = map(TABLE);
5578        // "Pear" starts at byte 32 in TABLE; the caret there draws on the 'P'.
5579        let pear = TABLE.find("Pear").unwrap();
5580        let (r, c) = m.pos_of_offset(pear);
5581        assert_eq!(m.rows[r].glyphs[c].ch, 'P');
5582        assert_eq!(m.offset_of_pos(r, c), pear, "round trips");
5583    }
5584
5585    #[test]
5586    fn a_wide_table_is_cut_to_fit_and_its_cells_wrap() {
5587        // Columns wider than the surface used to run off the right edge, where
5588        // nothing could reach them. They're cut to the budget instead, and the
5589        // text wraps down inside the column — the header rule stays put, and
5590        // an alignment holds on every line of a wrapped cell, not just the first.
5591        let src = "| Ingredient | Notes |\n|---|---:|\n\
5592                   | flour milled coarse | sift it twice |\n| salt | a pinch |\n";
5593        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
5594        let m = build_t(&ed.nodes().unwrap(), src, Some(30));
5595        let text = rendered(&m);
5596        assert_eq!(
5597            text,
5598            "┌──────────────┬─────────────┐\n\
5599             │ Ingredient   │       Notes │\n\
5600             ├──────────────┼─────────────┤\n\
5601             │ flour milled │     sift it │\n\
5602             │ coarse       │       twice │\n\
5603             │ salt         │     a pinch │\n\
5604             └──────────────┴─────────────┘",
5605            "got:\n{text}"
5606        );
5607        for (r, row) in m.rows.iter().enumerate() {
5608            assert!(
5609                row.glyphs.len() <= 30,
5610                "row {r} overflows: {}",
5611                row.glyphs.len()
5612            );
5613        }
5614    }
5615
5616    #[test]
5617    fn a_column_too_narrow_for_a_word_breaks_it_rather_than_spilling() {
5618        // A paragraph lets an overlong word trail off the end of the line; a
5619        // table column can't — a glyph past the border lands on the border.
5620        let src = "| A | B |\n|---|---|\n| antidisestablishmentarianism | x |\n";
5621        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
5622        let m = build_t(&ed.nodes().unwrap(), src, Some(20));
5623        for (r, row) in m.rows.iter().enumerate() {
5624            assert!(
5625                row.glyphs.len() <= 20,
5626                "row {r} overflows: {}",
5627                row.glyphs.len()
5628            );
5629        }
5630        // Broken across lines, but whole: every letter is still drawn, at its
5631        // own source byte, where the caret can reach it.
5632        let word = "antidisestablishmentarianism";
5633        let at = src.find(word).unwrap();
5634        for (i, ch) in word.char_indices() {
5635            assert!(
5636                m.rows
5637                    .iter()
5638                    .flat_map(|r| r.glyphs.iter())
5639                    .any(|g| g.stop && g.src == at + i && g.ch == ch),
5640                "{ch:?} at {} was lost to the break",
5641                at + i
5642            );
5643        }
5644    }
5645
5646    #[test]
5647    fn a_code_block_maps_each_line_to_its_own_source_text() {
5648        // Every glyph used to point at the block's start, which made the whole
5649        // block one offset — visible, but impossible to put a caret inside.
5650        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
5651        let m = map(src);
5652        for row in &m.rows {
5653            for g in row.glyphs.iter().filter(|g| g.stop) {
5654                assert_eq!(
5655                    src[g.src..].chars().next(),
5656                    Some(g.ch),
5657                    "glyph {:?} at {} isn't the source byte it claims",
5658                    g.ch,
5659                    g.src
5660                );
5661            }
5662        }
5663    }
5664
5665    #[test]
5666    fn an_indented_code_block_maps_past_its_stripped_indent() {
5667        // twig strips the four-space indent, so `text` isn't a source slice and
5668        // the lines have to be re-found. Offsets land on the code, not the indent.
5669        let src = "    indented\n    code\n";
5670        let m = map(src);
5671        let stops: Vec<(char, usize)> = m
5672            .rows
5673            .iter()
5674            .flat_map(|r| r.glyphs.iter().filter(|g| g.stop).map(|g| (g.ch, g.src)))
5675            .collect();
5676        assert_eq!(
5677            stops[0],
5678            ('i', 4),
5679            "first line should start past the indent"
5680        );
5681        assert!(
5682            stops.contains(&('c', 17)),
5683            "second line misplaced: {stops:?}"
5684        );
5685    }
5686
5687    #[test]
5688    fn a_fenced_block_whose_code_echoes_its_info_string_maps_to_the_code() {
5689        // The one case that defeats a forward search: the opening fence
5690        // ```` ```rust ```` ends with the same text as the code under it.
5691        let src = "```rust\nrust\n```\n";
5692        let m = map(src);
5693        let first = m.rows[0].glyphs.iter().find(|g| g.stop).unwrap();
5694        assert_eq!(first.src, 8, "matched the info string, not the code");
5695    }
5696
5697    #[test]
5698    fn a_code_block_carries_no_gutter_and_is_published_as_a_row_span() {
5699        // The old `▏ ` gutter is gone: a code row is the block prefix (none, at
5700        // the top level) plus the code text, and the whole run is named in
5701        // `code_blocks` so a frontend can box it.
5702        let src = "para\n\n```\ncode\nlines\n```\n\nafter\n";
5703        let m = map(src);
5704        assert_eq!(m.code_blocks.len(), 1, "one code block");
5705        let span = m.code_blocks[0].rows_span.clone();
5706        let rows: Vec<String> = m.rows[span.clone()]
5707            .iter()
5708            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
5709            .collect();
5710        assert_eq!(rows, vec!["code".to_string(), "lines".to_string()]);
5711        assert!(!rendered(&m).contains('▏'), "gutter still drawn");
5712        assert!(
5713            m.rows[span].iter().all(|r| r.code),
5714            "every row in the span is flagged code"
5715        );
5716    }
5717
5718    #[test]
5719    fn a_directive_container_is_tinted_and_labeled_on_its_first_row() {
5720        // diaryx's `:::vis{.public .family}` visibility block, and any other
5721        // `:::name{.class}` fenced div — core is agnostic of `name`.
5722        let src = ":::vis{.public .family}\nhello\n\nworld\n:::\nafter\n";
5723        let m = map_directives(src);
5724
5725        let content_rows: Vec<usize> = (0..m.rows.len()).filter(|&i| m.rows[i].directive).collect();
5726        assert!(!content_rows.is_empty(), "some row is flagged directive");
5727
5728        let after_rows: Vec<usize> = (0..m.rows.len())
5729            .filter(|&i| !content_rows.contains(&i) && !m.rows[i].glyphs.is_empty())
5730            .collect();
5731        assert!(
5732            after_rows.iter().all(|&i| !m.rows[i].directive),
5733            "content outside the fence isn't tinted"
5734        );
5735
5736        let labels: Vec<&str> = content_rows
5737            .iter()
5738            .filter_map(|&i| m.rows[i].directive_label.as_deref())
5739            .collect();
5740        assert_eq!(
5741            labels,
5742            vec!["public family"],
5743            "only the first row carries the label"
5744        );
5745
5746        assert_eq!(
5747            rendered(&m)
5748                .lines()
5749                .filter(|l| !l.is_empty())
5750                .collect::<Vec<_>>(),
5751            vec!["hello", "world", "after"],
5752            "fence markers don't leak into the rendered text"
5753        );
5754    }
5755
5756    #[test]
5757    fn a_bare_word_directive_is_labeled_same_as_dot_classes() {
5758        // diaryx_core::visibility's own `:::vis{public family}` — no leading
5759        // dots — is what apps/web's directive serializer and the native
5760        // publish-time filter both actually write today, distinct from twig's
5761        // `.class` convention. Both must label the same way so every existing
5762        // diaryx `:::vis{...}` block reads, not just newly dot-authored ones.
5763        let src = ":::vis{public family}\nhello\n:::\n";
5764        let m = map_directives(src);
5765        let label = m.rows.iter().find_map(|r| r.directive_label.clone());
5766        assert_eq!(label.as_deref(), Some("public family"));
5767    }
5768
5769    #[test]
5770    fn a_text_directive_keeps_its_paragraph_visible() {
5771        // Regression: an inline `:name[label]{…}` used to make its paragraph
5772        // fail the "all children inline" test, so the whole line was walked as
5773        // a container of blocks and rendered as empty rows with NO caret stops —
5774        // the text vanished from the editor and the caret couldn't enter it.
5775        // diaryx's inline `:vis[…]` is exactly this shape.
5776        let src = "Text with :abbr[HTML]{title=\"HyperText\"} inline.\n";
5777        let m = map_directives(src);
5778        assert_eq!(rendered(&m).trim_end(), "Text with HTML inline.");
5779        // Every character of the line is a caret home, markup excluded — the
5780        // label reads as ordinary text, the way a link's does.
5781        let stops: usize = m
5782            .rows
5783            .iter()
5784            .map(|r| r.glyphs.iter().filter(|g| g.stop).count())
5785            .sum();
5786        assert_eq!(stops, "Text with HTML inline.".chars().count());
5787        // It is inline, so it is not the container form's tinted panel.
5788        assert!(m.rows.iter().all(|r| !r.directive));
5789    }
5790
5791    #[test]
5792    fn a_text_directives_label_maps_to_its_true_source_bytes() {
5793        // Regression (needs twig-doc >= 2.5.0): twig parses a `[label]` as a
5794        // detached slice, and until it rebased the enclosing scan's segments
5795        // onto it every node inside the label reported a span of `(0,0)`. Read
5796        // by anything that trusts a span that means "byte 0", so the label's
5797        // glyphs mapped to the START OF THE DOCUMENT — a click on the label put
5798        // the caret at the top of the file, its stops collided with the real
5799        // first line's, and an edit there landed on the wrong bytes entirely.
5800        //
5801        // The sibling test `a_text_directive_keeps_its_paragraph_visible` only
5802        // counts stops, which is exactly why this went unnoticed: the right
5803        // NUMBER of stops at completely wrong offsets.
5804        let src = "x :abbr[HTML]{title=\"y\"} z\n";
5805        let m = map_directives(src);
5806        let stops: Vec<(char, usize)> = m
5807            .rows
5808            .iter()
5809            .flat_map(|r| &r.glyphs)
5810            .filter(|g| g.stop)
5811            .map(|g| (g.ch, g.src))
5812            .collect();
5813        // `HTML` sits at 8..12. The name, brackets and `{…}` are hidden markup
5814        // the caret steps over, so the line's stops run 0, 1, 8..12, then 24.
5815        assert_eq!(
5816            stops,
5817            [
5818                ('x', 0),
5819                (' ', 1),
5820                ('H', 8),
5821                ('T', 9),
5822                ('M', 10),
5823                ('L', 11),
5824                (' ', 24),
5825                ('z', 25)
5826            ]
5827        );
5828    }
5829
5830    #[test]
5831    fn every_glyph_in_a_directive_label_points_at_its_source_byte() {
5832        // The `every_glyph_points_at_its_source_byte` invariant, extended over
5833        // directive labels now that their offsets are real. Nested markup is
5834        // included: its delimiters are hidden, so the visible glyphs must skip
5835        // them and still name their own bytes.
5836        let src = "x :abbr[a *b* c] y and :vis[family only] z\n";
5837        let m = map_directives(src);
5838        for g in m.rows.iter().flat_map(|r| &r.glyphs).filter(|g| g.stop) {
5839            let at = src[g.src..].chars().next();
5840            assert_eq!(
5841                at,
5842                Some(g.ch),
5843                "glyph {:?} claims byte {}, which is {at:?}",
5844                g.ch,
5845                g.src
5846            );
5847        }
5848        assert_eq!(rendered(&m).trim_end(), "x a b c y and family only z");
5849    }
5850
5851    #[test]
5852    fn a_directive_labels_nested_emphasis_keeps_both_its_style_and_its_offsets() {
5853        let src = "x :abbr[a *b* c] y\n";
5854        let m = map_directives(src);
5855        let b = m
5856            .rows
5857            .iter()
5858            .flat_map(|r| &r.glyphs)
5859            .find(|g| g.ch == 'b')
5860            .expect("the emphasised char");
5861        assert!(b.style.italic, "the label's *b* lost its emphasis");
5862        assert_eq!(b.src, 11, "the label's *b* lost its source byte");
5863    }
5864
5865    #[test]
5866    fn a_bare_colon_word_renders_as_the_prose_it_almost_always_is() {
5867        // Regression: twig matches a colon followed by any letter-led word, so
5868        // ordinary prose is full of "text directives" nobody meant to write.
5869        // With no `[label]` there are no children, and the arm recursed into
5870        // them — rendering *nothing*. The word vanished from the document with
5871        // no caret stop left behind, so it could not even be deleted.
5872        for src in ["a :word b\n", "note :see below\n", ":smile: hi\n"] {
5873            let m = map_directives(src);
5874            assert_eq!(
5875                rendered(&m).trim_end(),
5876                src.trim_end(),
5877                "prose was eaten: {src:?}"
5878            );
5879        }
5880    }
5881
5882    #[test]
5883    fn a_bare_colon_word_keeps_every_byte_a_caret_stop() {
5884        let src = "a :word b\n";
5885        let m = map_directives(src);
5886        // Nothing here is markup, so nothing is hidden: each byte maps to
5887        // itself and can be stood on, which is what makes the colon deletable.
5888        let stops: Vec<(char, usize)> = m
5889            .rows
5890            .iter()
5891            .flat_map(|r| &r.glyphs)
5892            .filter(|g| g.stop)
5893            .map(|g| (g.ch, g.src))
5894            .collect();
5895        assert_eq!(
5896            stops,
5897            "a :word b"
5898                .chars()
5899                .enumerate()
5900                .map(|(i, c)| (c, i))
5901                .collect::<Vec<_>>()
5902        );
5903    }
5904
5905    #[test]
5906    fn an_attribute_bearing_text_directive_draws_a_chip() {
5907        // `{…}` is deliberate in a way a bare colon is not — diaryx writes
5908        // `:vis{.family}` inline — so this one reads as an embed, on the same
5909        // `⧉ label` recipe the leaf form's placeholder row uses.
5910        // Both attribute conventions label it: twig's dot-prefixed classes and
5911        // the bare pandoc-style words diaryx also writes.
5912        for src in ["a :vis{.family} b\n", "a :vis{family} b\n"] {
5913            let m = map_directives(src);
5914            assert_eq!(rendered(&m).trim_end(), "a ⧉ vis family b", "{src:?}");
5915        }
5916        // A `key=value` attr is configuration, not a name, so it adds nothing.
5917        let m = map_directives("a :foo{title=\"x\"} b\n");
5918        assert_eq!(rendered(&m).trim_end(), "a ⧉ foo b");
5919    }
5920
5921    #[test]
5922    fn a_directive_chip_is_one_atomic_caret_stop_at_its_own_offset() {
5923        let src = "a :vis{.family} b\n";
5924        let m = map_directives(src);
5925        let stops: Vec<usize> = m
5926            .rows
5927            .iter()
5928            .flat_map(|r| &r.glyphs)
5929            .filter(|g| g.stop)
5930            .map(|g| g.src)
5931            .collect();
5932        // The chip contributes exactly one stop, at the directive's start (2),
5933        // so the caret steps over it whole instead of walking hidden markup a
5934        // byte at a time. `{.family}`'s bytes (3..15) are never stood on.
5935        assert_eq!(stops, [0, 1, 2, 15, 16]);
5936    }
5937
5938    #[test]
5939    fn a_paragraph_holding_only_a_chip_is_still_navigable() {
5940        // With no stop of its own the row would be unreachable — the caret
5941        // could never be put on the line to edit or delete the directive.
5942        let m = map_directives(":vis{.family}\n");
5943        assert!(
5944            m.row_is_navigable(0),
5945            "a chip-only paragraph has no caret home"
5946        );
5947        assert_eq!(
5948            m.offset_of_pos(0, 0),
5949            0,
5950            "its caret home isn't the directive's start"
5951        );
5952    }
5953
5954    #[test]
5955    fn a_ratio_or_a_clock_time_is_never_a_directive() {
5956        // twig requires a letter after the colon, so these stay prose — the
5957        // verbatim arm must not be reached for them at all.
5958        let src = "ratio 3:4 and 10:30\n";
5959        assert_eq!(
5960            rendered(&map_directives(src)).trim_end(),
5961            "ratio 3:4 and 10:30"
5962        );
5963    }
5964
5965    #[test]
5966    fn a_leaf_directive_is_a_placeholder_row_with_its_attrs_published() {
5967        // `::name{…}` is a standalone block with no body — an embed, a table of
5968        // contents. It used to emit no rows at all: invisible, no caret home,
5969        // vertical motion crossing a void. Now it draws the image recipe's
5970        // placeholder and publishes what the host app needs to paint the real
5971        // thing.
5972        let src = "before\n\n::embed{src=\"demo.html\" height=\"400\"}\n\nafter\n";
5973        let m = map_directives(src);
5974
5975        let row = m
5976            .rows
5977            .iter()
5978            .position(|r| r.leaf_directive.is_some())
5979            .expect("a placeholder row");
5980        assert_eq!(
5981            m.rows[row].glyphs.iter().map(|g| g.ch).collect::<String>(),
5982            "⧉ embed"
5983        );
5984        assert!(
5985            m.rows[row].glyphs.iter().any(|g| g.stop),
5986            "the caret can land on it"
5987        );
5988        assert!(
5989            m.rows[row].directive,
5990            "a frontend frames it like the container form"
5991        );
5992
5993        assert_eq!(m.directives.len(), 1);
5994        let info = &m.directives[0];
5995        assert_eq!(info.name, "embed");
5996        assert_eq!(info.rows_span, row..row + 1);
5997        assert_eq!(info.attr("src"), Some("demo.html"));
5998        assert_eq!(info.attr("height"), Some("400"));
5999        assert_eq!(info.attr("nope"), None);
6000        // The prose around it is untouched.
6001        assert!(rendered(&m).contains("before") && rendered(&m).contains("after"));
6002    }
6003
6004    #[test]
6005    fn a_leaf_directive_shows_its_label_and_honours_its_prefix() {
6006        // A `[label]` names the placeholder (the way an image's alt does), and a
6007        // quoted directive keeps the quote's gutter — it is a block like any
6008        // other, not a special case that escapes its container.
6009        let m = map_directives("::embed[Audience demo]{src=\"demo.html\"}\n");
6010        assert_eq!(rendered(&m).trim_end(), "⧉ Audience demo");
6011        assert_eq!(m.directives[0].label, "Audience demo");
6012
6013        let quoted = map_directives("> ::embed{src=\"x.html\"}\n");
6014        assert_eq!(rendered(&quoted).trim_end(), "│ ⧉ embed");
6015        assert_eq!(quoted.directives[0].name, "embed");
6016    }
6017
6018    #[test]
6019    fn a_container_directive_is_still_a_panel_not_a_placeholder() {
6020        // The three forms must not bleed into each other: only the leaf form is
6021        // a placeholder, and only the container form tints the blocks it wraps.
6022        let m = map_directives(":::note{.warning}\nBody\n:::\n");
6023        assert!(
6024            m.directives.is_empty(),
6025            "a container publishes no placeholder"
6026        );
6027        assert!(m.rows.iter().all(|r| r.leaf_directive.is_none()));
6028        assert_eq!(rendered(&m).trim_end(), "Body");
6029        assert!(
6030            m.rows
6031                .iter()
6032                .any(|r| r.directive && r.directive_label.as_deref() == Some("warning"))
6033        );
6034    }
6035
6036    /// A production-path build with both extensions on — the only way to put a
6037    /// promoted HTML element and a directive in one document, which is what the
6038    /// `container` kind made necessary to tell apart. Returns the whole `Doc`
6039    /// because [`VisualMap`] is not `Clone`; read `doc.vmap`.
6040    fn doc_built(src: &str) -> crate::Doc {
6041        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
6042        doc.build_visual(80);
6043        doc
6044    }
6045
6046    /// Every `container` node in `src`, parsed the way production does (both
6047    /// extensions on), paired with what [`container_is_directive`] makes of it.
6048    fn containers(src: &str) -> Vec<(String, bool, Option<DirectiveForm>)> {
6049        let mut ed = Editor::new_ext(
6050            src.as_bytes(),
6051            Format::Markdown,
6052            twig::MarkdownExtensions {
6053                directives: true,
6054                html_elements: true,
6055                ..Default::default()
6056            },
6057        )
6058        .unwrap();
6059        ed.nodes()
6060            .unwrap()
6061            .iter()
6062            .filter(|n| n.kind == Kind::Container)
6063            .map(|n| {
6064                (
6065                    n.name.clone().unwrap_or_default(),
6066                    container_is_directive(n),
6067                    n.directive_form,
6068                )
6069            })
6070            .collect()
6071    }
6072
6073    #[test]
6074    fn a_directive_and_an_html_element_are_told_apart_by_spelling_not_by_form() {
6075        // twig 2.8 folded `div`/`span`/`directive`/`element` into one `container`
6076        // kind. `directive_form` reads as though it separates them and does not:
6077        // a block-level `<div>` reports `Some(DirectiveForm::Container)` exactly
6078        // as a `:::note` does. Trusting it would draw directive chrome — a tinted
6079        // panel, a `.class` audience label — on every pasted Slack/Docs div.
6080        for (src, name, want) in [
6081            (":::note{.a}\nbody\n:::\n", "note", true),
6082            ("::embed{src=x}\n", "embed", true),
6083            ("a :vis[hi]{.b} b\n", "vis", true),
6084            ("<div class=\"x\">\nhi\n</div>\n", "div", false),
6085            ("<video src=\"v.mp4\" controls></video>\n", "video", false),
6086            ("<audio src=\"a.mp3\" controls></audio>\n", "audio", false),
6087            ("<figure>\n\nhi\n\n</figure>\n", "figure", false),
6088            // The `:` in an attribute must not read as a directive opener: the
6089            // `<` of the tag comes first, and first one wins.
6090            (
6091                "<video src=\"http://x.test/v.mp4\" controls></video>\n",
6092                "video",
6093                false,
6094            ),
6095            (
6096                "<source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\n",
6097                "source",
6098                false,
6099            ),
6100        ] {
6101            let found = containers(src);
6102            let hit = found.iter().find(|(n, ..)| n == name);
6103            let Some((_, is_directive, form)) = hit else {
6104                panic!("no `{name}` container in {src:?} — found {found:?}");
6105            };
6106            assert_eq!(*is_directive, want, "{name} in {src:?} (form was {form:?})");
6107        }
6108
6109        // And the reason this can't just read the field: for the one collision
6110        // that matters, the field says the same thing for both.
6111        let div = containers("<div class=\"x\">\nhi\n</div>\n");
6112        let note = containers(":::note{.a}\nbody\n:::\n");
6113        assert_eq!(
6114            div[0].2, note[0].2,
6115            "if these ever differ, `directive_form` became usable and this rule can go"
6116        );
6117    }
6118
6119    #[test]
6120    fn a_directive_nested_in_a_quote_or_list_is_still_a_directive() {
6121        // A container's span opens with its *block prefix*, not its own markup —
6122        // `> ::embed{…}` starts at the `>`. Reading only the first byte to tell a
6123        // directive from an element (both `container` since 2.8) therefore misses
6124        // every nested one, and the placeholder silently renders as nothing.
6125        for (src, ctx) in [
6126            ("> ::embed{src=\"x\"}\n", "quoted"),
6127            ("- ::embed{src=\"x\"}\n", "listed"),
6128            (">> ::embed{src=\"x\"}\n", "twice quoted"),
6129        ] {
6130            let m = map_directives(src);
6131            assert_eq!(m.directives.len(), 1, "{ctx} directive was lost");
6132            assert_eq!(m.directives[0].name, "embed", "{ctx}");
6133        }
6134    }
6135
6136    #[test]
6137    fn a_video_is_still_media_and_not_a_directive() {
6138        // The other side of the same coin: `<video>` is a `container` too, and
6139        // must reach `block_media` rather than the directive arms.
6140        let doc = doc_built("<video src=\"clip.mp4\" controls></video>\n");
6141        assert_eq!(doc.vmap.media.len(), 1, "the video is block media");
6142        assert!(
6143            doc.vmap.rows.iter().all(|r| !r.directive),
6144            "the video drew directive chrome"
6145        );
6146    }
6147
6148    #[test]
6149    fn a_directive_needs_the_extension_flag() {
6150        // `map` (twig's default extensions) leaves `directives` off — the fence
6151        // renders as literal paragraph text, same as any other unrecognized
6152        // punctuation, never corrupting or panicking.
6153        let src = ":::vis{.public}\nhello\n:::\n";
6154        let m = map(src);
6155        assert!(m.rows.iter().all(|r| !r.directive));
6156        assert!(rendered(&m).contains(":::vis{.public}"));
6157    }
6158
6159    #[test]
6160    fn a_footnote_reference_keeps_its_paragraph_visible() {
6161        // Regression: `footnote_reference` was in neither `is_inline_kind` nor
6162        // the inline walker, so a paragraph carrying one failed the "all children
6163        // inline" test, was walked as a container of blocks, and rendered as
6164        // empty rows with no caret stop anywhere — the whole line vanished.
6165        let src = "A claim[^1] and more.\n";
6166        let m = map(src);
6167        assert_eq!(rendered(&m).trim_end(), "A claim[1] and more.");
6168        // The `^` is spelling, not text: hidden the way a link's `](dest)` is.
6169        assert!(!rendered(&m).contains('^'));
6170    }
6171
6172    #[test]
6173    fn a_footnote_reference_is_raised_and_the_prose_around_it_is_not() {
6174        // What makes `[1]` read as a reference rather than as bracketed text.
6175        // The brackets ride with the label: the chip is one raised mark.
6176        let m = map("A claim[^1] and more.\n");
6177        assert_eq!(baselines_of(&m, '1'), vec![Baseline::Super]);
6178        assert_eq!(baselines_of(&m, '['), vec![Baseline::Super]);
6179        assert_eq!(baselines_of(&m, ']'), vec![Baseline::Super]);
6180        assert_eq!(baselines_of(&m, 'A'), vec![Baseline::Normal]);
6181    }
6182
6183    #[test]
6184    fn a_footnote_reference_keeps_the_link_role_it_had() {
6185        // The raised baseline is added to the role, not swapped for it: every
6186        // frontend already paints `Role::Link`, and a reference is one.
6187        let m = map("A claim[^1].\n");
6188        let label = m
6189            .rows
6190            .iter()
6191            .flat_map(|r| &r.glyphs)
6192            .find(|g| g.ch == '1')
6193            .unwrap();
6194        assert_eq!(label.style.role, Role::Link);
6195        assert_eq!(label.style.baseline, Baseline::Super);
6196    }
6197
6198    /// The [`Role`] of the first glyph spelling `ch` — how a test reads one
6199    /// run's styling off a map without caring which row it landed on.
6200    fn role_of(m: &VisualMap, ch: char) -> Role {
6201        m.rows
6202            .iter()
6203            .flat_map(|r| r.glyphs.iter())
6204            .find(|g| g.ch == ch)
6205            .unwrap_or_else(|| panic!("no glyph spelling {ch:?}"))
6206            .style
6207            .role
6208    }
6209
6210    #[test]
6211    fn a_markdown_highlight_is_a_mark_and_a_coloured_one_names_its_colour() {
6212        // twig 3.3's `highlight`/`highlight_colors`, which `parse_extensions`
6213        // turns on for every leaf document: `==text==` is a `mark` in Markdown
6214        // and not the literal `==` it used to be, and `==🔴 text==` is one
6215        // carrying a colour.
6216        //
6217        // `doc_built` rather than `map`, deliberately — the extensions are
6218        // leaf's choice, not twig's default, so a test that parsed bare
6219        // Markdown here would be testing a document leaf never builds.
6220        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
6221        assert_eq!(role_of(&doc.vmap, 'y'), Role::Mark(None));
6222        assert_eq!(
6223            role_of(&doc.vmap, 'r'),
6224            Role::Mark(Some(MarkColor::Red)),
6225            "the `data-color` twig stripped the emoji into"
6226        );
6227        assert_eq!(role_of(&doc.vmap, 'P'), Role::Body);
6228    }
6229
6230    #[test]
6231    fn the_emoji_that_named_a_highlight_is_markup_and_never_drawn() {
6232        // The colour is *spelling*: twig strips the emoji out of the mark's
6233        // content, so the reader sees the words and the wash, never the circle.
6234        // Drawing it would put a character in the rendered text that the author
6235        // wrote as syntax — the same mistake as drawing an emphasis's `*`.
6236        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
6237        let drawn: String = doc.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
6238        assert_eq!(drawn, "Plain yes and red ok");
6239    }
6240
6241    #[test]
6242    fn a_superscript_and_a_subscript_sit_off_the_baseline() {
6243        // Regression: both rendered flat, so the toolbar's superscript button
6244        // produced markup that looked exactly like the text around it.
6245        let m = map_djot("H~2~O and x^2^\n");
6246        assert_eq!(baselines_of(&m, '2'), vec![Baseline::Sub, Baseline::Super]);
6247        assert_eq!(baselines_of(&m, 'H'), vec![Baseline::Normal]);
6248        assert_eq!(baselines_of(&m, 'O'), vec![Baseline::Normal]);
6249    }
6250
6251    #[test]
6252    fn a_raised_glyph_keeps_the_style_it_was_raised_out_of() {
6253        // Why this is a `Baseline` and not a `Role`: raising a glyph says where
6254        // it sits, and must not cost it what it already was.
6255        let m = map_djot("# Heading x^2^\n");
6256        let two = m
6257            .rows
6258            .iter()
6259            .flat_map(|r| &r.glyphs)
6260            .find(|g| g.ch == '2')
6261            .unwrap();
6262        assert_eq!(two.style.baseline, Baseline::Super);
6263        assert_eq!(two.style.role, Role::Heading(1), "still heading text");
6264    }
6265
6266    #[test]
6267    fn a_footnote_references_brackets_are_decoration_and_only_its_label_is_a_stop() {
6268        let src = "see[^note] here\n";
6269        let m = map(src);
6270        // `[^note]` spans 3..10, its label `note` 5..9. The caret walks the
6271        // label; the brackets are drawn but never stood on, as a table's are,
6272        // and the `[^`/`]` bytes are stepped over like any hidden delimiter.
6273        let stops: Vec<usize> = m
6274            .rows
6275            .iter()
6276            .flat_map(|r| &r.glyphs)
6277            .filter(|g| g.stop)
6278            .map(|g| g.src)
6279            .collect();
6280        for off in 5..9 {
6281            assert!(
6282                stops.contains(&off),
6283                "label byte {off} isn't a caret stop: {stops:?}"
6284            );
6285        }
6286        for off in [3usize, 4, 9] {
6287            assert!(
6288                !stops.contains(&off),
6289                "delimiter byte {off} is a caret stop: {stops:?}"
6290            );
6291        }
6292    }
6293
6294    #[test]
6295    fn a_task_item_draws_its_box_where_the_bullet_would_be() {
6296        // Regression: the `[ ] ` is markup twig consumes — the item's paragraph
6297        // content starts past it — so a task item used to render as `• todo`,
6298        // identical to a plain bullet and with no way to see it was ticked.
6299        let m = map("- [ ] todo\n- [x] done\n- plain\n");
6300        assert_eq!(rendered(&m), "☐ todo\n☑ done\n• plain");
6301
6302        // The tick rides the item's first row, for a GUI that paints its own box.
6303        let ticks: Vec<Option<bool>> = m.rows.iter().map(|r| r.task).collect();
6304        assert_eq!(ticks, [Some(false), Some(true), None]);
6305    }
6306
6307    #[test]
6308    fn a_task_items_box_survives_a_wrap_and_marks_only_the_first_row() {
6309        let m = map_at(
6310            "- [x] a much longer task that has to wrap somewhere\n",
6311            Some(20),
6312        );
6313        assert!(m.rows.len() > 1, "the item should wrap: {:?}", rendered(&m));
6314        assert_eq!(m.rows[0].task, Some(true));
6315        assert!(
6316            m.rows[1..].iter().all(|r| r.task.is_none()),
6317            "only the first row"
6318        );
6319        // The continuation lines hang under the box, not under column zero.
6320        assert!(
6321            rendered(&m)
6322                .lines()
6323                .nth(1)
6324                .is_some_and(|l| l.starts_with("  "))
6325        );
6326    }
6327
6328    #[test]
6329    fn a_bracket_in_an_items_prose_is_not_a_checkbox() {
6330        // `task_checked` finds the box past the list marker; a plain item whose
6331        // text merely contains a bracket has none, and must keep its bullet.
6332        let m = map("- see [1] below\n");
6333        assert_eq!(rendered(&m), "• see [1] below");
6334        assert_eq!(m.rows[0].task, None);
6335    }
6336
6337    #[test]
6338    fn a_footnote_definition_renders_where_it_was_written() {
6339        // Regression: twig parses `[^1]: …` as a root *beside* `doc` — not a
6340        // child of it — so the walk from `doc` never reached one and every byte
6341        // of the note's body rendered as nothing at all.
6342        let src = "A claim[^1].\n\n[^1]: The note body.\n\nAfter.\n";
6343        let m = map(src);
6344        let text = rendered(&m);
6345        assert!(
6346            text.contains("The note body."),
6347            "the note body is invisible: {text:?}"
6348        );
6349        // In source order — between the paragraph that cites it and the one
6350        // after — not hoisted to the end, and marked to match its reference.
6351        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
6352        assert_eq!(lines, ["A claim[1].", "[1] The note body.", "After."]);
6353    }
6354
6355    #[test]
6356    fn a_footnote_definitions_body_maps_to_its_own_source_bytes() {
6357        let src = "x[^a].\n\n[^a]: body\n";
6358        let m = map(src);
6359        // `body` sits at 14..18. Its glyphs must map there — a marker that ate
6360        // the offsets would put the caret in the wrong place on every click.
6361        let body: Vec<(char, usize)> = m
6362            .rows
6363            .iter()
6364            .flat_map(|r| &r.glyphs)
6365            .filter(|g| g.stop && g.src >= 14)
6366            .map(|g| (g.ch, g.src))
6367            .collect();
6368        assert_eq!(body, [('b', 14), ('o', 15), ('d', 16), ('y', 17)]);
6369    }
6370
6371    #[test]
6372    fn an_empty_footnote_definition_still_shows_its_marker() {
6373        // The instant `[^1]: ` has been typed and nothing after it. `blocks`
6374        // renders no child, so without the explicit marker row the definition
6375        // wouldn't appear at all until something was typed into it.
6376        let src = "x[^1]\n\n[^1]:\n";
6377        let m = map(src);
6378        assert!(
6379            rendered(&m).contains("[1] "),
6380            "no marker row: {:?}",
6381            rendered(&m)
6382        );
6383    }
6384
6385    #[test]
6386    fn a_footnote_definition_wearing_a_long_label_indents_its_wrapped_body() {
6387        let src = "x[^src]\n\n[^src]: one two three four five six seven\n";
6388        let m = map_at(src, Some(24));
6389        let text = rendered(&m);
6390        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
6391        // Continuation lines hang under the marker, as a list item's do — the
6392        // indent is the marker's own width, not a fixed one.
6393        assert_eq!(lines[1].trim_end(), "[src] one two three four");
6394        assert!(
6395            lines[2].starts_with("      "),
6396            "body doesn't hang: {:?}",
6397            lines[2]
6398        );
6399        assert_eq!(lines[2].trim(), "five six seven");
6400    }
6401
6402    #[test]
6403    fn a_code_block_leaves_exactly_one_blank_row_below_it() {
6404        // The closing fence line used to be miscounted as a blank separator,
6405        // opening a phantom second gap under the block. One block boundary is
6406        // one blank row, code block or not.
6407        let src = "para\n\n```\ncode\n```\n\nafter\n";
6408        let m = map(src);
6409        let code_end = m.code_blocks[0].rows_span.end;
6410        let after = m
6411            .rows
6412            .iter()
6413            .position(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "after")
6414            .unwrap();
6415        assert_eq!(
6416            after - code_end,
6417            1,
6418            "exactly one row between code and 'after'"
6419        );
6420    }
6421
6422    #[test]
6423    fn a_fenced_block_publishes_its_language_on_its_code_block() {
6424        // The info string becomes the block's label; a bare fence and an indented
6425        // block carry none.
6426        assert_eq!(
6427            map("```rust\nlet x = 1;\n```\n").code_blocks[0]
6428                .lang
6429                .as_deref(),
6430            Some("rust")
6431        );
6432        assert_eq!(map("```\nplain\n```\n").code_blocks[0].lang, None);
6433        assert_eq!(map("    indented\n").code_blocks[0].lang, None);
6434    }
6435
6436    #[test]
6437    fn inline_code_is_not_a_code_block() {
6438        // A `code` span inside prose is styled by role, not boxed: it's part of a
6439        // normal paragraph row, so it names no `code_blocks` entry.
6440        let m = map("a `snippet` b\n");
6441        assert!(m.code_blocks.is_empty(), "inline code wrongly boxed");
6442        assert!(
6443            m.rows.iter().all(|r| !r.code),
6444            "inline code flagged a code row"
6445        );
6446    }
6447
6448    #[test]
6449    fn caret_steps_over_hidden_delimiters() {
6450        // "a **bold** c": bytes 8,9 are the closing ** — no glyph. Moving right
6451        // from 'd' (src 7) lands on the space before 'c' (src 10), not inside **.
6452        let m = map("a **bold** c\n");
6453        let (r, c) = m.pos_of_offset(7);
6454        assert_eq!(m.offset_of_pos(r, c + 1), 10);
6455    }
6456
6457    // ── the structural view of a table ───────────────────────────────────────
6458
6459    #[test]
6460    fn a_table_is_published_structurally_beside_its_picture() {
6461        let m = map(TABLE);
6462        let t = &m.tables[0];
6463        let cell = |r: usize, c: usize| -> String {
6464            t.grid[r].cells[c].glyphs.iter().map(|g| g.ch).collect()
6465        };
6466        assert_eq!(t.grid.len(), 3, "head + two body rows");
6467        assert_eq!(
6468            (cell(0, 0), cell(0, 1), cell(1, 0), cell(2, 1)),
6469            ("Name".into(), "Qty".into(), "Pear".into(), "12".into())
6470        );
6471        assert_eq!(
6472            t.grid.iter().map(|r| r.head).collect::<Vec<_>>(),
6473            [true, false, false]
6474        );
6475        // The alignment the delimiter row spelled, carried per cell — the only
6476        // place it survives, since the parser consumes that row.
6477        assert!(matches!(t.grid[1].cells[0].align, Alignment::Left));
6478        assert!(matches!(t.grid[1].cells[1].align, Alignment::Right));
6479    }
6480
6481    #[test]
6482    fn a_block_media_is_published_structurally_beside_its_placeholder() {
6483        let m = map("intro\n\n![a cat](img/cat.png)\n\nend\n");
6484        assert_eq!(m.media.len(), 1, "one block image");
6485        let img = &m.media[0];
6486        assert_eq!(img.destination, "img/cat.png");
6487        assert_eq!(img.alt, "a cat");
6488        // The placeholder row named by `rows_span` carries the label a plain
6489        // surface paints and a capable frontend replaces.
6490        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
6491        assert_eq!(
6492            img.rows_span.end - img.rows_span.start,
6493            1,
6494            "one placeholder row"
6495        );
6496        assert_eq!(row_text(img.rows_span.start), "🖼 a cat");
6497        // The row carries the mark `media_spans` derives the side-table from.
6498        assert!(m.rows[img.rows_span.start].media.is_some());
6499    }
6500
6501    #[test]
6502    fn an_image_without_alt_labels_itself_with_its_filename() {
6503        let m = map("![](photos/beach.jpg)\n");
6504        let row = &m.rows[m.media[0].rows_span.start];
6505        assert_eq!(
6506            row.glyphs.iter().map(|g| g.ch).collect::<String>(),
6507            "🖼 beach.jpg"
6508        );
6509        assert_eq!(m.media[0].alt, "");
6510    }
6511
6512    #[test]
6513    fn a_block_media_gives_the_caret_a_home_before_and_after_it() {
6514        // `![x](y)` on its own line: the caret can rest in front of the image
6515        // (its start) and just past it (the row end), and nowhere inside the
6516        // markup — the same coarse mapping a thematic break uses.
6517        let src = "![x](y.png)\n";
6518        let m = map(src);
6519        let img = &m.rows[m.media[0].rows_span.start];
6520        let start = 0; // the image opens the document
6521        let end = "![x](y.png)".len();
6522        // Every placeholder glyph maps to the image start and is a stop there.
6523        assert!(img.glyphs.iter().all(|g| g.src == start && g.stop));
6524        assert_eq!(img.end_src, end, "the row ends past the image");
6525        assert_eq!(m.stops.first(), Some(&start));
6526        assert!(m.stops.contains(&end), "a stop sits after the image");
6527        // Nothing inside the markup is a stop.
6528        assert!(!m.stops.iter().any(|&s| s > start && s < end));
6529    }
6530
6531    #[test]
6532    fn an_inline_image_amid_text_is_not_a_block_media() {
6533        // An image sharing its line with prose isn't block-level: it stays in the
6534        // inline path (rendered as its alt text), and publishes no MediaInfo.
6535        let m = map("see ![a cat](cat.png) here\n");
6536        assert!(m.media.is_empty(), "not a block image");
6537        assert!(
6538            rendered(&m).contains("a cat"),
6539            "alt text still renders inline"
6540        );
6541    }
6542
6543    /// The block images `Doc` publishes for `src`, driven through the real
6544    /// production build (`build_visual` → `build_cached`) with `html_elements`
6545    /// on — the path a `<picture>` actually travels. Not the raw `build` the
6546    /// other tests use: the editor's flat whole-arena snapshot tangles the links
6547    /// of inline-promoted HTML (phantom roots, dangling `parent`s), which only
6548    /// the per-block subtree walk `build_cached` does untangles.
6549    fn doc_media(src: &str) -> Vec<MediaInfo> {
6550        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
6551        doc.build_visual(80);
6552        doc.vmap.media.clone()
6553    }
6554
6555    #[test]
6556    fn a_video_block_is_media_with_its_src_poster_and_kind() {
6557        // The load-bearing assumption of video support: twig has no `video` node
6558        // kind, so `html_elements` promotion must land a `<video>` as a generic
6559        // `element` whose tag name and attributes survive onto `FlatNode` — the
6560        // same treatment `<picture>` gets. If that ever stops holding, this is
6561        // the test that says so.
6562        let m = doc_media("<video src=\"clip.mp4\" poster=\"still.png\" controls>\n</video>\n");
6563        assert_eq!(m.len(), 1, "the video is one block media");
6564        assert_eq!(m[0].kind, MediaKind::Video);
6565        assert_eq!(m[0].destination, "clip.mp4");
6566        assert_eq!(m[0].poster, "still.png");
6567    }
6568
6569    #[test]
6570    fn a_single_line_video_is_a_block_too() {
6571        // The spelling everyone actually writes. It used to parse as a paragraph
6572        // of raw inline HTML — CommonMark opens a block on a complete tag only
6573        // when the line ends there, and its fixed tag list predates `<video>` —
6574        // so the tags never reached core as an element at all. twig 2.5.1 widened
6575        // that list under `html_elements`; this is the test that would catch the
6576        // pin sliding back.
6577        let m = doc_media("<video src=\"clip.mp4\" controls></video>\n");
6578        assert_eq!(m.len(), 1, "single-line <video> is a block");
6579        assert_eq!(m[0].kind, MediaKind::Video);
6580        assert_eq!(m[0].destination, "clip.mp4");
6581    }
6582
6583    #[test]
6584    fn a_single_line_picture_is_a_block_with_its_alternatives() {
6585        // `<picture>` had the identical gap and it went unnoticed because the
6586        // conventional spelling breaks the lines. Same twig fix covers it.
6587        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\
6588                   <img src=\"l.svg\" alt=\"banner\"></picture>\n";
6589        let m = doc_media(src);
6590        assert_eq!(m.len(), 1);
6591        assert_eq!(m[0].kind, MediaKind::Image);
6592        assert_eq!(m[0].destination, "l.svg");
6593        assert_eq!(m[0].resolve(ColorScheme::Dark), "d.svg");
6594    }
6595
6596    #[test]
6597    fn an_audio_block_is_media_with_no_poster() {
6598        let m = doc_media("<audio src=\"take.mp3\" controls>\n</audio>\n");
6599        assert_eq!(m.len(), 1);
6600        assert_eq!(m[0].kind, MediaKind::Audio);
6601        assert_eq!(m[0].destination, "take.mp3");
6602        assert!(m[0].poster.is_empty(), "audio has no poster frame");
6603    }
6604
6605    #[test]
6606    fn a_videos_source_children_are_its_candidates_typed_by_mime() {
6607        // A `<video>` with no `src` of its own — the common shape, since it's how
6608        // you offer more than one codec. The candidates come from `<source src>`
6609        // (not `srcset`, which is `<picture>`'s spelling) and carry their MIME.
6610        let src = "<video controls>\n\
6611                   <source src=\"a.webm\" type=\"video/webm\">\n\
6612                   <source src=\"a.mp4\" type=\"video/mp4\">\n\
6613                   fallback\n\
6614                   </video>\n";
6615        let m = doc_media(src);
6616        assert_eq!(m.len(), 1);
6617        assert!(
6618            m[0].destination.is_empty(),
6619            "no src attribute on the element"
6620        );
6621        assert_eq!(m[0].sources.len(), 2);
6622        assert_eq!(m[0].sources[0].srcset, "a.webm");
6623        assert_eq!(m[0].sources[0].mime, "video/webm");
6624        assert_eq!(m[0].sources[1].srcset, "a.mp4");
6625        // With an empty destination, `resolve` falls through to the first
6626        // candidate rather than handing the frontend nothing to load.
6627        assert_eq!(m[0].resolve(ColorScheme::Light), "a.webm");
6628    }
6629
6630    #[test]
6631    fn a_video_placeholder_row_carries_its_own_sigil_and_mark() {
6632        // The placeholder contract images already hold, now for a video: the row
6633        // renders as a labelled stand-in a plain surface can paint as-is, and
6634        // carries the mark a capable frontend replaces it from.
6635        let src = "<video src=\"clip.mp4\" controls>\n</video>\n";
6636        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
6637        doc.build_visual(80);
6638        let row = &doc.vmap.rows[doc.vmap.media[0].rows_span.start];
6639        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
6640        assert!(
6641            text.starts_with('🎬'),
6642            "video sigil, not the image one: {text:?}"
6643        );
6644        assert!(row.media.is_some(), "the mark rides the placeholder row");
6645    }
6646
6647    #[test]
6648    fn a_picture_block_carries_its_source_alternatives() {
6649        // A `<picture>` with a dark-mode `<source>`: one block image, whose
6650        // fallback destination is the `<img>` and whose `sources` carry the
6651        // `<source>`'s media + srcset for a theme-aware frontend to pick.
6652        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"banner\"></picture>\n";
6653        let images = doc_media(src);
6654        assert_eq!(images.len(), 1, "the picture is one block image");
6655        let img = &images[0];
6656        assert_eq!(img.destination, "light.svg", "fallback is the <img>");
6657        assert_eq!(img.alt, "banner");
6658        assert_eq!(
6659            img.sources,
6660            vec![MediaSource {
6661                media: "(prefers-color-scheme: dark)".into(),
6662                srcset: "dark.svg".into(),
6663                mime: String::new(),
6664            }],
6665        );
6666    }
6667
6668    #[test]
6669    fn a_picture_inside_a_heading_is_still_a_block_media_with_sources() {
6670        // fig.md's shape: the banner is an `<h1>` wrapping the `<picture>`.
6671        let src = "<h1><picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\"><img src=\"l.svg\" alt=\"fig\"></picture></h1>\n";
6672        let images = doc_media(src);
6673        assert_eq!(images.len(), 1, "heading-wrapped picture is a block image");
6674        assert_eq!(images[0].destination, "l.svg");
6675        assert_eq!(images[0].sources.len(), 1);
6676        assert_eq!(images[0].sources[0].srcset, "d.svg");
6677    }
6678
6679    #[test]
6680    fn a_plain_image_has_no_media_sources() {
6681        // A bare Markdown image carries an empty `sources` — nothing to pick from.
6682        let images = doc_media("![alt](p.png)\n");
6683        assert_eq!(images.len(), 1);
6684        assert!(
6685            images[0].sources.is_empty(),
6686            "no <picture>, no alternatives"
6687        );
6688    }
6689
6690    #[test]
6691    fn resolve_picks_the_source_matching_the_scheme() {
6692        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"b\"></picture>\n";
6693        let images = doc_media(src);
6694        let img = &images[0];
6695        // Dark theme takes the dark source; light falls through to the <img>.
6696        assert_eq!(img.resolve(ColorScheme::Dark), "dark.svg");
6697        assert_eq!(img.resolve(ColorScheme::Light), "light.svg");
6698    }
6699
6700    #[test]
6701    fn resolve_falls_back_for_a_plain_image_and_unknown_media() {
6702        // A plain image ignores the scheme.
6703        let plain = doc_media("![a](p.png)\n");
6704        assert_eq!(plain[0].resolve(ColorScheme::Dark), "p.png");
6705
6706        // A <source> with an unrecognized media query is skipped; a light source
6707        // is taken under a light theme.
6708        let m = doc_media(
6709            "<picture><source media=\"print\" srcset=\"p.svg\"><source media=\"(prefers-color-scheme: light)\" srcset=\"l.svg\"><img src=\"f.svg\" alt=\"x\"></picture>\n",
6710        );
6711        assert_eq!(m[0].resolve(ColorScheme::Light), "l.svg");
6712        assert_eq!(
6713            m[0].resolve(ColorScheme::Dark),
6714            "f.svg",
6715            "no dark source → <img>"
6716        );
6717    }
6718
6719    #[test]
6720    fn resolve_reads_the_first_srcset_url_ignoring_descriptors() {
6721        // A comma/descriptor srcset resolves to its first URL.
6722        assert_eq!(first_srcset_url("a.png 1x, b.png 2x"), Some("a.png"));
6723        assert_eq!(first_srcset_url("  solo.svg  "), Some("solo.svg"));
6724        assert_eq!(first_srcset_url(""), None);
6725        // An empty (unconditional) media always matches.
6726        assert!(media_matches("", ColorScheme::Light));
6727        assert!(media_matches(
6728            "(prefers-color-scheme:dark)",
6729            ColorScheme::Dark
6730        ));
6731        assert!(!media_matches(
6732            "(prefers-color-scheme: dark)",
6733            ColorScheme::Light
6734        ));
6735    }
6736
6737    #[test]
6738    fn a_block_media_carries_its_list_prefix() {
6739        // An image that is a list item's body opens past the bullet, like every
6740        // other block does.
6741        let m = map("- ![alt](p.png)\n");
6742        let row = &m.rows[m.media[0].rows_span.start];
6743        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
6744        assert!(
6745            text.starts_with("• "),
6746            "the list marker prefixes the image row: {text:?}"
6747        );
6748        assert!(text.contains("🖼 alt"));
6749    }
6750
6751    #[test]
6752    fn the_structural_table_spans_exactly_its_drawn_rows() {
6753        // A frontend drawing its own grid skips `rows_span` and renders from
6754        // `grid`. If the span were short the leftover border rows would be
6755        // painted as text under the real table; if long it would eat a
6756        // neighbouring paragraph. Both are silent, so pin it to the picture.
6757        let m = map(&format!("before\n\n{TABLE}\nafter\n"));
6758        let t = &m.tables[0];
6759        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
6760        assert!(
6761            row_text(t.rows_span.start).starts_with('┌'),
6762            "opens on the top border"
6763        );
6764        assert!(
6765            row_text(t.rows_span.end - 1).starts_with('└'),
6766            "closes on the bottom border"
6767        );
6768        assert!(
6769            !row_text(t.rows_span.start - 1).contains('┌'),
6770            "the row before the span is not the table's"
6771        );
6772        assert_eq!(
6773            row_text(t.rows_span.end),
6774            "",
6775            "the span ends before the gap row"
6776        );
6777    }
6778
6779    #[test]
6780    fn a_nested_tables_structure_carries_the_block_prefix() {
6781        // The picture puts the quote's gutter on every row of the grid. A
6782        // frontend drawing its own table has to draw that too and start past it,
6783        // so the prefix has to travel with the structure — without it a quoted
6784        // table renders flush at the margin and leaves the quote it's in.
6785        let m = map("> | a | b |\n> |---|---|\n> | c | d |\n");
6786        let t = &m.tables[0];
6787        let prefix: String = t.prefix.iter().map(|g| g.ch).collect();
6788        assert_eq!(prefix, "│ ", "the quote's gutter should ride the structure");
6789        // And it matches what the picture actually drew.
6790        let drawn: String = m.rows[t.rows_span.start]
6791            .glyphs
6792            .iter()
6793            .map(|g| g.ch)
6794            .collect();
6795        assert!(
6796            drawn.starts_with(&prefix),
6797            "picture and structure disagree: {drawn:?}"
6798        );
6799    }
6800
6801    #[test]
6802    fn a_top_level_table_carries_no_prefix() {
6803        assert!(map(TABLE).tables[0].prefix.is_empty());
6804    }
6805
6806    #[test]
6807    fn structural_cells_are_unwrapped_even_when_the_picture_wraps_them() {
6808        // The picture wraps a cell to its column; a frontend laying the grid out
6809        // in pixels needs the text as the document spells it, before that
6810        // decision. Narrow enough that the drawn cell must break.
6811        let src = "| Name |\n|------|\n| alpha beta gamma |\n";
6812        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6813        let m = build_t(&ed.nodes().unwrap(), src, Some(12));
6814        let drawn = rendered(&m);
6815        let cell: String = m.tables[0].grid[1].cells[0]
6816            .glyphs
6817            .iter()
6818            .map(|g| g.ch)
6819            .collect();
6820        assert_eq!(
6821            cell, "alpha beta gamma",
6822            "structure must not carry the wrap"
6823        );
6824        assert!(
6825            drawn.lines().count() > 5,
6826            "the picture should have wrapped, else this proves nothing:\n{drawn}"
6827        );
6828    }
6829
6830    // ── display columns ──────────────────────────────────────────────────────
6831
6832    #[test]
6833    fn a_table_column_is_as_wide_as_its_cells_are_drawn() {
6834        // A column sized by counting characters is drawn narrower than the text
6835        // it has to hold — `你好` is two characters in four cells — and the cell
6836        // spills over the border it is supposed to sit inside, taking the whole
6837        // grid out of square with it. Squareness is the property: every row of a
6838        // grid is drawn to the same column, whatever its cells are spelled with.
6839        for src in [
6840            "| A | B |\n|---|---|\n| 你好 | y |\n",
6841            "| A | B |\n|---|---|\n| a👨‍👩‍👧b | y |\n",
6842            "| A | 漢字 |\n|---|---|\n| x | y |\n",
6843        ] {
6844            let m = map(src);
6845            let widths: Vec<usize> = m.rows.iter().map(|r| r.width()).collect();
6846            assert!(
6847                widths.windows(2).all(|w| w[0] == w[1]),
6848                "ragged grid {widths:?} for {src:?}:\n{}",
6849                rendered(&m)
6850            );
6851        }
6852    }
6853
6854    #[test]
6855    fn a_cell_wrapped_narrow_never_breaks_inside_a_character() {
6856        // A column too narrow for its cell hard-breaks the text, and every line
6857        // of it is given an end stop just past its last glyph. Broken into runs
6858        // of four glyphs, the first line of this cell ends between `👨‍👩` and the
6859        // joiner holding `👧` on — so its end stop lands inside a character,
6860        // where a click or Down can reach it and the next Backspace takes the
6861        // cluster apart from the middle.
6862        let src = "| A |\n|---|\n| 👨‍👩‍👧👨‍👩‍👧 |\n";
6863        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6864        let m = build_t(&ed.nodes().unwrap(), src, Some(8));
6865        let boundaries: Vec<usize> = src
6866            .grapheme_indices(true)
6867            .map(|(i, _)| i)
6868            .chain(std::iter::once(src.len()))
6869            .collect();
6870        for off in (0..=src.len()).filter(|&o| m.is_stop(o)) {
6871            assert!(
6872                boundaries.contains(&off),
6873                "stop at {off} is inside a character:\n{}",
6874                rendered(&m)
6875            );
6876        }
6877    }
6878
6879    #[test]
6880    fn a_wrapped_cell_keeps_every_line_inside_its_column() {
6881        // The width is a promise in a table, where a glyph past the column lands
6882        // on the border or in the next cell — and it is a promise about cells,
6883        // which is not what a count of glyphs measures.
6884        let src = "| A |\n|---|\n| 你好世界漢字 |\n";
6885        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6886        let m = build_t(&ed.nodes().unwrap(), src, Some(14));
6887        for r in &m.rows {
6888            assert_eq!(r.width(), 14, "{:?} is not drawn to the grid", rendered(&m));
6889        }
6890    }
6891
6892    #[test]
6893    fn a_hard_break_falls_between_clusters_and_measures_in_cells() {
6894        let glyphs = |s: &str| {
6895            let mut out = Vec::new();
6896            push_text(&mut out, s, 0, Style::default());
6897            out
6898        };
6899        let piece = |p: &[Glyph]| p.iter().map(|g| g.ch).collect::<String>();
6900
6901        // Six cells of CJK broken at four: two characters, then one — never
6902        // between the two cells of `好`.
6903        let w = glyphs("你好世");
6904        let pieces: Vec<String> = hard_break(&w, 4).iter().map(|p| piece(p)).collect();
6905        assert_eq!(pieces, ["你好", "世"]);
6906
6907        // A character wider than the column has nowhere legal to break, so it
6908        // keeps its cells rather than being cut in half.
6909        let w = glyphs("你好");
6910        let pieces: Vec<String> = hard_break(&w, 1).iter().map(|p| piece(p)).collect();
6911        assert_eq!(pieces, ["你", "好"]);
6912
6913        // An empty word yields no pieces at all — a double space stays a space.
6914        assert!(hard_break(&[], 4).is_empty());
6915    }
6916
6917    #[test]
6918    fn an_empty_list_item_still_gets_a_bulleted_row_with_a_caret_home() {
6919        // Pressing Enter at the end of a list item opens a new, empty item —
6920        // a childless `list_item`. Without a row of its own the new bullet
6921        // wouldn't appear until something was typed into it (the caret would be
6922        // stranded on an offset no row draws). It now renders as one prefixed
6923        // row whose end is a caret stop, so the bullet shows and the caret lands
6924        // just past the marker.
6925        let m = map("- item\n- \n");
6926        assert_eq!(m.num_rows(), 2, "the empty second item needs its own row");
6927        assert_eq!(
6928            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
6929            "• ",
6930            "the empty item draws just its bullet",
6931        );
6932        // Its end is the caret home (past the `- ` marker), and it's a real stop.
6933        assert!(
6934            m.is_stop(m.rows[1].end_src),
6935            "the empty item's caret home is not a stop"
6936        );
6937        assert_eq!(
6938            m.pos_of_offset(m.rows[1].end_src),
6939            (1, 2),
6940            "caret sits after '• '"
6941        );
6942    }
6943
6944    #[test]
6945    fn a_notes_row_range_stops_at_the_note_even_when_it_ends_in_a_link() {
6946        // The peek bug: a note whose body ends in a link has its last byte
6947        // inside the hidden destination, so mapping `end - 1` through
6948        // `pos_of_offset` snapped *forward* — past its own row, past the drawn
6949        // gap, and onto the next note's row. The popover then drew both notes.
6950        let src = "A[^1] B[^2].\n\n[^1]: bare text\n\n[^2]: [title](https://example.com/x)\n\n[^3]: last\n";
6951        let m = map(src);
6952        let body = src.find("[title]").unwrap();
6953        let end = src.find("\n\n[^3]").unwrap();
6954
6955        let (first, last) = m.row_range_for(body..end);
6956        assert_eq!(
6957            first, last,
6958            "a one-block note is one row, not a span onto the next"
6959        );
6960
6961        // The old arithmetic, kept here as the thing that must stay wrong: it
6962        // is what this method exists instead of.
6963        assert_ne!(
6964            m.pos_of_offset(end - 1).0,
6965            last,
6966            "the forward snap still leaves the note's row — that is the whole point",
6967        );
6968
6969        // A note ending in *visible* text was never broken, and still isn't:
6970        // both readings agree there, which is why the original test missed it.
6971        let plain = src.find("bare text").unwrap();
6972        let plain_end = src.find("\n\n[^2]").unwrap();
6973        let (pf, pl) = m.row_range_for(plain..plain_end);
6974        assert_eq!(pf, pl);
6975        assert_eq!(m.pos_of_offset(plain_end - 1).0, pl);
6976    }
6977
6978    #[test]
6979    fn a_row_range_covers_every_row_of_a_block_that_spans_several() {
6980        // The range is a span, not a point: a quote of two paragraphs covers its
6981        // gap row and both of its text rows, so a peek draws the whole thing.
6982        let src = "> one\n>\n> two\n\nafter\n";
6983        let m = map(src);
6984        let (first, last) = m.row_range_for(0..src.find("\n\nafter").unwrap());
6985        assert_eq!((first, last), (0, 2));
6986
6987        // And a range with no visible byte at all still covers the row it opened
6988        // on, rather than collapsing to nothing.
6989        let (f, l) = m.row_range_for(0..1);
6990        assert_eq!((f, l), (0, 0));
6991    }
6992
6993    #[test]
6994    fn an_empty_block_quote_still_gets_a_gutter_row_with_a_caret_home() {
6995        // The peer of the empty list item, and the case that made an empty line
6996        // in a quote draw as plain body text: a childless `block_quote` — a bare
6997        // `> `, which is what the toolbar's Quote button leaves on a blank line —
6998        // has no inner block to carry the gutter, so the whole quote used to
6999        // render as *nothing*. It didn't merely lose its bar; the row went away
7000        // and the caret had no home on it.
7001        let m = map("a\n\n> \n\nb\n");
7002        assert_eq!(
7003            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
7004            "│ ",
7005            "the empty quote draws just its gutter",
7006        );
7007        assert!(
7008            m.rows[2]
7009                .glyphs
7010                .iter()
7011                .all(|g| g.style.role == Role::QuoteGutter)
7012        );
7013        assert!(
7014            !m.rows[2].decoration,
7015            "it is a line text can go on, not a drawn gap"
7016        );
7017        assert!(
7018            m.is_stop(m.rows[2].end_src),
7019            "the empty quote's caret home is not a stop"
7020        );
7021        assert_eq!(
7022            m.pos_of_offset(m.rows[2].end_src),
7023            (2, 2),
7024            "caret sits after '│ '"
7025        );
7026
7027        // And a document that is *only* an empty quote still renders a row — it
7028        // used to render none at all, leaving the caret nowhere to stand.
7029        let m = map("> \n");
7030        assert_eq!(m.num_rows(), 1);
7031        assert_eq!(
7032            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7033            "│ "
7034        );
7035    }
7036
7037    #[test]
7038    fn a_quotes_own_trailing_marker_lines_stay_inside_the_quote() {
7039        // Enter at the end of `> a` writes `> a\n>\n> \n`. Those last two lines
7040        // hold no block — a quote's `content_span` stops at its last child — so
7041        // the children walk never reaches them, and they used to fall through to
7042        // the document-level trailing pass, which knows no prefix: the gutter
7043        // stopped and the writer's new line drew as plain prose. Fixable only
7044        // since twig 3.2.0, where the quote's *span* covers its own marker lines
7045        // (`0..3` before, `0..8` now) and there is finally a node saying they
7046        // are the quote's.
7047        let m = map("> a\n>\n> \n");
7048        assert_eq!(m.num_rows(), 3, "one row per line the quote spells");
7049        for (i, row) in m.rows.iter().enumerate() {
7050            let text = row.glyphs.iter().map(|g| g.ch).collect::<String>();
7051            assert!(text.starts_with("│ "), "row {i} lost the gutter: {text:?}");
7052            assert!(
7053                !row.decoration,
7054                "row {i} is a line to type on, not a drawn gap"
7055            );
7056            assert!(m.is_stop(row.end_src), "row {i} has no caret home");
7057        }
7058        assert_eq!(
7059            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7060            "│ a"
7061        );
7062        // Distinct offsets, so ↑/↓ between them moves the caret rather than
7063        // landing twice on the same byte.
7064        assert!(m.rows[0].end_src < m.rows[1].end_src);
7065        assert!(m.rows[1].end_src < m.rows[2].end_src);
7066
7067        // A blank line *after* the quote is not the quote's: it is spelled with
7068        // no marker, so it stays an ordinary boundary and the gutter ends.
7069        let m = map("> a\n\nb\n");
7070        assert_eq!(m.num_rows(), 3);
7071        assert_eq!(
7072            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
7073            "b"
7074        );
7075        assert!(
7076            !m.rows[1]
7077                .glyphs
7078                .iter()
7079                .any(|g| g.style.role == Role::QuoteGutter)
7080        );
7081
7082        // Nesting is the case this could get wrong, and the depth has to come
7083        // from which quote's span the line falls in rather than from the row
7084        // above it. A trailing `>` under `> > a` matches only the OUTER quote,
7085        // so it wears one gutter; spell it `> >` and it wears two.
7086        let m = map("> > a\n>\n");
7087        assert_eq!(
7088            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7089            "│ │ a"
7090        );
7091        assert_eq!(
7092            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
7093            "│ "
7094        );
7095        let m = map("> > a\n> >\n");
7096        assert_eq!(
7097            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
7098            "│ │ "
7099        );
7100
7101        // And a marker line BETWEEN two quoted paragraphs is untouched: that is
7102        // the boundary `emit_separators_before` spells, and it stays a drawn gap
7103        // rather than becoming a line to type on.
7104        let m = map("> a\n>\n> b\n");
7105        assert_eq!(m.num_rows(), 3);
7106        assert!(
7107            m.rows[1].decoration,
7108            "the gap between two quoted blocks is still a gap"
7109        );
7110    }
7111
7112    #[test]
7113    fn an_empty_ordered_item_gets_its_number_and_a_caret_home() {
7114        let m = map("1. item\n2. \n");
7115        assert_eq!(m.num_rows(), 2);
7116        assert_eq!(
7117            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
7118            "2. "
7119        );
7120        assert!(m.is_stop(m.rows[1].end_src));
7121        assert_eq!(
7122            m.pos_of_offset(m.rows[1].end_src),
7123            (1, 3),
7124            "caret sits after '2. '"
7125        );
7126    }
7127
7128    #[test]
7129    fn an_empty_headings_caret_home_is_past_its_hidden_marker() {
7130        // The toolbar's H1 on a blank line writes `# ` and nothing else. The row
7131        // it renders is empty (the marker is hidden), so its end *is* its only
7132        // caret stop — and it has to be the offset past the `# `, where typing
7133        // continues the heading. Anchored at the block's start instead, the caret
7134        // drew in front of the hashes and the first character typed there landed
7135        // before them (`x# `), which isn't a heading at all.
7136        let m = map("# \n");
7137        assert_eq!(m.num_rows(), 1);
7138        assert!(m.rows[0].glyphs.is_empty(), "the `# ` marker is hidden");
7139        assert_eq!(m.rows[0].end_src, 2, "the caret home is past the marker");
7140        assert!(m.is_stop(2), "the empty heading's caret home is not a stop");
7141    }
7142
7143    #[test]
7144    fn a_headings_rows_carry_its_level_even_with_nothing_typed_in_it() {
7145        // The row-level fact a proportional frontend sizes a whole line by. An
7146        // empty heading has no glyph to read a `Role::Heading` off, so a renderer
7147        // scanning glyphs drew `# ` (and its caret) at body height until the
7148        // first character landed.
7149        let m = map("# \n");
7150        assert_eq!(
7151            m.rows[0].heading,
7152            Some(1),
7153            "the empty heading knows its level"
7154        );
7155
7156        // Every row of one that wraps, not just the first — and nothing else.
7157        let m = map_at(
7158            "## a heading long enough to wrap over two rows\n\nbody\n",
7159            Some(20),
7160        );
7161        let heads: Vec<Option<u8>> = m.rows.iter().map(|r| r.heading).collect();
7162        assert!(
7163            heads.iter().filter(|h| **h == Some(2)).count() >= 2,
7164            "got {heads:?}"
7165        );
7166        assert_eq!(
7167            m.rows.last().and_then(|r| r.heading),
7168            None,
7169            "the paragraph under it is not a heading",
7170        );
7171    }
7172
7173    #[test]
7174    fn an_empty_heading_leaves_the_rows_under_it_at_their_own_offsets() {
7175        // The row's end is also what the *next* row's separator is measured from,
7176        // so an empty heading that under-reported it shifted every offset below —
7177        // and the blank line under the heading then claimed the same offset as the
7178        // heading's own end. `pos_of_offset` resolves such a tie downstream (a
7179        // soft wrap belongs to the row below), so the caret at the end of the
7180        // heading was drawn two rows lower, on the blank line.
7181        // `text\n\n# \n\n`: the heading's content opens at 8, and the two rows
7182        // under it end at 9 and 10 — the blank line and the document's end.
7183        let m = map("text\n\n# \n\n");
7184        let end = m.rows.last().expect("a trailing blank row").end_src;
7185        assert_eq!(end, 10, "the trailing rows must end at their real offsets");
7186        // The heading's caret home is its own row's, not one shared with a row
7187        // below — the tie that drew the caret two rows down.
7188        assert_eq!(m.pos_of_offset(8), (2, 0), "the empty heading's own row");
7189        assert!(
7190            m.rows[3..].iter().all(|r| r.end_src > 8),
7191            "rows below own later offsets"
7192        );
7193    }
7194
7195    // ── block boundaries ─────────────────────────────────────────────────────
7196
7197    /// Every drawn boundary in `src`, in order, as `(above, below)`.
7198    fn boundaries(m: &VisualMap) -> Vec<(BlockClass, BlockClass)> {
7199        m.rows
7200            .iter()
7201            .filter_map(|r| r.boundary)
7202            .map(|b| (b.above, b.below))
7203            .collect()
7204    }
7205
7206    #[test]
7207    fn a_boundary_says_which_blocks_it_divides() {
7208        use BlockClass::*;
7209        let m = map("one\n\ntwo\n\n# Head\n\ntail\n\n> quoted\n\n```\ncode\n```\n");
7210        assert_eq!(
7211            boundaries(&m),
7212            vec![
7213                (Paragraph, Paragraph),
7214                (Paragraph, Heading),
7215                (Heading, Paragraph),
7216                (Paragraph, Quote),
7217                (Quote, Code),
7218                // The blank the document trails off with is a boundary too — it
7219                // closes the last block above the empty paragraph the caret rests
7220                // on. See `emit_trailing_blank_lines`.
7221                (Code, Paragraph),
7222            ],
7223            "each gap names the pair it falls between, in document order"
7224        );
7225    }
7226
7227    #[test]
7228    fn the_trailing_gap_closes_the_last_block() {
7229        // Two Enters at the end of a document: a drawn gap, then the navigable
7230        // empty paragraph. Only the gap is labelled, so a frontend that shrinks
7231        // boundaries shrinks the spacer and leaves the row being typed on alone.
7232        let m = map("# Head\n\n\n");
7233        assert_eq!(
7234            boundaries(&m),
7235            vec![(BlockClass::Heading, BlockClass::Paragraph)]
7236        );
7237    }
7238
7239    #[test]
7240    fn only_the_drawn_gap_rows_carry_a_boundary() {
7241        let m = map("one\n\ntwo\n");
7242        for row in &m.rows {
7243            assert_eq!(
7244                row.boundary.is_some(),
7245                row.decoration,
7246                "a boundary is exactly a drawn gap row: {:?}",
7247                row.glyphs.iter().map(|g| g.ch).collect::<String>()
7248            );
7249        }
7250    }
7251
7252    #[test]
7253    fn preserve_flow_labels_no_boundary() {
7254        // Every blank line is a caret home there — somewhere text can go, not a
7255        // gap between blocks — so nothing is drawn-only and nothing is labelled.
7256        // A frontend keying its spacing off `boundary` can't shrink a row the
7257        // author is about to type on.
7258        let m = map_preserve("one\n\ntwo\n\n# Head\n", Some(80));
7259        assert!(boundaries(&m).is_empty());
7260    }
7261
7262    #[test]
7263    fn a_list_draws_no_boundary_between_its_items() {
7264        // Tight or loose, core puts no gap row between two items of one list —
7265        // so an item↔item boundary is a shape no frontend will ever be handed,
7266        // and spacing one is spacing something that isn't there.
7267        for src in ["- one\n- two\n", "- one\n\n- two\n"] {
7268            let m = map(src);
7269            assert!(
7270                boundaries(&m).is_empty(),
7271                "no gap row inside the list of {src:?}"
7272            );
7273        }
7274        // Leaving the list is an ordinary boundary, and the list is named as
7275        // what sits above it.
7276        let m = map("- one\n- two\n\npara\n");
7277        assert_eq!(
7278            boundaries(&m),
7279            vec![(BlockClass::List, BlockClass::Paragraph)]
7280        );
7281    }
7282
7283    #[test]
7284    fn a_nested_boundary_names_the_blocks_inside_the_container() {
7285        // Two paragraphs inside a blockquote are divided by a Paragraph↔Paragraph
7286        // boundary — the quote is the container they're both in, not what the gap
7287        // separates.
7288        let m = map("> one\n>\n> two\n");
7289        assert_eq!(
7290            boundaries(&m),
7291            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
7292        );
7293    }
7294
7295    #[test]
7296    fn a_directive_container_draws_one_boundary_like_every_other_block() {
7297        // A container's rows stop at its last *child*, so without anchoring
7298        // `last_off` past the closing `:::` the separator logic counted the fence
7299        // line as a blank row of its own and drew the gap twice — one authored
7300        // blank line, two boundaries, and a frontend spacing each of them put
7301        // double margin under every fenced div. The code-block arm anchors past
7302        // its ``` for exactly this reason; compare the two here.
7303        let fenced = map_directives(":::note\nin\n:::\n\ntwo\n");
7304        assert_eq!(
7305            boundaries(&fenced),
7306            vec![(BlockClass::Directive, BlockClass::Paragraph)],
7307            "one authored gap, one boundary row"
7308        );
7309        let code = map("```\nc\n```\n\ntwo\n");
7310        assert_eq!(
7311            boundaries(&code).len(),
7312            boundaries(&fenced).len(),
7313            "a fenced div spaces like a fenced code block"
7314        );
7315        // Nesting closes several fences at once; still one gap.
7316        let nested = map_directives(":::a\n:::b\nin\n:::\n:::\n\ntwo\n");
7317        assert_eq!(
7318            boundaries(&nested),
7319            vec![(BlockClass::Directive, BlockClass::Paragraph)]
7320        );
7321    }
7322
7323    #[test]
7324    fn a_block_media_names_itself_in_the_boundaries_either_side() {
7325        use BlockClass::*;
7326        // A block image is never a node of its own — `media_only` promotes the
7327        // *paragraph* wrapping it — so classifying the node the walk stands on
7328        // called the picture `Paragraph` and left `BlockClass::Media` unreachable:
7329        // a frontend could not give a photo more air than a line of prose.
7330        // `label_media_boundaries` reads it back off the finished rows instead.
7331        let m = map("one\n\n![alt](p.png)\n\ntwo\n");
7332        assert_eq!(boundaries(&m), vec![(Paragraph, Media), (Media, Paragraph)]);
7333        // At the edges of the document too: the leading gap has no boundary of
7334        // its own, and the trailing one is `emit_trailing_blank_lines`'.
7335        let edges = map("![a](p.png)\n\nmid\n\n![b](q.png)\n");
7336        assert_eq!(
7337            boundaries(&edges),
7338            vec![(Media, Paragraph), (Paragraph, Media)]
7339        );
7340        // One gap spelled with several rows — the row closing the block above and
7341        // the row opening the one below, with the author's spare blank line
7342        // navigable between them — carries the same pair on every drawn row.
7343        let roomy = map("one\n\n\n\n![alt](p.png)\n");
7344        assert_eq!(
7345            boundaries(&roomy),
7346            vec![(Paragraph, Media), (Paragraph, Media)]
7347        );
7348    }
7349
7350    #[test]
7351    fn a_block_video_is_media_at_its_boundaries_not_a_directive_panel() {
7352        // Worse than the image case before `label_media_boundaries`: a `<video>`
7353        // arrives as twig's generic `container`, which classifies `Directive` —
7354        // the one class a frontend reads as "draw a tinted panel here". A movie
7355        // got the chrome of a fenced div.
7356        let mut doc = crate::Doc::from_source(
7357            "one\n\n<video src=\"v.mp4\"></video>\n\ntwo\n".to_string(),
7358            Format::Markdown,
7359        )
7360        .unwrap();
7361        doc.build_visual(80);
7362        assert_eq!(
7363            boundaries(&doc.vmap),
7364            vec![
7365                (BlockClass::Paragraph, BlockClass::Media),
7366                (BlockClass::Media, BlockClass::Paragraph),
7367            ]
7368        );
7369    }
7370
7371    #[test]
7372    fn the_incremental_walk_labels_boundaries_like_the_full_one() {
7373        // `assert_maps_eq` compares boundaries too, so this pins the two doors
7374        // into `BlockClass::from_node_kind` — a `FlatNode`'s kind on the full
7375        // build, a query match's on the cached one — against a document with one
7376        // of every boundary in it.
7377        let src = "one\n\n# Head\n\ntwo\n\n- a\n- b\n\n> q\n\n```\nc\n```\n\npara\n";
7378        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7379        let mut cache = BlockCache::default();
7380        let (full, cached) = render_both(&mut ed, src, Some(80), &mut cache);
7381        assert_maps_eq(&full, &cached, "boundary labelling");
7382        assert!(
7383            !boundaries(&full).is_empty(),
7384            "the fixture has boundaries to compare"
7385        );
7386    }
7387
7388    #[test]
7389    fn every_caret_stop_opens_a_cluster_of_its_row() {
7390        // The two ways of finding a cluster have to agree. `push_text` marks the
7391        // stops by segmenting one run of text; the column mapping segments the
7392        // whole row, decoration and all. A stop that came out as the *middle* of
7393        // some row-level cluster would be a caret with no column of its own —
7394        // drawn at the column of whatever swallowed it.
7395        let src = "# 標題\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` 你好\n\n\
7396                   - 項目 one\n- e\u{0301}dge\n\n> 引用 text\n\n\
7397                   | A | 值 |\n|---|---|\n| 你好 | 👩‍🚀 |\n";
7398        let m = map(src);
7399        for (r, row) in m.rows.iter().enumerate() {
7400            let openers: Vec<usize> = clusters(&row.glyphs).iter().map(|c| c.glyph).collect();
7401            for (i, g) in row.glyphs.iter().enumerate() {
7402                assert!(
7403                    !g.stop || openers.contains(&i),
7404                    "row {r}: the stop at glyph {i} ({:?}) is inside a cluster, \
7405                     so it is drawn at another glyph's column",
7406                    g.ch
7407                );
7408            }
7409        }
7410    }
7411}