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