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