Skip to main content

leaf_core/
wysiwyg.rs

1//! The WYSIWYG view: render the document with its markup *resolved*, not shown —
2//! headings and code tagged with a typographic role (a frontend sizes or colours
3//! them; see [`crate::style`]), `**bold**` as real bold, `# ` / `**` / `` ` ``
4//! delimiters hidden — while keeping every visible glyph tied back to the source
5//! byte it came from.
6//!
7//! That back-reference (`Glyph::src`) is what lets a caret still work: the caret
8//! stays a source offset (shared with the source view), but the [`VisualMap`]
9//! converts between an offset and a screen `(row, col)`, so cursor drawing,
10//! mouse clicks, and vertical motion all operate in *visible* space.
11//!
12//! Left and Right instead walk the map's caret *stops* in document order. On
13//! ordinary prose that's the same journey — the stops are laid out left to right
14//! — and it steps over the hidden delimiters either way. They part company only
15//! in a table, where the text is arranged in two dimensions and a cell wrapped
16//! within its column continues *below* rather than to the right. Following the
17//! document is what a caret means there.
18//!
19//! Text is walked from the AST (`str` nodes carry exact spans, and their text is
20//! the verbatim source slice), so a Markdown and a Djot file that parse alike
21//! render — and map — identically.
22
23use std::cell::{Cell, RefCell};
24use std::collections::HashMap;
25use std::ops::Range;
26use std::sync::OnceLock;
27
28use twig::{Alignment, ContainerOrigin, DirectiveForm, Editor, FlatNode, Kind, QueryMatch};
29use unicode_segmentation::UnicodeSegmentation;
30use unicode_width::UnicodeWidthStr;
31
32use crate::style::{
33    Align, Baseline, FaceId, FaceRef, FaceTable, FontSize, LineHeight, MarkColor, Role, Style,
34    TextColor, Token,
35};
36
37/// One rendered character plus the source byte offset it originates from.
38/// Synthetic glyphs (a list bullet, a quote gutter) point at their block's
39/// start, so clicking one lands the caret at the start of that block.
40#[derive(Clone)]
41pub struct Glyph {
42    pub ch: char,
43    pub style: Style,
44    pub src: usize,
45    /// Whether the caret may *rest* on this glyph. Decoration — a table border
46    /// or a cell's alignment padding — is visible but isn't text, so the caret
47    /// steps over it instead of into it. It also can't be a stop even in
48    /// principle: a run of decoration shares one `src`, and a caret can only
49    /// move by changing offset, so resting on it would pin horizontal motion.
50    /// A click still maps through `src`, which is why decoration points at the
51    /// text it decorates.
52    ///
53    /// Real text is a stop once per *grapheme cluster*, on the glyph that opens
54    /// it: the continuation glyphs of an emoji or an accented letter are drawn,
55    /// but standing between them is standing inside a character.
56    pub stop: bool,
57}
58
59/// One visual line. `end_src` is the source offset a caret sits at when placed
60/// at the line's end (past its last glyph) — the anchor for end-of-line and
61/// click-past-content.
62///
63/// `Clone` so a block's rows can be cached and re-emitted at a shifted offset
64/// across an edit — see [`BlockCache`].
65#[derive(Clone)]
66pub struct VRow {
67    pub glyphs: Vec<Glyph>,
68    pub end_src: usize,
69    /// A row that is drawn but holds no caret: a table's `├───┼───┤` rules, and
70    /// the blank gap a block boundary is spelled with. Vertical motion steps
71    /// over it, `pos_of_offset` never resolves onto it, and its stops (it has
72    /// none) and `end_src` stay out of the map's stop table.
73    ///
74    /// Emptiness isn't the test — an empty paragraph is a blank row too, and a
75    /// real caret stop. The test is whether the row is somewhere text can go.
76    pub decoration: bool,
77    /// This row is one line of a fenced or indented code block. Set on every row
78    /// the `"code_block"` arm emits — including its blank lines, which carry no
79    /// glyph to tell them apart otherwise. A frontend draws its own chrome (a
80    /// border and a tinted background) around each maximal run of these, and
81    /// scrolls them horizontally instead of wrapping; see
82    /// [`VisualMap::code_blocks`]. Survives the row shuffling of [`BlockCache`]
83    /// reuse and [`build_spliced`] because it rides on the row, not on a
84    /// row-index span the way a table's picture does.
85    pub code: bool,
86    /// A fenced code block's info string (its language), carried on the *first*
87    /// row of the block so it survives row reuse the way [`code`](Self::code)
88    /// does. `None` on every other row, and on an indented block (which has no
89    /// fence to label). A frontend paints it as a small label on the block's box
90    /// and edits it through a prompt — see [`CodeBlockInfo::lang`]. It's a plain
91    /// display string, not a source slice, so it needs no offset shifting; the
92    /// label re-derives from twig on the next build.
93    pub code_lang: Option<String>,
94    /// This row belongs to a `:::name{.class}` directive container — twig's
95    /// generic fenced-div block, whose meaning is entirely up to the host app
96    /// (diaryx's `:::vis{.audience}` visibility blocks, say). Set on every row
97    /// the `"directive"` arm emits, the same way [`code`](Self::code) marks a
98    /// code block's rows, so a frontend can draw a tinted panel around each
99    /// maximal run of these.
100    pub directive: bool,
101    /// A directive container's space-joined attrs — dot-prefixed classes
102    /// (`.public .family` → `"public family"`) unioned with bare pandoc-style
103    /// words (`public family`, no leading dot — diaryx's other `:::vis{...}`
104    /// convention), carried on the block's *first* row only — the
105    /// [`code_lang`](Self::code_lang) pattern. `None` on every other row, and
106    /// when the directive carries no such attrs. A frontend paints it as a
107    /// small label on the block's panel; it's a plain display string, not a
108    /// source slice, so it rides row reuse untouched.
109    pub directive_label: Option<String>,
110    /// Set on the single placeholder row a block-level image renders to, carrying
111    /// the image's destination and alt text; `None` on every other row. The row's
112    /// glyphs are the default `🖼 alt` label (which a plain surface paints as-is);
113    /// an image-capable frontend reads this to paint the real picture instead,
114    /// skipping the row named by [`MediaInfo::rows_span`]. Like
115    /// [`code_lang`](Self::code_lang) it's plain display strings, not source
116    /// slices, so it rides row reuse and needs no offset shifting; the map's
117    /// [`media`](VisualMap::media) side-table is derived from it once the rows
118    /// are final, the same way [`code_blocks`](VisualMap::code_blocks) is.
119    pub media: Option<MediaMark>,
120    /// Set on the **first** row of a task list item, carrying whether its box is
121    /// ticked; `None` on every other row, including a plain `list_item`'s. The
122    /// row's glyphs already draw the box as `☐ `/`☑ ` in the marker's place, so a
123    /// plain surface needs nothing further; a GUI reads this to paint a real
124    /// checkbox widget and to know which way it is facing.
125    ///
126    /// A `bool` rather than a source span, for the reason
127    /// [`code_lang`](Self::code_lang) is a plain string: it rides [`BlockCache`]
128    /// reuse and [`build_spliced`] untouched, needing no offset shifting. To
129    /// *toggle* the box, a frontend maps its click to a source offset the way it
130    /// maps any other — the marker's glyphs carry the item's own `src` — and
131    /// hands that to [`crate::Doc::toggle_task_at`].
132    pub task: Option<bool>,
133    /// Set on the single placeholder row a **leaf** directive (`::name{…}`)
134    /// renders to, carrying its name and attributes; `None` on every other row.
135    /// The container form isn't this — it wraps real blocks and marks each of
136    /// them [`directive`](Self::directive) instead. Like [`media`](Self::media)
137    /// it's plain display strings, so it rides row reuse untouched, and the map's
138    /// [`directives`](VisualMap::directives) side-table is derived from it once
139    /// the rows are final.
140    pub leaf_directive: Option<DirectiveMark>,
141    /// The heading level (1–6) of the block this row belongs to, on every row a
142    /// `heading` emits (a long one wraps to several) and `None` everywhere else.
143    ///
144    /// A frontend that sizes a whole line — a proportional renderer giving the
145    /// row a bigger line box — needs the level *per row*, and the glyphs can't
146    /// always supply it: an empty heading (`# ` with nothing typed after it,
147    /// which is what the toolbar's H1 leaves on a blank line) has no glyph to
148    /// carry a [`Role::Heading`] at all, so a glyph scan called it body text and
149    /// the line drew at body height until the first character landed. Riding the
150    /// row says it once, for the empty case and the wrapped case alike.
151    ///
152    /// Per-*glyph* styling still comes from [`Role::Heading`] on the glyphs; this
153    /// is the row-level fact, and the two agree wherever a heading has content —
154    /// same `u8` level, clamped the same way [`heading_style`] clamps it.
155    pub heading: Option<u8>,
156    /// How this row's block is aligned across the measure — the author's
157    /// `class="center"`, on every row the block emits and `None` for the
158    /// theme's default, which is left.
159    ///
160    /// A *row* fact and not a glyph one for [`heading`](Self::heading)'s reason,
161    /// and more sharply: alignment is a property of the *line*, not of the
162    /// letters on it, so an empty paragraph the author has just centred has to
163    /// carry it with no glyph to hang it on. It rides the row like a plain
164    /// `Copy` flag, so [`BlockCache`] reuse and [`build_spliced`] carry it
165    /// untouched.
166    ///
167    /// Read from the paragraph's or heading's own attributes and from those of
168    /// every `div` around it, the nearest winning — so `<div class="center">`
169    /// around three paragraphs centres all three, which is what the author of
170    /// that HTML meant.
171    pub align: Option<Align>,
172    /// How far apart this row's block sets its lines, as a multiple of the
173    /// theme's own line height — the author's `data-line-height`, on every row
174    /// the block emits and `None` for the theme's spacing.
175    ///
176    /// A frontend that lays rows out in pixels scales the row's height by
177    /// [`LineHeight::as_f32`]; one that draws a row per terminal line ignores
178    /// it, the way it ignores a heading's size. Read at the same two levels
179    /// [`align`](Self::align) is, and one of the menu's three names or the
180    /// exact ratio the author asked for.
181    pub line_height: Option<LineHeight>,
182    /// What this row divides, on the blank rows a block boundary is *drawn* with
183    /// and `None` on every other row — including the navigable blank lines of
184    /// preserve-soft flow, which are somewhere text can go rather than a gap
185    /// between blocks. So `boundary.is_some()` is exactly "this row is a drawn
186    /// block boundary", the [`decoration`](Self::decoration) rows that come from
187    /// [`Builder::emit_separators_before`].
188    ///
189    /// It exists because a boundary's *height* is a frontend decision but its
190    /// *kind* is not. Typography spaces a boundary by what it separates — the
191    /// margin above a heading is wider than the one between two paragraphs, so
192    /// the heading groups with the text it introduces — and a frontend that has
193    /// only rows to look at has to re-derive the structure by sniffing glyph
194    /// roles. Three frontends sniffing separately is three chances to disagree
195    /// about the same document. Core already knows, having just walked the AST
196    /// to emit this row, so it says so once here and each frontend multiplies by
197    /// its own spacing.
198    pub boundary: Option<Boundary>,
199    /// The offsets on this row where an inline mark's *content* ends under a
200    /// hidden closing delimiter — the end of the `d` in `**bold**`, one byte
201    /// before the `**` that draws nothing. Each is a caret stop with no glyph
202    /// of its own: the caret standing there is drawn where the next glyph is,
203    /// but typing there extends the mark, where typing past the delimiter
204    /// leaves it. See [`VisualMap::mark_ends`] for the rule.
205    ///
206    /// Source offsets, so [`shift_row`] moves them with the glyphs; empty on
207    /// decoration rows and on every row no mark closes on.
208    pub mark_ends: Vec<usize>,
209    /// The formulas this row stands in for, in glyph order: one [`MathMark`]
210    /// per inline atom on the row, or the single block mark on the
211    /// placeholder row a display formula renders to. Empty on every other
212    /// row, and on the revealed line, where a formula is its TeX and no
213    /// picture stands for it.
214    ///
215    /// Plain strings and a glyph *index* rather than a source offset, for
216    /// [`media`](Self::media)'s reason: the mark rides [`BlockCache`] reuse and
217    /// [`build_spliced`] untouched, and the glyph it names carries the offset.
218    /// The map's [`math`](VisualMap::math) side-table is derived from these
219    /// once the rows are final.
220    pub math: Vec<MathMark>,
221}
222
223/// One formula a row stands in for — what a picture-capable frontend typesets
224/// and draws in place of the glyph or the rows that hold its spot. See
225/// [`VRow::math`] and, for the frontend's view of the same thing,
226/// [`MathInfo`].
227#[derive(Clone, Debug, PartialEq, Eq)]
228pub struct MathMark {
229    /// The TeX between the delimiters, verbatim — a display block's keeps its
230    /// newlines. What `leaf-math` typesets.
231    pub tex: String,
232    /// Display style (`$$…$$`) rather than text style (`$…$`). True for every
233    /// block mark, and for a `$$…$$` written inside a line of prose, which is
234    /// display style set inline.
235    pub display: bool,
236    /// The index into [`VRow::glyphs`] of the atom this mark stands behind —
237    /// the one [`Role::Math`] glyph an inline formula renders to. `None` for
238    /// a block mark, whose placeholder is the whole row.
239    pub glyph: Option<usize>,
240    /// How many rows a block formula reserves — the label row plus the blank
241    /// fillers under it, the [`MediaMark::rows`] recipe, and from the same
242    /// door: a terminal frontend that has typeset and measured the picture
243    /// reports its height through [`crate::Doc::set_math_rows`]. `1` for an
244    /// inline atom, which reserves nothing.
245    pub rows: usize,
246}
247
248/// What a drawn block boundary separates: the kinds of the blocks it falls
249/// between — the pair a frontend spaces by.
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
251pub struct Boundary {
252    pub above: BlockClass,
253    pub below: BlockClass,
254}
255
256/// The block kinds core tells apart when it walks a document — the vocabulary
257/// [`Boundary`] is spelled in. A statement about *structure*, not about how any
258/// of it should look: what a frontend does with "this gap sits above a heading"
259/// is entirely the frontend's.
260///
261/// `Class` rather than `Kind` because [`twig::BlockKind`] already means
262/// something else in this crate's public surface — the *command* vocabulary
263/// (`Paragraph | Heading(n)`) a toolbar passes to [`Doc::set_block`](crate::Doc::set_block).
264/// This is the reverse direction: what a block already *is*, read back off a
265/// rendered row.
266///
267/// [`BlockClass::Other`] is the honest answer for a node kind core doesn't
268/// separate out, so adding one here is additive for every frontend: nothing has
269/// to change until it wants to space that kind differently.
270#[derive(Clone, Copy, Debug, PartialEq, Eq)]
271pub enum BlockClass {
272    Paragraph,
273    Heading,
274    /// A whole list. Its *items* are [`BlockClass::ListItem`]; note that core
275    /// draws no boundary row between two items of one list, tight or loose, so
276    /// an item↔item pair never reaches a frontend.
277    List,
278    ListItem,
279    Quote,
280    Code,
281    Table,
282    /// A block-level image, video, or audio.
283    ///
284    /// Never reached through [`from_node_kind`](BlockClass::from_node_kind): a
285    /// block picture is not a node of its own — [`Builder::media_only`] promotes
286    /// the paragraph (or `<picture>`/`<video>` container) wrapping it — so the
287    /// walk only ever sees the wrapper's kind. [`label_media_boundaries`] reads
288    /// it back off the finished rows instead, after the fact.
289    Media,
290    /// A display formula on lines of its own — a paragraph holding nothing but
291    /// a `$$…$$`. Never reached through [`from_node_kind`](BlockClass::from_node_kind)
292    /// for [`Media`](BlockClass::Media)'s reason: the walk sees the wrapping
293    /// paragraph, and [`label_media_boundaries`] relabels the gaps around the
294    /// placeholder once the rows are final.
295    Math,
296    /// A `:::name{.class}` directive container.
297    Directive,
298    Rule,
299    Footnote,
300    Other,
301}
302
303impl BlockClass {
304    /// Classify a twig node kind — the same vocabulary [`Builder::block`]
305    /// matches on, so the two can't drift about what a block is. Both the
306    /// whole-arena walk (which has [`FlatNode`]s) and the incremental top-level
307    /// walk (which has only a query match's kind) reach it by this one door.
308    pub fn from_node_kind(kind: &Kind) -> BlockClass {
309        match kind {
310            Kind::Para => BlockClass::Paragraph,
311            Kind::Heading => BlockClass::Heading,
312            Kind::BulletList | Kind::OrderedList | Kind::TaskList => BlockClass::List,
313            Kind::ListItem | Kind::TaskListItem => BlockClass::ListItem,
314            Kind::BlockQuote => BlockClass::Quote,
315            Kind::CodeBlock => BlockClass::Code,
316            Kind::Table => BlockClass::Table,
317            Kind::Image => BlockClass::Media,
318            // twig 2.8 folded `div`/`span`/`directive`/`element` into one
319            // `container` kind, so a `:::note` panel and a promoted `<video>`
320            // arrive here indistinguishable — telling them apart needs the
321            // node's `origin`, and the incremental walk has only this kind.
322            // `Directive` is the right answer for the case that motivates the
323            // class (nothing else draws a tinted panel) and a harmless one for
324            // the rest: `BlockClass` is descriptive and core never branches on
325            // it. The one case where it was actively wrong — a promoted
326            // `<video>`, which would have been handed to a frontend as something
327            // to draw a fenced-div panel around — is corrected by
328            // [`label_media_boundaries`] once the rows are final, along the same
329            // door as a block image. Anything else that must be exact reads
330            // [`container_is_directive`] off a real node.
331            Kind::Container => BlockClass::Directive,
332            Kind::ThematicBreak => BlockClass::Rule,
333            Kind::Footnote => BlockClass::Footnote,
334            _ => BlockClass::Other,
335        }
336    }
337}
338
339/// The name and attributes a leaf directive's placeholder row carries, so a
340/// frontend that knows the host app's vocabulary can paint the real thing —
341/// an embedded page for diaryx's `::embed{src=…}`, a generated table of
342/// contents for a `::toc`, and the plain `⧉ name` label for one it doesn't
343/// know. The peer of [`MediaMark`], and plain strings for the same reason: they
344/// survive the row shuffling of [`BlockCache`] reuse and [`build_spliced`].
345#[derive(Clone, Debug, PartialEq, Eq)]
346pub struct DirectiveMark {
347    /// The directive's type — `embed`, `toc`, `vis` — with no leading colons.
348    /// Core is agnostic of what it means: the vocabulary is the host app's.
349    pub name: String,
350    /// Its `{…}` attributes as `(key, value)` pairs in source order. A bare
351    /// attribute (`{public}`) has a `None` value, the way twig reports it.
352    pub attrs: Vec<(String, Option<String>)>,
353    /// The directive's `[label]` text, flattened from its inline children, or
354    /// empty when it has none. Also what the placeholder label shows.
355    pub label: String,
356    /// How many visual rows this directive reserves — the label row plus blank
357    /// filler rows below it, so a frontend painting something real has the
358    /// vertical room. `1` is the bare placeholder, and the only value core
359    /// produces today: unlike an image (whose height a terminal frontend
360    /// measures and reports back), nothing has told core how tall an embed is.
361    /// A pixel-laid-out GUI sets its own height regardless.
362    pub rows: usize,
363}
364
365/// What a block-level media placeholder actually is, so a frontend knows which
366/// widget to build over the reserved rows: a raster, a movie player, or a
367/// transport with no picture at all. Core classifies and stops there — it opens
368/// nothing, so this is a statement about the *markup*, not about a file it has
369/// verified exists or can decode.
370#[derive(Clone, Copy, Debug, PartialEq, Eq)]
371pub enum MediaKind {
372    /// A `![](…)` / `<img>` / `<picture>` — a still picture.
373    Image,
374    /// An HTML `<video>`. Markdown and Djot spell no video of their own, so this
375    /// only ever arrives through `html_elements` promotion (or a `::video{…}`
376    /// directive a host app maps itself, which core reports as a directive).
377    Video,
378    /// An HTML `<audio>` — a transport with no picture, so a frontend gives it a
379    /// fixed control height rather than measuring an aspect ratio.
380    Audio,
381}
382
383/// Which of the two caret homes a block media has — see
384/// [`VisualMap::block_media_stop`].
385#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum MediaStop {
387    /// The stop in front of the picture. What is typed here belongs above it.
388    Before,
389    /// The stop just past it. What is typed here belongs below it.
390    After,
391}
392
393impl MediaKind {
394    /// The emoji a plain surface prefixes the placeholder label with — the
395    /// `🖼`/`🎬`/`🔊` that makes the row read as *a thing* rather than as text.
396    fn sigil(self) -> char {
397        match self {
398            MediaKind::Image => '🖼',
399            MediaKind::Video => '🎬',
400            MediaKind::Audio => '🔊',
401        }
402    }
403}
404
405/// The destination and label a block-level media placeholder row carries, so a
406/// capable frontend can resolve and paint the real thing. Plain strings (no
407/// source offsets), so they survive the row shuffling of [`BlockCache`] reuse
408/// and [`build_spliced`] untouched — see [`VRow::media`].
409#[derive(Clone, Debug, PartialEq, Eq)]
410pub struct MediaMark {
411    /// Whether this is a picture, a movie, or a sound — which widget the
412    /// frontend builds over the reserved rows.
413    pub kind: MediaKind,
414    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
415    /// the AST. A frontend resolves a relative path against the document's
416    /// directory itself; core holds no I/O.
417    ///
418    /// Empty is possible and legal for a `<video>`/`<audio>`, which may carry no
419    /// `src` of its own and name its candidates in child `<source>`s instead —
420    /// unlike an `<img>`, whose `src` *is* the picture. A frontend with an empty
421    /// destination takes its URL from [`sources`](MediaMark::sources).
422    pub destination: String,
423    /// A `<picture>`'s theme/media alternatives, in document order, when this
424    /// block image came from one; empty for a plain `![](…)` / bare `<img>`. Each
425    /// is a `<source>`'s media query + candidate URL(s); a frontend that knows its
426    /// theme picks the first whose media matches and falls back to [`destination`]
427    /// (the `<img>`). Core keeps them verbatim and picks nothing — it has no theme.
428    ///
429    /// [`destination`]: MediaMark::destination
430    pub sources: Vec<MediaSource>,
431    /// The media's alt text (its rendered inline children, flattened), or empty
432    /// when it has none. Also what the placeholder label shows. For a `<video>`/
433    /// `<audio>` this is the element's own text content — the "your browser does
434    /// not support…" fallback, which doubles as its accessible name.
435    pub alt: String,
436    /// A `<video poster="…">`'s still frame, verbatim, or empty when there is
437    /// none (and always empty for an image or audio). It is an *image*
438    /// destination, so a frontend already able to draw a picture can show it
439    /// before the movie loads — or in place of one it can't play at all.
440    pub poster: String,
441    /// How many visual rows this media reserves — the placeholder label row plus
442    /// the blank filler rows below it, so a frontend that paints a real raster has
443    /// the vertical room to draw it. `1` is the bare placeholder (a frontend that
444    /// can't draw pictures, or an image it couldn't resolve). A terminal frontend
445    /// asks for as many rows as the fitted picture is tall; the pixel-laid-out GUI
446    /// ignores this and sets its own row height, so it always leaves it `1`. The
447    /// count comes from the frontend (via [`crate::Doc::set_media_rows`]) because
448    /// core does no I/O and can't measure the image itself. See [`VRow::media`].
449    pub rows: usize,
450}
451
452/// One `<source>` under a `<picture>`, `<video>`, or `<audio>`: a candidate URL
453/// plus whichever of the two things HTML lets a `<source>` be chosen by — a
454/// media query (`<picture>`) or a MIME type (`<video>`/`<audio>`). Verbatim from
455/// the AST: core carries the alternatives and resolves none of them, having
456/// neither a theme nor a codec list to judge them by.
457///
458/// The two spellings are normalised onto one field. `<picture>` writes
459/// `srcset`, `<video>`/`<audio>` write `src`; both land in
460/// [`srcset`](MediaSource::srcset), since a frontend wants the URL either way
461/// and only `<picture>` ever uses the descriptor syntax.
462#[derive(Clone, Debug, PartialEq, Eq)]
463pub struct MediaSource {
464    /// The `<source media="…">` query, verbatim (`"(prefers-color-scheme: dark)"`),
465    /// or empty for a `<source>` with no `media` (an unconditional override, and
466    /// the norm for `<video>`/`<audio>`, which pick by codec rather than theme).
467    pub media: String,
468    /// The candidate URL(s): a `<picture>`'s `srcset` verbatim — one URL, or a
469    /// comma-separated candidate list with `1x`/`2x`/width descriptors — or a
470    /// `<video>`/`<audio>` `<source>`'s plain `src`. A frontend takes the first
471    /// URL token; the theme and codec cases both only ever need that.
472    pub srcset: String,
473    /// The `<source type="…">` MIME type (`"video/webm"`), verbatim, or empty
474    /// when the `<source>` declares none. How a `<video>`/`<audio>` frontend
475    /// picks a candidate it can actually decode; a `<picture>`'s sources
476    /// normally leave it empty and are chosen by [`media`](MediaSource::media).
477    pub mime: String,
478}
479
480/// The rendered document plus the offset⇄position mapping the caret rides on.
481#[derive(Clone, Default)]
482pub struct VisualMap {
483    /// The document's **default monospace rendering** — one [`VRow`] of glyphs
484    /// per visual line, tables spelled with box-drawing borders (`│ ─ ┌┬┐…`) and
485    /// cells padded to whole character-cell columns. Any monospace surface can
486    /// draw these verbatim, so a consumer gets a working view for free: the TUI
487    /// paints them as-is, and a five-line plain-text dump would too.
488    ///
489    /// It's a *default*, not the only truth. A frontend with its own geometry —
490    /// a proportional GUI — lays text out in its own units, and for a table
491    /// skips the box-drawn rows named by [`TableInfo::rows_span`] and draws from
492    /// the structural [`TableInfo`] instead. The box glyphs live here rather than
493    /// in a frontend precisely because they *are* a renderable default: unlike a
494    /// colour (a role each surface must map to its own palette — see
495    /// [`crate::style`]), `┌─┐` is finished text that needs no interpretation.
496    pub rows: Vec<VRow>,
497    /// The first source offset that is actually rendered — the caret floor for
498    /// the WYSIWYG view. Non-zero when a leading `metadata` block (YAML/TOML
499    /// frontmatter) is skipped: the frontmatter is preserved in the source and
500    /// editable in the source view, but hidden and unreachable here, so the
501    /// caret and selection can't wander into it (and copy won't grab it).
502    pub content_start: usize,
503    /// Every offset the caret may rest at, ascending and deduplicated: each
504    /// row's stop glyphs plus the row's own end (the "after the last character"
505    /// spot every line needs). Decoration contributes nothing.
506    ///
507    /// Left/Right read this instead of walking the grid, because the grid isn't
508    /// laid out in offset order: a table with wrapped cells puts column 1's
509    /// second line *below* column 2's first, so "the next stop rightward" and
510    /// "the next stop in the document" part ways. Following the document is what
511    /// a caret means — and on every row that *is* in order the two agree anyway,
512    /// so nothing else has to change.
513    stops: Vec<usize>,
514    /// The caret's second home at the end of every hidden inline mark: the
515    /// offset where the mark's content ends, one byte before its closing
516    /// delimiter — ascending and deduplicated, from every row's
517    /// [`VRow::mark_ends`].
518    ///
519    /// With delimiters hidden, `**bold** tail` draws one spot after the `d`
520    /// and the source has two offsets for it: the content end (inside the
521    /// mark, where typing extends the bold) and the byte past the `**` (where
522    /// typing leaves it). Only the second is a glyph's offset, so only it was
523    /// a stop, and a caret asked to rest at the first was snapped a whole
524    /// character back onto the `d` — a drag over `bold` came back one letter
525    /// short. The delete and backspace paths already settle the caret on the
526    /// content end as its natural home there
527    /// ([`crate::Doc::settle_inside_close_delims`]); this makes it one the
528    /// caret can be placed at and step onto too.
529    ///
530    /// Kept apart from [`stops`](Self::stops) rather than merged in, because
531    /// the two lists answer different questions. A stop with no glyph is
532    /// invisible to a walk that pairs stops with characters — a system text
533    /// input counting `position(from:offset:)` steps against the text it was
534    /// shown would drift a character at every mark — and to word motion, which
535    /// classifies a stop by the source byte under it (a `*`). So
536    /// [`stop_after`](Self::stop_after) and its kin walk the glyph stops alone,
537    /// and only the places a caret *rests* — snapping, resting checks, and
538    /// Left/Right — read both.
539    mark_ends: Vec<usize>,
540    /// Every table in the document, in order, described structurally rather than
541    /// drawn — see [`TableInfo`] for why both exist.
542    pub tables: Vec<TableInfo>,
543    /// Every fenced/indented code block, in order, as the range of [`rows`] it
544    /// occupies — a frontend draws one bordered, tinted box around each and
545    /// scrolls it horizontally rather than wrapping. Derived from the per-row
546    /// [`VRow::code`] flag once the rows are final (so it survives incremental
547    /// row reuse), the same way [`collect_stops`] derives the stop table.
548    ///
549    /// [`rows`]: VisualMap::rows
550    pub code_blocks: Vec<CodeBlockInfo>,
551    /// Every block-level image in the document, in order — one per placeholder
552    /// row a frontend replaces with a real picture. Derived from the per-row
553    /// [`VRow::media`] mark once the rows are final (so it survives incremental
554    /// row reuse), the same way [`code_blocks`](VisualMap::code_blocks) is
555    /// derived from [`VRow::code`].
556    pub media: Vec<MediaInfo>,
557    /// Every **leaf** directive in the document, in order — one per placeholder
558    /// row a frontend may replace with whatever the host app's vocabulary makes
559    /// of it. Derived from the per-row [`VRow::leaf_directive`] mark once the
560    /// rows are final, exactly as [`media`](VisualMap::media) is.
561    pub directives: Vec<DirectiveInfo>,
562    /// Every formula standing as a picture in this map, in row order — each
563    /// inline atom and each display block's placeholder. A frontend that
564    /// paints pictures typesets each one's TeX and draws it over the glyph or
565    /// the rows named. Derived from the per-row [`VRow::math`] marks once the
566    /// rows are final, exactly as [`media`](VisualMap::media) is.
567    ///
568    /// A formula on the revealed line is not here: there it is its own TeX,
569    /// drawn as code, and nothing stands in for it.
570    pub math: Vec<MathInfo>,
571    /// Every named font family this map's glyphs are set in, by the
572    /// [`FaceId`] they carry — the side table that lets [`Style`] stay `Copy`
573    /// while a family name stays a `String`.
574    ///
575    /// Not derived from the rows the way [`code_blocks`](Self::code_blocks) is,
576    /// because the name is not on the rows: it is interned as the walker meets
577    /// the attribute. So each of the three build paths assembles it from what
578    /// it actually walked — a fresh build from its own walk, a cached build
579    /// from each block's walk or the names its cache entry stored, a splice
580    /// from the previous map's table plus the one block it re-rendered. A
581    /// [`FaceId`] is derived from the name rather than being an index, which is
582    /// what makes those three agree glyph for glyph; see the type's note.
583    faces: FaceTable,
584    /// The visible text tabulated over the stops — see [`Spelling`]. Derived
585    /// on the first lookup that asks for it rather than by the build paths,
586    /// since a map that is only ever drawn never needs it, and a splice
587    /// would otherwise have to patch it the way it patches the stops.
588    spelling: OnceLock<Spelling>,
589}
590
591/// The visible text ([`VisualMap::visible_text`]) as a table over the stops:
592/// for stop `i`, the character the text spells it with — `None` for the
593/// `'\n'` of a stop that draws no glyph — and the UTF-16 length of the text
594/// before it. A UTF-16 index and a stop then find each other by binary
595/// search, where they used to find each other by walking every character of
596/// the document from the top: a frontend converts an `NSRange` end per
597/// selection change and per misspelled word, and each conversion was a whole
598/// document's work.
599///
600/// Built once per map and never maintained. The stops are private and fixed
601/// for the map's life; the rows only lend the character each stop draws, and
602/// a frontend that reshapes the rows after the build (the terminal inserts
603/// blank filler rows) neither changes those characters nor asks this.
604#[derive(Clone, Default)]
605struct Spelling {
606    /// Parallel to [`VisualMap::stops`].
607    chars: Vec<Option<char>>,
608    /// One longer than `chars`: `utf16[i]` is the UTF-16 length of the text
609    /// before stop `i`, and the last entry the length of the whole text.
610    utf16: Vec<usize>,
611}
612
613impl VisualMap {
614    pub fn num_rows(&self) -> usize {
615        self.rows.len()
616    }
617
618    /// The family name a glyph's [`FaceRef::Named`] stands for, or `None` for
619    /// an id from another map — which a frontend draws in the theme's body
620    /// face, as it draws a family it cannot resolve.
621    pub fn face_name(&self, id: FaceId) -> Option<&str> {
622        self.faces.name(id)
623    }
624
625    /// Every named family this map draws — how a frontend warms a font cache
626    /// before it lays a frame out. See [`faces`](Self::faces).
627    ///
628    /// [`faces`]: VisualMap::faces
629    pub fn faces(&self) -> &FaceTable {
630        &self.faces
631    }
632
633    /// The width of `row` in display columns — the rightmost column its caret
634    /// can occupy, and so what a goal column is clamped to on the way in.
635    pub fn row_width(&self, row: usize) -> usize {
636        self.rows.get(row).map_or(0, |r| r.width())
637    }
638
639    /// The screen `(row, col)` for a source offset — where to draw the caret:
640    /// the *nearest* stop at or past `off`. Snaps a hidden offset (inside a
641    /// delimiter) to the next visible glyph, and never resolves onto decoration
642    /// (a table border, a cell's padding), which is drawn but holds no caret.
643    ///
644    /// "Nearest" rather than "the first one found" because a table's wrapped
645    /// cells put rows slightly out of offset order: scanning top to bottom, the
646    /// second line of column 1 comes *after* the first line of column 2 but
647    /// holds smaller offsets. Where rows are in order the two rules agree.
648    ///
649    /// A soft wrap is the one place two rows want the same offset: the row above
650    /// ends where the row below opens, the space the wrap ate being drawn on the
651    /// row above and the offset past it being the row below's first character.
652    /// It resolves *downstream*, to the row that character is on — the row
653    /// above's last column is a phantom, a place the caret can be drawn but
654    /// never sent, and resolving upstream into it is what pinned Down at the
655    /// first wrap of a paragraph: it aimed at the row below's column 0, landed
656    /// on the offset it already had, and read that back as the row above's end.
657    ///
658    /// The walk is over the rows, not their text: a row before `off` is
659    /// dismissed by looking at where it opens and where it reaches — its first
660    /// stop and its last — rather than at every glyph between, so the cost of
661    /// a lookup mid-document is a few hundred rows' worth of two glyphs each,
662    /// and the one row that holds the answer is the only one read through.
663    /// It used to read every row through, and worse: the row's end candidate
664    /// was built eagerly, and building it measured the row's width, which
665    /// segments the row's whole text into grapheme clusters — so every row
666    /// before `off` paid a full cluster walk to learn it held nothing, and a
667    /// document of long paragraphs paid milliseconds per caret placement.
668    ///
669    /// Not a binary search, though the rows' opening stops ascend. A table's
670    /// wrapped cells put several rows before the one an offset opens on that
671    /// can still hold it, and `end_src` does not ascend across those rows at
672    /// all, so a search would need a prefix table over the rows — and
673    /// [`rows`](Self::rows) is public, reshaped by a frontend after the build
674    /// (the terminal inserts filler rows under a heading), which is exactly
675    /// what a table over it could not survive. The walk needs no table.
676    pub fn pos_of_offset(&self, off: usize) -> (usize, usize) {
677        // (src, row, the glyph — or `None` for the caret past the row's end)
678        let mut best: Option<(usize, usize, Option<usize>)> = None;
679        for (r, row) in self.rows.iter().enumerate() {
680            if row.decoration {
681                continue;
682            }
683            // A row's *first* stop never decreases from one row to the next —
684            // true even across a table's wrapped cells, since a cell's lines run
685            // downward. So once a row opens past the best found so far, no later
686            // row can beat it and the scan stays proportional to `off`.
687            let open = row
688                .glyphs
689                .iter()
690                .find(|g| g.stop)
691                .map_or(row.end_src, |g| g.src);
692            if best.is_some_and(|b| open > b.0) {
693                break;
694            }
695            // Offsets ascend *within* a row, so its last stop or its end is as
696            // far as it reaches: a row that reaches short of `off` has nothing
697            // to offer, and says so from its two ends.
698            let reach = row
699                .glyphs
700                .iter()
701                .rev()
702                .find(|g| g.stop)
703                .map_or(row.end_src, |g| g.src.max(row.end_src));
704            if reach < off {
705                continue;
706            }
707            // And so its first stop at or past `off` is the best it has.
708            let cand = row
709                .glyphs
710                .iter()
711                .enumerate()
712                .find(|(_, g)| g.stop && g.src >= off)
713                .map(|(i, g)| (g.src, r, Some(i)))
714                .or_else(|| (row.end_src >= off).then_some((row.end_src, r, None)));
715            // `<=`, so a tie goes to the later row: the only offset two rows
716            // both hold is a wrap boundary, and it belongs to the row below.
717            if let Some(c) = cand
718                && best.is_none_or(|b| c.0 <= b.0)
719            {
720                best = Some(c);
721            }
722        }
723        match best {
724            Some((_, r, Some(i))) => (r, self.rows[r].col_of_glyph(i)),
725            Some((_, r, None)) => (r, self.rows[r].width()),
726            None => {
727                let r = self.last_stop_row();
728                (r, self.row_width(r))
729            }
730        }
731    }
732
733    /// The rows a source range occupies, inclusive: `(first, last)`.
734    ///
735    /// A *different question* from [`pos_of_offset`](Self::pos_of_offset), which
736    /// is why it can't be spelled with two calls to it. That one answers "where
737    /// does the caret go", and for a caret its forward snap is right — an offset
738    /// inside a hidden delimiter has no column of its own, so the caret belongs
739    /// at the next visible glyph, wherever that turns out to be. This one asks
740    /// "which rows does this block cover", and there the snap is a trap: a
741    /// footnote whose body *ends* in a link (`[^2]: [title](url)`) has a last
742    /// byte inside the hidden destination, so `pos_of_offset(end - 1)` walked
743    /// clean off the note's row and landed on the next note's — and a peek
744    /// slicing `first..=last` out of the frame drew two notes where the reader
745    /// asked for one. Every block ending in a link, an image, or any trailing
746    /// hidden markup had the same fault; only a block ending in visible text
747    /// (which is what the tests happened to use) did not.
748    ///
749    /// `row.end_src` is no help either: it is where the *rendered* text of a row
750    /// ends, not how far into the source the block reaches, and redefining it
751    /// would move every end-of-line caret.
752    ///
753    /// So the last row is found by asking which rows *open* before the range
754    /// does, rather than by mapping its last byte: a row belongs to the range
755    /// when its first caret stop lies before `range.end`. Decoration is skipped
756    /// (a drawn gap between blocks is not part of either), and the answer is
757    /// never shorter than one row — a range whose every byte is hidden still
758    /// covers the row it started on.
759    pub fn row_range_for(&self, range: Range<usize>) -> (usize, usize) {
760        if self.rows.is_empty() {
761            return (0, 0);
762        }
763        let first = self.pos_of_offset(range.start).0;
764        let mut last = first;
765        for (r, row) in self.rows.iter().enumerate().skip(first) {
766            if row.decoration {
767                continue;
768            }
769            let open = row
770                .glyphs
771                .iter()
772                .find(|g| g.stop)
773                .map_or(row.end_src, |g| g.src);
774            if open >= range.end {
775                // A row's first stop never decreases from one row to the next —
776                // the invariant `pos_of_offset` breaks on, true even across a
777                // table's wrapped cells — so nothing below can be in range.
778                break;
779            }
780            last = r;
781        }
782        (first, last)
783    }
784
785    /// The source offset of the task checkbox drawn at `(row, col)`, or `None`
786    /// when that cell holds no box — the hit-test a frontend runs on a click
787    /// before treating it as a tick rather than a caret placement.
788    ///
789    /// Only the box's own cells answer. Clicking an item's *text* places the
790    /// caret like any other click, so the box is a target aimed at rather than
791    /// something tripped over while editing — which is also why this is a
792    /// separate question from [`offset_of_pos`](Self::offset_of_pos) instead of
793    /// a flag on the offset it returns.
794    pub fn task_box_at(&self, row: usize, col: usize) -> Option<usize> {
795        let r = self.rows.get(row)?;
796        self.task_box_at_glyph(row, r.glyph_at_col(col)?)
797    }
798
799    /// [`task_box_at`](Self::task_box_at) keyed by glyph index rather than
800    /// display column — for a frontend that shapes its own rows (the GUI) and so
801    /// resolves a click to a glyph before it ever has a column.
802    pub fn task_box_at_glyph(&self, row: usize, glyph: usize) -> Option<usize> {
803        let r = self.rows.get(row)?;
804        r.task?;
805        let g = r.glyphs.get(glyph)?;
806        (g.style.role == Role::ListMarker).then_some(g.src)
807    }
808
809    /// The source offset for a screen `(row, col)` — where a click or a
810    /// visual-space move lands the caret. Clicking decoration maps through its
811    /// `src`, which points at the text it decorates, so a click on a border or
812    /// on a cell's padding lands in that cell.
813    ///
814    /// The inverse of [`pos_of_offset`](Self::pos_of_offset), which it has to
815    /// agree with: `col` is a display column, and the one it names may be the
816    /// far cell of a wide glyph — [`VRow::glyph_at_col`] is where that lands.
817    pub fn offset_of_pos(&self, row: usize, col: usize) -> usize {
818        let Some(r) = self.rows.get(row) else {
819            // A click or drag below the last row — a short document with empty
820            // space under it, dragged into to extend a selection. Land on the
821            // document's last caret stop (its end), not offset 0: jumping the
822            // caret to the top is the wrong direction, and 0 isn't even a stop
823            // when the document opens on hidden frontmatter or a `# ` marker, so
824            // returning it would leave the caret where it draws in one place and
825            // types in another (`move_to` would then clamp it onto the unhomeable
826            // frontmatter floor). `None` only for a document with no stops at all
827            // (empty), where the caret has nowhere to be but 0.
828            return self.stops.last().copied().unwrap_or(0);
829        };
830        match r.glyph_at_col(col).and_then(|i| r.glyphs.get(i)) {
831            // A glyph that holds no caret is clickable, but where it points
832            // isn't always somewhere the caret can be: the blank gap between two
833            // paragraphs stands at an offset that belongs to neither of them,
834            // and the tail of a grapheme cluster stands inside a character.
835            // Land on the nearest real stop instead of handing back an offset
836            // that looks like the gap but types into the paragraph above.
837            Some(g) if !g.stop => self.nearest_stop(g.src),
838            Some(g) => g.src,
839            // A row's end is a stop by construction — unless the row is
840            // decoration, which contributes none.
841            None if r.decoration => self.nearest_stop(r.end_src),
842            None => r.end_src,
843        }
844    }
845
846    /// Which of a block media's two caret homes `off` is, or `None` for every
847    /// other offset in the document.
848    ///
849    /// [`block_media`](Builder::block_media) gives a block-level image, video, or
850    /// audio exactly two stops — one in front of it and one just past it — and
851    /// nothing inside the markup. Both are ordinary offsets to everything else in
852    /// core, but they are the two places where inserting text would *dissolve the
853    /// picture*: `![](p.png)` with anything typed against it is no longer a block
854    /// image but a paragraph with an inline one, and the frontend that was
855    /// painting a photo there paints a text run instead. A caller that is about to
856    /// insert asks this so it can open a paragraph first — see
857    /// [`Doc::insert`](crate::Doc::insert).
858    ///
859    /// An *inline* image reports `None`: it has no placeholder row and no stops of
860    /// its own, and typing beside one is ordinary editing.
861    ///
862    /// Answers with the media's own source span as well, since a caller that has
863    /// to keep the picture whole usually has to address it — [`Doc::backspace`]
864    /// takes the picture out in one piece rather than nibbling a byte off its
865    /// markup, which is the same dissolution from the other side.
866    ///
867    /// [`Doc::backspace`]: crate::Doc::backspace
868    pub fn block_media_stop(&self, off: usize) -> Option<(MediaStop, Range<usize>)> {
869        for m in &self.media {
870            let Some(row) = self.rows.get(m.rows_span.start) else {
871                continue;
872            };
873            // Every glyph of the `🖼 alt` label maps to the media's start offset;
874            // the row's end is past its markup. Read the start off the label
875            // rather than the first glyph, which on a quoted or listed picture is
876            // the block prefix and points at the gutter.
877            let Some(start) = row
878                .glyphs
879                .iter()
880                .find(|g| g.style.role == Role::Image)
881                .map(|g| g.src)
882            else {
883                continue;
884            };
885            if off == start {
886                return Some((MediaStop::Before, start..row.end_src));
887            }
888            if off == row.end_src {
889                return Some((MediaStop::After, start..row.end_src));
890            }
891        }
892        None
893    }
894
895    /// Whether `off` is a table's trailing caret stop — the one home past a
896    /// table's last cell, at the block's own end ([`TableInfo::end_src`]).
897    ///
898    /// The table's peer of [`block_media_stop`](Self::block_media_stop)'s
899    /// `After`: text inserted at that offset joins the table's last source
900    /// line, and a line glued under a table is a row of it (`| 1 | 2 |x`), so
901    /// a caller about to insert there opens a paragraph first — see
902    /// [`Doc::insert`](crate::Doc::insert). Nothing else about the offset is
903    /// special: it is where Down from the last row lands and where a click in
904    /// the blank space under a trailing table lands.
905    pub fn table_end_stop(&self, off: usize) -> bool {
906        self.tables.iter().any(|t| t.end_src == off)
907    }
908
909    /// Snap `off` to the nearest caret stop — the funnel a frontend that
910    /// hit-tests pixels straight to a source offset must run its result through.
911    /// A click or drag can land in the blank gap a paragraph break is drawn with,
912    /// or inside a hidden delimiter; both are offsets the caret can't rest at, so
913    /// resting there would draw the caret in one place and type in another. This
914    /// settles it on a real caret home instead. Idempotent on an offset that is
915    /// already a stop — the `(row, col)` click path already snaps this way inside
916    /// [`offset_of_pos`](Self::offset_of_pos), and this gives the pixel path the
917    /// same guarantee. Returns `off` unchanged only for an empty document (no
918    /// stops at all).
919    pub fn snap_to_stop(&self, off: usize) -> usize {
920        self.nearest_stop(off)
921    }
922
923    /// The caret stop nearest `off`, preferring the one before it when `off`
924    /// falls exactly between two. Returns `off` unchanged if there are no stops
925    /// at all (an empty document). A mark's content end counts: it is a place
926    /// the caret rests, and the one a drag ending on a marked word means.
927    fn nearest_stop(&self, off: usize) -> usize {
928        let before = Self::last_at_or_before(&self.stops, off)
929            .max(Self::last_at_or_before(&self.mark_ends, off));
930        let after = match (
931            Self::first_at_or_after(&self.stops, off),
932            Self::first_at_or_after(&self.mark_ends, off),
933        ) {
934            (Some(a), Some(b)) => Some(a.min(b)),
935            (a, b) => a.or(b),
936        };
937        match (before, after) {
938            (Some(b), Some(a)) if off - b <= a - off => b,
939            (_, Some(a)) => a,
940            (Some(b), None) => b,
941            (None, None) => off,
942        }
943    }
944
945    /// The glyph stop nearest `off` — [`nearest_stop`](Self::nearest_stop)
946    /// for a walk that pairs stops with characters, which a mark's content
947    /// end has none of. A caret resting on one resolves to the glyph stop
948    /// drawn at the same spot, the one just past the hidden delimiter, so the
949    /// text a system input is shown from there and the steps it counts agree.
950    pub fn snap_to_glyph_stop(&self, off: usize) -> usize {
951        if self.mark_ends.binary_search(&off).is_ok()
952            && let Some(next) = Self::first_at_or_after(&self.stops, off)
953        {
954            return next;
955        }
956        let before = Self::last_at_or_before(&self.stops, off);
957        let after = Self::first_at_or_after(&self.stops, off);
958        match (before, after) {
959            (Some(b), Some(a)) if off - b <= a - off => b,
960            (_, Some(a)) => a,
961            (Some(b), None) => b,
962            (None, None) => off,
963        }
964    }
965
966    /// The last of `sorted` at or before `off`, if any.
967    fn last_at_or_before(sorted: &[usize], off: usize) -> Option<usize> {
968        let i = sorted.partition_point(|&s| s <= off);
969        i.checked_sub(1).map(|i| sorted[i])
970    }
971
972    /// The first of `sorted` at or after `off`, if any.
973    fn first_at_or_after(sorted: &[usize], off: usize) -> Option<usize> {
974        let i = sorted.partition_point(|&s| s < off);
975        sorted.get(i).copied()
976    }
977
978    /// The next place the caret rests past `off` — the next glyph stop or the
979    /// next mark's content end, whichever comes first. What Right walks:
980    /// leaving `**bold**` from the `d` is two presses, one onto the end of the
981    /// bold (still bold, the toolbar lit) and one past its delimiter, at the
982    /// same spot on screen. [`stop_after`](Self::stop_after) is the walk that
983    /// skips the first, for every caller that pairs stops with characters.
984    pub fn caret_stop_after(&self, off: usize) -> Option<usize> {
985        match (
986            self.stop_after(off),
987            Self::first_at_or_after(&self.mark_ends, off + 1),
988        ) {
989            (Some(a), Some(b)) => Some(a.min(b)),
990            (a, b) => a.or(b),
991        }
992    }
993
994    /// The previous place the caret rests before `off` — the mirror of
995    /// [`caret_stop_after`](Self::caret_stop_after), what Left walks.
996    pub fn caret_stop_before(&self, off: usize) -> Option<usize> {
997        self.stop_before(off).max(
998            off.checked_sub(1)
999                .and_then(|o| Self::last_at_or_before(&self.mark_ends, o)),
1000        )
1001    }
1002
1003    /// Whether the caret can occupy `row` at all: decoration rows (a table's
1004    /// border rules) are stepped over by vertical motion.
1005    pub fn row_is_navigable(&self, row: usize) -> bool {
1006        self.rows.get(row).is_some_and(|r| !r.decoration)
1007    }
1008
1009    /// The first offset the caret can rest at on `row` — its first stop, or the
1010    /// row's own end when it holds no text (an empty paragraph). `None` for a
1011    /// decoration row, which holds no caret at all.
1012    ///
1013    /// Not `offset_of_pos(row, 0)`: column 0 of a quoted or listed row is the
1014    /// gutter, and a gutter's `src` points at the *block* it opens, so the stop
1015    /// nearest it is the one on the block's first row rather than on this one.
1016    /// Which is right for a click — the gutter decorates the whole block — and
1017    /// wrong for Home, whose whole question is where *this* row starts.
1018    pub fn row_start(&self, row: usize) -> Option<usize> {
1019        let r = self.rows.get(row).filter(|r| !r.decoration)?;
1020        Some(
1021            r.glyphs
1022                .iter()
1023                .find(|g| g.stop)
1024                .map_or(r.end_src, |g| g.src),
1025        )
1026    }
1027
1028    /// The last row the caret can rest on — the fallback when an offset is past
1029    /// everything rendered (a table's bottom border must not swallow the caret).
1030    fn last_stop_row(&self) -> usize {
1031        (0..self.rows.len())
1032            .rev()
1033            .find(|&r| self.row_is_navigable(r))
1034            .unwrap_or(0)
1035    }
1036
1037    /// The nearest row above `row` the caret can occupy, skipping decoration.
1038    pub fn navigable_above(&self, row: usize) -> Option<usize> {
1039        (0..row.min(self.rows.len()))
1040            .rev()
1041            .find(|&r| self.row_is_navigable(r))
1042    }
1043
1044    /// The nearest row below `row` the caret can occupy, skipping decoration.
1045    pub fn navigable_below(&self, row: usize) -> Option<usize> {
1046        ((row + 1)..self.rows.len()).find(|&r| self.row_is_navigable(r))
1047    }
1048
1049    /// The caret stop just before `off` — one press of Left. `None` at the
1050    /// first stop in the document.
1051    ///
1052    /// Runs of decoration (a table border, a cell's alignment padding) are
1053    /// stepped over in a single press: they hold no stop, so they aren't in the
1054    /// table to land on.
1055    pub fn stop_before(&self, off: usize) -> Option<usize> {
1056        let i = self.stops.partition_point(|&s| s < off);
1057        i.checked_sub(1).map(|i| self.stops[i])
1058    }
1059
1060    /// The caret stop just after `off` — one press of Right. `None` at the last
1061    /// stop in the document.
1062    pub fn stop_after(&self, off: usize) -> Option<usize> {
1063        let i = self.stops.partition_point(|&s| s <= off);
1064        self.stops.get(i).copied()
1065    }
1066
1067    /// The first caret stop at or past `off` — where the caret at a hidden
1068    /// offset is *drawn*, and so where a rightward walk over the rendered text
1069    /// starts from.
1070    pub fn stop_at_or_after(&self, off: usize) -> Option<usize> {
1071        let i = self.stops.partition_point(|&s| s < off);
1072        self.stops.get(i).copied()
1073    }
1074
1075    /// The last caret stop at or before `off` — where a leftward walk starts
1076    /// from. Snapping the way the walk is headed, rather than always forward,
1077    /// is what keeps a leftward motion from ever moving the caret right.
1078    pub fn stop_at_or_before(&self, off: usize) -> Option<usize> {
1079        let i = self.stops.partition_point(|&s| s <= off);
1080        i.checked_sub(1).map(|i| self.stops[i])
1081    }
1082
1083    /// Whether the caret may rest at `off` — the invariant every motion in this
1084    /// view has to leave standing. A glyph stop, a row's end, or a hidden
1085    /// mark's content end ([`mark_ends`](Self::mark_ends)).
1086    pub fn is_stop(&self, off: usize) -> bool {
1087        self.stops.binary_search(&off).is_ok() || self.mark_ends.binary_search(&off).is_ok()
1088    }
1089
1090    /// The visible text a caret crosses walking rightward from `from` up to
1091    /// (but not including) `to` — `UITextInput.text(in:)`'s `[from, to)` in
1092    /// *this* view. A hidden inline-mark delimiter (`**`, `` ` ``, `_`, an
1093    /// escape backslash) never got a glyph in the first place — see
1094    /// [`push_text`]/[`synth`] — so it contributes nothing; what's left is
1095    /// what's drawn on screen for that span, one character per caret stop.
1096    ///
1097    /// **Exactly one character per stop** is the contract, and it is the
1098    /// system text input's, not a nicety: `UITextInput`'s tokenizer reads a
1099    /// window of this text around a tap, indexes into it by the integer
1100    /// `offset(from:to:)` reports (`distance_offset` in `leaf-ffi`, a count of
1101    /// [`stop_after`](Self::stop_after) hops), finds a word boundary at some
1102    /// character index, and hands the delta back through
1103    /// `position(from:offset:)`, which hops stops again. If the text ever
1104    /// spends a character on something that is not a stop, or a stop on
1105    /// nothing, every index past that point is off by one and the word the
1106    /// reader double-tapped comes back shifted — into the header row of a
1107    /// table, or one letter short. So a stop that draws a glyph is spelled
1108    /// as that glyph, and a stop that draws none is spelled `'\n'`:
1109    ///
1110    /// - a row's own end stop ([`VRow::end_src`]) — the caret home past a
1111    ///   paragraph's, heading's, list item's, or code line's last glyph. This
1112    ///   is also what keeps two blocks' words apart: without it the last word
1113    ///   of one paragraph and the first of the next read as one run of
1114    ///   letters (`"…edb\n\nhello\n"` came back as `"edbhello"`), and the
1115    ///   tokenizer selected across the boundary. A list item's end is a
1116    ///   row end like any other, though no blank gap row follows it.
1117    /// - a table cell's end, which [`push_table_row`] draws as the gutter
1118    ///   space before the next `│` so the caret has somewhere to stand past
1119    ///   the cell's last character. To a reader of *this* text a cell ends a
1120    ///   line: spelled as a space, a touch surface that lands a tap at a
1121    ///   word's end past the space that follows it stepped into the next
1122    ///   cell — or the next row, from the last column.
1123    ///
1124    /// A hidden mark's content end ([`mark_ends`](Self::mark_ends)) is a place
1125    /// the caret rests but not a stop the walks above count, so it has no
1126    /// character here either; `from` is snapped to the glyph stop drawn at
1127    /// the same spot first, exactly as [`snap_to_glyph_stop`] does for those
1128    /// walks. `to` is left as given, so a stop landing exactly on it is still
1129    /// excluded — the same half-open range `distance_offset`'s loop counts.
1130    ///
1131    /// [`push_table_row`]: Builder::push_table_row
1132    /// [`snap_to_glyph_stop`]: Self::snap_to_glyph_stop
1133    pub fn visible_text(&self, from: usize, to: usize) -> String {
1134        self.visible_items(from, to)
1135            .into_iter()
1136            .map(|(_, ch)| ch.unwrap_or('\n'))
1137            .collect()
1138    }
1139
1140    /// The UTF-16 length of `visible_text(from, to)` — what an `NSRange`
1141    /// location into that text is, without building the string.
1142    ///
1143    /// AppKit's `NSTextInputClient` and `NSAccessibility` speak in UTF-16
1144    /// units of *the text as the system sees it*, which for leaf is the visible
1145    /// text — delimiters hidden. A frontend reporting its selection to the
1146    /// system converts each end with this and gets back an index into the
1147    /// string `visible_text(0, end)` returns, which is exactly what the system
1148    /// will index into.
1149    pub fn visible_utf16_len(&self, from: usize, to: usize) -> usize {
1150        let (lo, hi) = self.visible_span(from, to);
1151        let utf16 = &self.spelling().utf16;
1152        utf16[hi] - utf16[lo]
1153    }
1154
1155    /// The inverse of `visible_utf16_len(0, ·)`: the source offset of the
1156    /// visible character a UTF-16 index into `visible_text(0, to)` lands on.
1157    ///
1158    /// An index inside a surrogate pair resolves to the character that owns
1159    /// it; one at or past the end of the text returns `None`, so a caller can
1160    /// substitute the document's end stop. The `\n` a row's or a cell's end
1161    /// is spelled with resolves to that end stop — a caret home, so a caller
1162    /// placing a caret there needs no snap.
1163    pub fn offset_at_visible_utf16(&self, to: usize, index: usize) -> Option<usize> {
1164        let (lo, hi) = self.visible_span(0, to);
1165        let utf16 = &self.spelling().utf16;
1166        // The stop whose text ends past the index is the one it lands on; a
1167        // stop whose text ends at or before it lies wholly before it.
1168        let target = utf16[lo] + index;
1169        let i = lo + utf16[lo + 1..=hi].partition_point(|&end| end <= target);
1170        (i < hi).then(|| self.stops[i])
1171    }
1172
1173    /// The items `visible_text` spells, in order — one per caret stop in
1174    /// `[from, to)`, keyed by the stop's source offset: the glyph it draws
1175    /// (`Some`), or `None` for a stop with no character of its own, which the
1176    /// text spells `'\n'`. See [`visible_text`](Self::visible_text) for which
1177    /// stops those are and why.
1178    fn visible_items(&self, from: usize, to: usize) -> Vec<(usize, Option<char>)> {
1179        let (lo, hi) = self.visible_span(from, to);
1180        self.stops[lo..hi]
1181            .iter()
1182            .copied()
1183            .zip(self.spelling().chars[lo..hi].iter().copied())
1184            .collect()
1185    }
1186
1187    /// The stops `visible_text(from, to)` spells, as a range into the stop
1188    /// table: from the glyph stop `from` snaps to, up to but excluding the
1189    /// first stop at or past `to`.
1190    fn visible_span(&self, from: usize, to: usize) -> (usize, usize) {
1191        let from = self.snap_to_glyph_stop(from);
1192        let lo = self.stops.partition_point(|&s| s < from);
1193        // The document's last stop is the end of the text, not a character in
1194        // it: `distance_offset` has no hop past it to pair one with.
1195        let last = self.stops.len().saturating_sub(1);
1196        let hi = self.stops.partition_point(|&s| s < to).min(last).max(lo);
1197        (lo, hi)
1198    }
1199
1200    /// The [`Spelling`] of this map's stops, tabulated on first use.
1201    fn spelling(&self) -> &Spelling {
1202        self.spelling.get_or_init(|| {
1203            // The glyph each stop draws — the first at its offset in row
1204            // order, since a media row's label glyphs all share the media's
1205            // offset and a wrapped line's end is the next line's first glyph.
1206            // Row order only follows source order outside a table's wrapped
1207            // cells (see `pos_of_offset`), which is why each glyph looks its
1208            // stop up rather than the two being walked side by side.
1209            //
1210            // Within a row offsets ascend, so a cursor into the stop table
1211            // walks forward with the row's glyphs and the whole pass is a
1212            // read of the glyphs plus one search per row — a keystroke's
1213            // first conversion pays for this, so it is kept to that. The
1214            // search is repeated only if a row's offsets step back, which
1215            // none does; the walk is correct either way.
1216            let stops = &self.stops;
1217            let mut chars: Vec<Option<char>> = vec![None; stops.len()];
1218            for row in self.rows.iter().filter(|r| !r.decoration) {
1219                let mut i = 0;
1220                let mut prev = usize::MAX;
1221                for g in row.glyphs.iter().filter(|g| g.stop) {
1222                    if prev == usize::MAX || g.src < prev {
1223                        i = stops.partition_point(|&s| s < g.src);
1224                    } else {
1225                        while i < stops.len() && stops[i] < g.src {
1226                            i += 1;
1227                        }
1228                    }
1229                    prev = g.src;
1230                    if i < stops.len() && stops[i] == g.src && chars[i].is_none() {
1231                        chars[i] = Some(g.ch);
1232                    }
1233                }
1234            }
1235            // A cell's end stop has a glyph (the gutter space) but is spelled
1236            // as a line end; the structural grid is where the cells' offsets
1237            // live.
1238            for cell in self
1239                .tables
1240                .iter()
1241                .flat_map(|t| t.grid.iter())
1242                .flat_map(|r| r.cells.iter())
1243            {
1244                if let Ok(i) = self.stops.binary_search(&cell.end) {
1245                    chars[i] = None;
1246                }
1247            }
1248            let mut utf16 = Vec::with_capacity(chars.len() + 1);
1249            utf16.push(0);
1250            for ch in &chars {
1251                let before = *utf16.last().unwrap_or(&0);
1252                utf16.push(before + ch.map_or(1, char::len_utf16));
1253            }
1254            Spelling { chars, utf16 }
1255        })
1256    }
1257}
1258
1259/// Collect the caret stops of a laid-out grid: every stop glyph's offset plus
1260/// every row's end, ascending and deduplicated. Duplicates are the norm rather
1261/// than the exception — a wrapped line's end is the same offset as the next
1262/// line's first glyph — and collapsing them is what makes one press of Left or
1263/// Right cross exactly one stop.
1264fn collect_stops(rows: &[VRow]) -> Vec<usize> {
1265    let mut stops: Vec<usize> = rows
1266        .iter()
1267        .filter(|r| !r.decoration)
1268        .flat_map(|r| {
1269            r.glyphs
1270                .iter()
1271                .filter(|g| g.stop)
1272                .map(|g| g.src)
1273                .chain(std::iter::once(r.end_src))
1274        })
1275        .collect();
1276    stops.sort_unstable();
1277    stops.dedup();
1278    stops
1279}
1280
1281/// Collect every row's [`VRow::mark_ends`] into one ascending, deduplicated
1282/// table — the peer of [`collect_stops`] for the caret's second home at the
1283/// end of a hidden mark. A mark that closes at a row's end coincides with the
1284/// row's own end stop; that offset is in both tables, and harmlessly so.
1285fn collect_mark_ends(rows: &[VRow]) -> Vec<usize> {
1286    let mut ends: Vec<usize> = rows
1287        .iter()
1288        .filter(|r| !r.decoration)
1289        .flat_map(|r| r.mark_ends.iter().copied())
1290        .collect();
1291    ends.sort_unstable();
1292    ends.dedup();
1293    ends
1294}
1295
1296/// Group the rows tagged [`VRow::code`] into one [`CodeBlockInfo`] per maximal
1297/// run — the block-level view a frontend needs to box and scroll each code
1298/// block. Two code blocks are always parted by the blank separator row a block
1299/// boundary is spelled with (never itself a code row), so a contiguous run is
1300/// exactly one block. Derived from the final rows rather than tracked through
1301/// the builder so it comes out right no matter how [`build_cached`] and
1302/// [`build_spliced`] shuffle rows around.
1303fn code_block_spans(rows: &[VRow]) -> Vec<CodeBlockInfo> {
1304    let mut blocks = Vec::new();
1305    let mut start: Option<usize> = None;
1306    for (i, row) in rows.iter().enumerate() {
1307        match (row.code, start) {
1308            (true, None) => start = Some(i),
1309            (false, Some(s)) => {
1310                blocks.push(CodeBlockInfo {
1311                    rows_span: s..i,
1312                    lang: rows[s].code_lang.clone(),
1313                });
1314                start = None;
1315            }
1316            _ => {}
1317        }
1318    }
1319    if let Some(s) = start {
1320        blocks.push(CodeBlockInfo {
1321            rows_span: s..rows.len(),
1322            lang: rows[s].code_lang.clone(),
1323        });
1324    }
1325    blocks
1326}
1327
1328/// The value of `node`'s `key` attribute, if it carries one *with* a value. A
1329/// bare attribute (`controls`, `muted`) has a `None` value and so reads as
1330/// absent here — a caller wanting presence-not-value tests the list directly.
1331/// Shared by the media element and `<source>` readers.
1332fn attr_of(node: &FlatNode, key: &str) -> Option<String> {
1333    node.attrs
1334        .iter()
1335        .find(|(k, _)| k == key)
1336        .and_then(|(_, v)| v.clone())
1337}
1338
1339/// Collect one [`MediaInfo`] per row carrying a [`VRow::media`] mark — the
1340/// block-level view a frontend needs to replace each placeholder row with a real
1341/// picture. The mark rides the block's *first* row and names how many rows the
1342/// media reserves ([`MediaMark::rows`]); the rows below it are blank
1343/// [`decoration`](VRow::decoration) fillers that hold the vertical space and no
1344/// caret. So the span runs from the marked row across those fillers. Derived from
1345/// the final rows rather than tracked through the builder so it survives however
1346/// [`build_cached`] and [`build_spliced`] shuffle rows around.
1347fn media_spans(rows: &[VRow]) -> Vec<MediaInfo> {
1348    rows.iter()
1349        .enumerate()
1350        .filter_map(|(i, row)| {
1351            row.media.as_ref().map(|m| MediaInfo {
1352                rows_span: i..i + m.rows.max(1),
1353                kind: m.kind,
1354                destination: m.destination.clone(),
1355                sources: m.sources.clone(),
1356                alt: m.alt.clone(),
1357                poster: m.poster.clone(),
1358            })
1359        })
1360        .collect()
1361}
1362
1363/// Re-label the drawn block boundaries either side of a block-level media
1364/// placeholder, so the pair a frontend spaces by names the picture.
1365///
1366/// [`BlockClass::from_node_kind`] classifies the node the walk is standing on,
1367/// and a block image is never a node of its own: [`Builder::media_only`] promotes
1368/// its *wrapper* — a `paragraph`, or the `container` a `<video>`/`<audio>`
1369/// arrives as — so the gap above a picture reported [`BlockClass::Paragraph`] and
1370/// the gap above a movie reported [`BlockClass::Directive`], the class a frontend
1371/// paints a tinted panel for. [`BlockClass::Media`] was unreachable in
1372/// consequence: the vocabulary named a kind no frontend could ever be told about.
1373///
1374/// Done as a pass over the finished rows rather than inside the walk because
1375/// only the rows know. The incremental top-level walk carries no node arena at
1376/// all (`nodes: &[]`) and can classify by kind alone, so teaching the wrapper
1377/// promotion to the whole-arena walk would label the full and incremental builds
1378/// differently — the exact drift that walk's own comment forbids. Both builds
1379/// emit the same [`VRow::media`] marks, so both reach the same answer here. The
1380/// [`media_spans`] / [`code_block_spans`] pattern.
1381///
1382/// One gap can be spelled with several rows — [`Builder::emit_separators_before`]
1383/// draws the row that closes the block above and the row that opens the block
1384/// below, with any extra blank source lines navigable between them — and gives
1385/// every one of them the same [`Boundary`]. So the walk crosses those navigable
1386/// blanks and relabels the whole run, stopping at the first row that is neither.
1387fn label_media_boundaries(rows: &mut [VRow]) {
1388    // A display formula's placeholder is promoted from its paragraph exactly
1389    // as a picture is, and its gaps are relabelled the same way, as `Math`.
1390    let spans: Vec<(Range<usize>, BlockClass)> = rows
1391        .iter()
1392        .enumerate()
1393        .filter_map(|(i, row)| {
1394            if let Some(m) = &row.media {
1395                Some((i..i + m.rows.max(1), BlockClass::Media))
1396            } else {
1397                row.math
1398                    .iter()
1399                    .find(|m| m.glyph.is_none())
1400                    .map(|m| (i..i + m.rows.max(1), BlockClass::Math))
1401            }
1402        })
1403        .collect();
1404    // A row inside one gap: a drawn boundary to relabel, or one of the navigable
1405    // blank lines sitting between two drawn ones. Anything else ends the run.
1406    fn in_gap(row: &VRow) -> bool {
1407        row.boundary.is_some() || (!row.decoration && row.glyphs.is_empty())
1408    }
1409    for (span, class) in spans {
1410        for i in (0..span.start).rev() {
1411            if !in_gap(&rows[i]) {
1412                break;
1413            }
1414            if let Some(b) = rows[i].boundary.as_mut() {
1415                b.below = class;
1416            }
1417        }
1418        for row in rows.iter_mut().skip(span.end) {
1419            if !in_gap(row) {
1420                break;
1421            }
1422            if let Some(b) = row.boundary.as_mut() {
1423                b.above = class;
1424            }
1425        }
1426    }
1427}
1428
1429/// Collect one [`DirectiveInfo`] per row carrying a [`VRow::leaf_directive`]
1430/// mark — the block-level view a frontend needs to replace each placeholder row
1431/// with whatever the directive means to it. The peer of [`media_spans`], derived
1432/// from the final rows for the same reason: it survives however [`build_cached`]
1433/// and [`build_spliced`] shuffle rows around.
1434fn directive_spans(rows: &[VRow]) -> Vec<DirectiveInfo> {
1435    rows.iter()
1436        .enumerate()
1437        .filter_map(|(i, row)| {
1438            row.leaf_directive.as_ref().map(|m| DirectiveInfo {
1439                rows_span: i..i + m.rows.max(1),
1440                name: m.name.clone(),
1441                attrs: m.attrs.clone(),
1442                label: m.label.clone(),
1443            })
1444        })
1445        .collect()
1446}
1447
1448/// Collect one [`MathInfo`] per [`VRow::math`] mark — the peer of
1449/// [`media_spans`] and [`directive_spans`], derived from the final rows for the
1450/// same reason. A block mark spans its fillers; an atom spans its own row.
1451fn math_spans(rows: &[VRow]) -> Vec<MathInfo> {
1452    rows.iter()
1453        .enumerate()
1454        .flat_map(|(i, row)| {
1455            row.math.iter().map(move |m| {
1456                let src = match m.glyph {
1457                    Some(g) => row.glyphs.get(g).map_or(row.end_src, |g| g.src),
1458                    None => row
1459                        .glyphs
1460                        .iter()
1461                        .find(|g| g.style.role == Role::Math)
1462                        .map_or(row.end_src, |g| g.src),
1463                };
1464                MathInfo {
1465                    rows_span: i..i + m.rows.max(1),
1466                    row: i,
1467                    glyph: m.glyph,
1468                    tex: m.tex.clone(),
1469                    display: m.display,
1470                    src,
1471                }
1472            })
1473        })
1474        .collect()
1475}
1476
1477/// The source range of a fenced code block's info string — everything on the
1478/// opening line past the fence (`` ```rust `` → the `rust`). `block_start` is the
1479/// code block node's `span.start`. `None` for an indented code block, which
1480/// opens with no fence to carry one. The range is empty for a fence written
1481/// bare (`` ``` `` alone), which is exactly where a language would be inserted.
1482///
1483/// A block inside a quote or a list item starts at its line's start, with the
1484/// container's marker in front of the fence — `> ```rust`, `- ```rust` — so
1485/// the marker is skipped first, and the fence's three-space indent allowance
1486/// is measured from where the container's content begins: past the marker on
1487/// the fence's own line, or, on a continuation line, from the content column
1488/// of the list item above. That is what keeps an *indented* code block inside
1489/// a list item answering `None`.
1490///
1491/// Shared by the WYSIWYG builder (to label the box) and [`crate::Doc`] (to edit
1492/// the label through a prompt), so the two agree on where the language lives.
1493pub fn code_info_span(source: &str, block_start: usize) -> Option<Range<usize>> {
1494    let rest = source.get(block_start..)?;
1495    let line_len = rest.find('\n').unwrap_or(rest.len());
1496    let line = &rest[..line_len];
1497    let (depth, quoted) = strip_quote_markers(line);
1498    let mut content = quoted;
1499    let mut listed = false;
1500    while let Some(n) = list_marker_len(&line[content..], 3) {
1501        content += n;
1502        listed = true;
1503    }
1504    let lead = leading_spaces(&line[content..]);
1505    // No marker of its own: a continuation line, whose leading spaces include
1506    // the enclosing item's indent. Only when the block owns its line — a span
1507    // that starts mid-line has had its container prefix measured off already.
1508    let at_line_start = block_start == 0 || source.as_bytes()[block_start - 1] == b'\n';
1509    let base = if listed || !at_line_start {
1510        0
1511    } else {
1512        item_content_column(&source[..block_start], depth, lead)
1513    };
1514    // A fence may be indented up to three spaces; past that it opens with a run
1515    // of the same fence character.
1516    if lead - base > 3 {
1517        return None;
1518    }
1519    let at = content + lead;
1520    let fence = line[at..].chars().next()?;
1521    if fence != '`' && fence != '~' {
1522        return None; // an indented block, not a fenced one
1523    }
1524    let fence_len = line[at..].chars().take_while(|&c| c == fence).count();
1525    let info_start = block_start + at + fence_len;
1526    Some(info_start..block_start + line_len)
1527}
1528
1529/// The spaces a line opens with.
1530fn leading_spaces(s: &str) -> usize {
1531    s.bytes().take_while(|&b| b == b' ').count()
1532}
1533
1534/// A line's block-quote markers — each `>` behind up to three spaces, with the
1535/// one space after it — as the quote depth and the byte offset past them.
1536fn strip_quote_markers(line: &str) -> (usize, usize) {
1537    let b = line.as_bytes();
1538    let (mut depth, mut i) = (0, 0);
1539    loop {
1540        let j = i + leading_spaces(&line[i..]);
1541        if j - i > 3 || b.get(j) != Some(&b'>') {
1542            return (depth, i);
1543        }
1544        depth += 1;
1545        i = j + 1 + usize::from(b.get(j + 1) == Some(&b' '));
1546    }
1547}
1548
1549/// The length of a list marker opening `s` — its indent (at most `max_lead`
1550/// spaces), a bullet or an ordinal, and the one space the item's content
1551/// starts after — or `None` when `s` opens with none.
1552fn list_marker_len(s: &str, max_lead: usize) -> Option<usize> {
1553    let b = s.as_bytes();
1554    let lead = leading_spaces(s);
1555    if lead > max_lead {
1556        return None;
1557    }
1558    let mark = match b.get(lead)? {
1559        b'-' | b'*' | b'+' => 1,
1560        c if c.is_ascii_digit() => {
1561            let digits = b[lead..].iter().take_while(|c| c.is_ascii_digit()).count();
1562            if digits > 9 || !matches!(b.get(lead + digits), Some(b'.' | b')')) {
1563                return None;
1564            }
1565            digits + 1
1566        }
1567        _ => return None,
1568    };
1569    match b.get(lead + mark) {
1570        Some(b' ') => Some(lead + mark + 1),
1571        None => Some(lead + mark),
1572        _ => None,
1573    }
1574}
1575
1576/// The content column of the list item a continuation line indented `lead`
1577/// spaces (past `depth` quote markers) sits in: the nearest item above whose
1578/// content starts at or before `lead`. `0` when a line at the margin, or a
1579/// change of quote depth, says there is no such item.
1580fn item_content_column(before: &str, depth: usize, lead: usize) -> usize {
1581    for line in before.strip_suffix('\n').unwrap_or(before).rsplit('\n') {
1582        let (d, q) = strip_quote_markers(line);
1583        let s = &line[q..];
1584        if s.trim().is_empty() {
1585            continue;
1586        }
1587        if d != depth {
1588            return 0;
1589        }
1590        let mut col = 0;
1591        while let Some(n) = list_marker_len(&s[col..], usize::MAX) {
1592            col += n;
1593        }
1594        if col > 0 && col <= lead {
1595            return col;
1596        }
1597        if col == 0 && leading_spaces(s) == 0 {
1598            return 0;
1599        }
1600    }
1601    0
1602}
1603
1604/// A fenced code block's language for display: its info string, trimmed, or
1605/// `None` when there's no fence or the fence carries no language. The trimmed
1606/// text is what a frontend labels the box with; [`code_info_span`] is what an
1607/// edit replaces.
1608pub fn code_language(source: &str, block_start: usize) -> Option<String> {
1609    let span = code_info_span(source, block_start)?;
1610    let text = source.get(span)?.trim();
1611    (!text.is_empty()).then(|| text.to_string())
1612}
1613
1614/// A horizontal rule's dash count when the map isn't wrapping to a column grid
1615/// (the GUI, which wraps at pixel width): a fixed, sane width the frontend can
1616/// paint or re-wrap, instead of a runaway count from an unbounded wrap width.
1617const UNWRAPPED_RULE_WIDTH: usize = 40;
1618
1619/// The one glyph an inline formula renders to on a surface that paints
1620/// pictures in a line — what a plain surface handed such a map would show.
1621/// One column wide, so a column-wrapped build's arithmetic still holds; the
1622/// frontend that asked for atoms draws the picture as wide as it is.
1623const MATH_ATOM: char = '∑';
1624
1625/// What the surface a map is built for can paint, and how tall its pictures
1626/// came out — the things about a frontend that change the rows core lays
1627/// down, gathered from the frontend by [`crate::Doc`] and threaded into every
1628/// build. The defaults are the plain surface: nothing painted in a line, every
1629/// picture a one-row placeholder, which is what every test that passes
1630/// `Surface::default()` gets and what every build got before there was one.
1631#[derive(Clone, Debug, Default, PartialEq, Eq)]
1632pub struct Surface {
1633    /// How many visual rows each block image reserves, keyed by its
1634    /// destination — the frontend's per-image height, set through
1635    /// [`crate::Doc::set_media_rows`] so [`Builder::block_media`] can size the
1636    /// placeholder without core doing any I/O. A destination absent from the
1637    /// map (or a `0`/`1` entry) reserves the bare one-row placeholder.
1638    pub media_rows: HashMap<String, usize>,
1639    /// The same for each display formula, keyed by its TeX verbatim (the
1640    /// [`MathMark::tex`] a frontend was handed) — set through
1641    /// [`crate::Doc::set_math_rows`] once the frontend has typeset and
1642    /// measured the picture.
1643    pub math_rows: HashMap<String, usize>,
1644    /// Whether the surface can paint a picture *inside* a line of text, so an
1645    /// inline formula may render to one atom glyph it draws over
1646    /// ([`MathInfo`]). A pixel-laid-out frontend says yes; a terminal cannot
1647    /// composite an image over one cell, and leaves this off to keep an inline
1648    /// formula as the code-styled TeX it always showed. Off by default.
1649    pub inline_pictures: bool,
1650}
1651
1652/// The one source line rendering its markup raw — the caret's, when the mode
1653/// or the content asks for it — and how much of the markup that means. See
1654/// [`crate::Doc::reveal_line`], which decides both.
1655///
1656/// Two grades because two things ask. Under
1657/// [`MarkupMode::Full`](crate::MarkupMode::Full) *every* delimiter on the line
1658/// comes back (`markup: true`). In the two hidden modes a formula still
1659/// reveals — its content is its TeX and not its picture, so hiding is not
1660/// enough — and the line is threaded through with `markup: false`: a math node
1661/// meeting it shows its source, and an emphasis meeting it hides its
1662/// asterisks as it always did.
1663#[derive(Clone, Debug, PartialEq, Eq)]
1664pub struct Reveal {
1665    /// The source byte range of the line, newline excluded — empty but present
1666    /// on a blank line.
1667    pub line: Range<usize>,
1668    /// Whether ordinary inline markup reveals on it too, or only math.
1669    pub markup: bool,
1670}
1671
1672impl Reveal {
1673    /// The caret's line under `MarkupMode::Full`: everything on it reveals.
1674    pub fn full(line: Range<usize>) -> Self {
1675        Reveal { line, markup: true }
1676    }
1677
1678    /// The caret's line in a hidden mode, where only a formula reveals.
1679    pub fn math(line: Range<usize>) -> Self {
1680        Reveal {
1681            line,
1682            markup: false,
1683        }
1684    }
1685
1686    /// Whether `span` meets this line — the test every arm that reveals runs.
1687    ///
1688    /// Touching at an endpoint counts: an emphasis ending exactly where the
1689    /// line does is on that line, and a zero-length reveal range (the caret
1690    /// alone on a blank line) still meets a node that starts there. The test
1691    /// is deliberately generous — the failure it avoids is revealing one
1692    /// delimiter of a pair while hiding the other, which looks like corruption
1693    /// rather than like markup.
1694    fn meets(&self, span: &Range<usize>) -> bool {
1695        span.start <= self.line.end && self.line.start <= span.end
1696    }
1697}
1698
1699/// Render the document to a [`VisualMap`]. `wrap` is the column budget for
1700/// word-wrapping (`Some` for the monospace TUI), or `None` to emit one row per
1701/// block — the GUI does its own proportional pixel wrapping over these rows.
1702/// Text and offsets come from the AST (`str` nodes carry the verbatim source
1703/// slice and an exact span), so the original source string isn't needed here.
1704pub fn build(
1705    nodes: &[FlatNode],
1706    source: &str,
1707    wrap: Option<usize>,
1708    preserve_soft: bool,
1709    surface: &Surface,
1710    reveal: Option<Reveal>,
1711) -> VisualMap {
1712    let Some(doc) = nodes.iter().position(|n| n.kind == Kind::Doc) else {
1713        return VisualMap::default();
1714    };
1715    let top = top_level(nodes, doc);
1716    let mut b = Builder {
1717        nodes,
1718        source,
1719        wrap: wrap.map(|w| w.max(8)),
1720        rows: Vec::new(),
1721        tables: Vec::new(),
1722        last_off: 0,
1723        stepped_over: 0,
1724        surface,
1725        break_glyph: Cell::new(' '),
1726        preserve_soft,
1727        reveal: reveal.clone(),
1728        pending_mark_ends: RefCell::new(Vec::new()),
1729        pending_math: RefCell::new(Vec::new()),
1730        saw_math: Cell::new(false),
1731        presentation: Presentation::default(),
1732        faces: RefCell::new(FaceTable::default()),
1733    };
1734    // The hidden frontmatter's end is the baseline for the leading and trailing
1735    // blank rows and for the caret floor — see [`hidden_prefix_end`].
1736    // `top_level` has already dropped every `metadata` child, so read it off
1737    // the arena.
1738    let hidden_end = hidden_prefix_end(source, metadata_end_of(nodes, doc));
1739    let last_drawn = b.top_blocks(&top, hidden_end);
1740    b.emit_trailing_blank_lines(last_drawn.unwrap_or(BlockClass::Paragraph), hidden_end);
1741    let content_start = floor_of(
1742        &b.rows,
1743        top.first().map_or(hidden_end, |&i| nodes[i].span.start),
1744    );
1745    let stops = collect_stops(&b.rows);
1746    let mark_ends = collect_mark_ends(&b.rows);
1747    label_media_boundaries(&mut b.rows);
1748    let code_blocks = code_block_spans(&b.rows);
1749    let media = media_spans(&b.rows);
1750    let directives = directive_spans(&b.rows);
1751    let math = math_spans(&b.rows);
1752    VisualMap {
1753        rows: b.rows,
1754        content_start,
1755        stops,
1756        mark_ends,
1757        tables: b.tables,
1758        code_blocks,
1759        media,
1760        directives,
1761        math,
1762        faces: b.faces.into_inner(),
1763        spelling: OnceLock::new(),
1764    }
1765}
1766
1767/// Like [`build`], but reuses a persistent [`BlockCache`] so an edit re-renders
1768/// only the top-level blocks whose source bytes changed *and* marshals only
1769/// those blocks from twig instead of the whole arena.
1770///
1771/// `top` is the document's top-level blocks — twig's `child_spans` of the doc
1772/// root: `(node_id, kind, span)` for each, in order. `fetch_subtree(node_id)`
1773/// marshals one block's subtree (local-indexed, root at 0) and is called *only*
1774/// for a block that missed the cache, i.e. one that actually changed. So a
1775/// keystroke marshals one small subtree, not ~20k nodes. The result is
1776/// byte-for-byte identical to [`build`] on the same document (the
1777/// `build_cached_matches_build` test pins this); [`build`] stays the cache-free,
1778/// whole-arena reference. This is the entry point [`crate::Doc`] uses.
1779// One builder, and every one of these is a distinct input to the same layout
1780// pass — a struct of them would be built at the one call site and unpacked
1781// here, which is the same arguments with an extra name in the way.
1782#[allow(clippy::too_many_arguments)]
1783pub fn build_cached(
1784    top: &[QueryMatch],
1785    source: &str,
1786    wrap: Option<usize>,
1787    preserve_soft: bool,
1788    surface: &Surface,
1789    reveal: Option<Reveal>,
1790    cache: &mut BlockCache,
1791    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
1792) -> VisualMap {
1793    let wrap = wrap.map(|w| w.max(8));
1794
1795    // Wrapping is a function of the width, so a width change makes every cached
1796    // row's wrap wrong: start the cache over.
1797    if cache.wrap != Some(wrap) {
1798        cache.entries.clear();
1799        cache.wrap = Some(wrap);
1800    }
1801    cache.generation = cache.generation.wrapping_add(1);
1802
1803    // Frontmatter (a leading `metadata` block) is document metadata, not prose:
1804    // hidden in the rich view exactly as [`Builder::blocks`] skips it.
1805    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
1806
1807    // The outer builder only accumulates rows/tables and spells block boundaries
1808    // — both a function of the source and `last_off`, never of a node array — so
1809    // it carries an empty `nodes`. Each changed block is rendered by a *fresh*
1810    // builder over that block's subtree.
1811    let mut b = Builder {
1812        nodes: &[],
1813        source,
1814        wrap,
1815        rows: Vec::new(),
1816        tables: Vec::new(),
1817        last_off: 0,
1818        stepped_over: 0,
1819        surface,
1820        break_glyph: Cell::new(' '),
1821        preserve_soft,
1822        reveal: reveal.clone(),
1823        pending_mark_ends: RefCell::new(Vec::new()),
1824        pending_math: RefCell::new(Vec::new()),
1825        saw_math: Cell::new(false),
1826        presentation: Presentation::default(),
1827        faces: RefCell::new(FaceTable::default()),
1828    };
1829
1830    // Record the per-block row decomposition as we go, so a later
1831    // [`build_spliced`] can patch one block without rebuilding the map.
1832    let mut layout_blocks: Vec<BlockLayout> = Vec::with_capacity(blocks.len());
1833    // The document's face table, assembled block by block: from the walk on a
1834    // miss, from what the entry stored on a hit. The outer builder walks no
1835    // attributes of its own (it spells boundaries), so it never adds to it.
1836    let mut faces = FaceTable::default();
1837    let mut all_shift_safe = true;
1838    // The class of the last block that drew anything: what the next separator
1839    // closes, and what the trailing blank lines close at the end. A hidden block
1840    // (a comment) never becomes it — see [`Builder::block_or_hidden`], whose
1841    // step-over this loop repeats for the incremental walk.
1842    let mut above: Option<BlockClass> = None;
1843    let hidden_end = hidden_prefix_end(
1844        source,
1845        top.iter()
1846            .filter(|m| m.kind == Kind::Metadata)
1847            .map(|m| m.span.end)
1848            .next_back(),
1849    );
1850    for block in &blocks {
1851        let start = block.span.start;
1852        let before_sep = b.rows.len();
1853        // This walker has no node arena at all (see the `nodes: &[]` above),
1854        // but a top-level query match carries its kind — the same string
1855        // `BlockClass::from_node_kind` classifies for the whole-arena walk, so
1856        // the incremental and full builds label a boundary identically.
1857        let below = BlockClass::from_node_kind(&block.kind);
1858        if let Some(above) = above {
1859            b.emit_separators_before(start, &[], true, Boundary { above, below });
1860        } else {
1861            let from = b.leading_from(hidden_end);
1862            b.emit_leading_blank_lines(from, start, below);
1863        }
1864        let after_sep = b.rows.len();
1865        let bytes = block_bytes(source, &block.span);
1866        let hash = block_hash(bytes);
1867        // How this block meets the reveal line, if at all — part of its cache
1868        // key, since the same bytes render differently on the caret's line.
1869        let rkey = reveal_key(&reveal, &block.span);
1870
1871        // Hit: clone the block's rows shifted to its current offset and restore
1872        // the (shifted) `last_off` so the next separator lands right — no marshal.
1873        // Only shift-safe blocks are ever cached, so a hit is safe by construction.
1874        let mut has_math = false;
1875        if let Some(hit) = cache.reuse(hash, bytes, &rkey) {
1876            faces.merge(&hit.faces);
1877            has_math = hit.has_math;
1878            let delta = start as isize - hit.built_start as isize;
1879            for row in &hit.rows {
1880                b.rows.push(shift_row(row, delta));
1881            }
1882            b.last_off = (hit.last_off as isize + delta) as usize;
1883            // `0` is a block that stepped over nothing, and no answer to shift.
1884            if hit.stepped_over > 0 {
1885                let stepped = (hit.stepped_over as isize + delta) as usize;
1886                b.stepped_over = b.stepped_over.max(stepped);
1887            }
1888        } else {
1889            // Miss: marshal just this block's subtree and render it. A subtree is
1890            // self-contained with local ids (root at 0) and absolute spans, so a
1891            // fresh builder over it produces the same rows the whole-arena path
1892            // would. An empty subtree (twig couldn't hand it back) renders nothing.
1893            let subtree = fetch_subtree(block.node_id);
1894            if !subtree.is_empty() {
1895                let mut sub = Builder {
1896                    nodes: &subtree,
1897                    source,
1898                    wrap,
1899                    rows: Vec::new(),
1900                    tables: Vec::new(),
1901                    last_off: 0,
1902                    stepped_over: 0,
1903                    surface,
1904                    break_glyph: Cell::new(' '),
1905                    preserve_soft,
1906                    reveal: reveal.clone(),
1907                    pending_mark_ends: RefCell::new(Vec::new()),
1908                    pending_math: RefCell::new(Vec::new()),
1909                    saw_math: Cell::new(false),
1910                    presentation: Presentation::default(),
1911                    faces: RefCell::new(FaceTable::default()),
1912                };
1913                sub.block(0, &[], &[]);
1914                // A block that drew nothing is stepped over, not stood on: its
1915                // `last_off` is its own end, so the separator after it counts
1916                // from there. The sub-builder started at 0 and never moved, and
1917                // 0 is where the next separator would otherwise count from —
1918                // every line of the document, as a blank row each.
1919                let last_off = if sub.rows.is_empty() {
1920                    block.span.end
1921                } else {
1922                    sub.last_off
1923                };
1924                let stepped_over = sub.stepped_over;
1925                b.stepped_over = b.stepped_over.max(stepped_over);
1926                // The names this block's glyph ids stand for. They go into the
1927                // document's table *and* into the cache entry, because a hit
1928                // re-emits these rows without walking an attribute again.
1929                let block_faces = sub.faces.into_inner();
1930                faces.merge(&block_faces);
1931                has_math = sub.saw_math.get();
1932                // Cache only a block that is table-free AND renders inside its own
1933                // span: those two are the conditions for reuse-by-shift to be
1934                // correct. A block failing either is re-rendered every build (a
1935                // fresh render always matches a fresh whole-document build).
1936                if sub.tables.is_empty() {
1937                    if rows_within(&sub.rows, &block.span) {
1938                        cache.store(
1939                            hash,
1940                            bytes,
1941                            start,
1942                            sub.rows.clone(),
1943                            last_off,
1944                            stepped_over,
1945                            rkey,
1946                            has_math,
1947                            block_faces,
1948                        );
1949                    }
1950                    b.rows.extend(sub.rows);
1951                } else {
1952                    // A table block is never cached; rebase its row-index
1953                    // bookkeeping onto the combined row vector and append.
1954                    let base = b.rows.len();
1955                    for t in &mut sub.tables {
1956                        t.rows_span = (t.rows_span.start + base)..(t.rows_span.end + base);
1957                    }
1958                    b.rows.extend(sub.rows);
1959                    b.tables.extend(sub.tables);
1960                }
1961                b.last_off = last_off;
1962            }
1963        }
1964        let content_rows = b.rows.len() - after_sep;
1965        let sep_rows = if content_rows == 0 {
1966            // Hidden: take back the separator drawn for it, so what stands
1967            // either side meets across one boundary. Its layout entry stays, at
1968            // no rows, so the splice arithmetic still counts one entry per block.
1969            b.rows.truncate(before_sep);
1970            // A cache hit restored the stored `last_off` above; an empty subtree
1971            // (twig couldn't hand it back) restored nothing. Either way the walk
1972            // stands past the block.
1973            b.last_off = b.last_off.max(block.span.end);
1974            b.stepped_over = b.stepped_over.max(block.span.end);
1975            0
1976        } else {
1977            above = Some(BlockClass::from_node_kind(&block.kind));
1978            all_shift_safe &= rows_within(&b.rows[after_sep..], &block.span);
1979            after_sep - before_sep
1980        };
1981        layout_blocks.push(BlockLayout {
1982            span: block.span.clone(),
1983            kind: block.kind.clone(),
1984            sep_rows,
1985            content_rows,
1986            has_math,
1987        });
1988    }
1989
1990    let before_trailing = b.rows.len();
1991    b.emit_trailing_blank_lines(above.unwrap_or(BlockClass::Paragraph), hidden_end);
1992    let trailing_rows = b.rows.len() - before_trailing;
1993
1994    // Evict every entry no block reused this build, so the cache tracks the
1995    // current document instead of growing without bound over a session.
1996    let g = cache.generation;
1997    cache.entries.retain(|_, bucket| {
1998        bucket.retain(|e| e.generation == g);
1999        !bucket.is_empty()
2000    });
2001
2002    cache.layout = Layout {
2003        blocks: layout_blocks,
2004        trailing_rows,
2005        built_len: source.len(),
2006        has_tables: !b.tables.is_empty(),
2007        all_shift_safe,
2008        reveal: reveal.clone(),
2009    };
2010
2011    // The first rendered offset is the first non-metadata block's start — the
2012    // analogue of [`first_content_offset`] for the top-level list. With nothing
2013    // but frontmatter it's the end of that frontmatter, and 0 for an empty
2014    // document ([`hidden_prefix_end`]).
2015    let content_start = floor_of(&b.rows, blocks.first().map_or(hidden_end, |m| m.span.start));
2016    let stops = collect_stops(&b.rows);
2017    let mark_ends = collect_mark_ends(&b.rows);
2018    label_media_boundaries(&mut b.rows);
2019    let code_blocks = code_block_spans(&b.rows);
2020    let media = media_spans(&b.rows);
2021    let directives = directive_spans(&b.rows);
2022    let math = math_spans(&b.rows);
2023    VisualMap {
2024        rows: b.rows,
2025        content_start,
2026        stops,
2027        mark_ends,
2028        tables: b.tables,
2029        code_blocks,
2030        media,
2031        directives,
2032        math,
2033        faces,
2034        spelling: OnceLock::new(),
2035    }
2036}
2037
2038/// The fast path for a single-block edit: patch the previous [`VisualMap`] in
2039/// place rather than reassembling it. Returns `Some(new_map)` when it applies,
2040/// or `None` to tell the caller to fall back to [`build_cached`] (always
2041/// correct). Consumes `prev` either way — on `None` the caller rebuilds from
2042/// scratch and doesn't need it.
2043///
2044/// It applies only when `dirty` (twig's dirty byte range) falls inside exactly
2045/// one top-level block AND the block structure around it is unchanged — verified
2046/// by matching the new `top` list against the previous [`Layout`] block for
2047/// block: kinds unchanged, spans before the edit identical, spans after it
2048/// shifted by the byte delta, count unchanged. Any deviation — a block split or
2049/// merged, a fence opened to swallow later blocks, a table anywhere, a
2050/// multi-block edit — fails the match and returns `None`. That check is what
2051/// makes the byte-range trustworthy: twig's dirty range is exact about *bytes*
2052/// but silent about *reparse*, and the structural match catches the reparse
2053/// effects it can't see.
2054///
2055/// When it applies, the unchanged prefix rows move verbatim, the suffix rows
2056/// shift by the delta *in place* (integer adds, no glyph copy), and only the one
2057/// dirty block is re-marshalled and re-rendered; stops splice the same way by
2058/// offset. So the cost is O(rows after the edit), and nothing before the edit is
2059/// touched. The hash-keyed entry cache is left alone — a later [`build_cached`]
2060/// will miss on the changed block, re-render it, and evict the stale entry, so
2061/// chained splices neither corrupt nor grow it.
2062// One builder, and every one of these is a distinct input to the same layout
2063// pass — a struct of them would be built at the one call site and unpacked
2064// here, which is the same arguments with an extra name in the way.
2065#[allow(clippy::too_many_arguments)]
2066pub fn build_spliced(
2067    prev: VisualMap,
2068    source: &str,
2069    wrap: Option<usize>,
2070    preserve_soft: bool,
2071    top: &[QueryMatch],
2072    dirty: Range<usize>,
2073    surface: &Surface,
2074    reveal: Option<Reveal>,
2075    cache: &mut BlockCache,
2076    mut fetch_subtree: impl FnMut(u32) -> Vec<FlatNode>,
2077) -> Option<VisualMap> {
2078    let wrap = wrap.map(|w| w.max(8));
2079    // A width change invalidates every cached row — a full rebuild's job.
2080    if cache.wrap != Some(wrap) {
2081        return None;
2082    }
2083    // So does a moved reveal line, and for the same reason: this path reuses
2084    // every row outside the dirty block, and those rows encode which line was
2085    // showing its raw markup when they were built. Typing almost always moves
2086    // the caret, so under `MarkupMode::Full` this bails to `build_cached` on
2087    // most keystrokes — still block-cached, so only the edited block and the
2088    // revealed one actually re-render.
2089    if cache.layout.reveal != reveal {
2090        return None;
2091    }
2092    // Take the previous layout; on any bail below the caller rebuilds it (and the
2093    // map) via `build_cached`, so leaving it empty is fine. A table or a block
2094    // that renders outside its span (a degenerate inline span) makes shifting
2095    // unsound, so those force the full-rebuild path.
2096    let prev_layout = std::mem::take(&mut cache.layout);
2097    if prev_layout.built_len == 0 || prev_layout.has_tables || !prev_layout.all_shift_safe {
2098        return None;
2099    }
2100    // The layout addresses `prev` by row index, so it is only usable against the
2101    // map it was built from. A frontend is free to hold the map it was handed and
2102    // present it differently — leaf-ratatui splices blank filler rows under an
2103    // oversized heading so the raster has somewhere to stand — and if one of those
2104    // comes back here the row arithmetic below lands on the wrong rows: the
2105    // re-rendered block is laid over a filler and the rows it really occupied
2106    // survive into the suffix, stranding a stale copy of the edited line and
2107    // pushing everything after it one row down, once per keystroke. A row count
2108    // that doesn't match what this layout describes is the tell, and the honest
2109    // answer is the full rebuild.
2110    let described_rows = prev_layout
2111        .blocks
2112        .iter()
2113        .map(|pl| pl.sep_rows + pl.content_rows)
2114        .sum::<usize>()
2115        + prev_layout.trailing_rows;
2116    if described_rows != prev.rows.len() {
2117        return None;
2118    }
2119
2120    let blocks: Vec<&QueryMatch> = top.iter().filter(|m| m.kind != Kind::Metadata).collect();
2121    if blocks.is_empty() || blocks.len() != prev_layout.blocks.len() {
2122        return None;
2123    }
2124    let delta = source.len() as isize - prev_layout.built_len as isize;
2125
2126    // The single block whose NEW span contains the whole dirty range. A dirty
2127    // range straddling a block boundary (or a separator) finds none → bail.
2128    let k = blocks
2129        .iter()
2130        .position(|m| m.span.start <= dirty.start && dirty.end <= m.span.end)?;
2131
2132    // Structural match: every OTHER block is unchanged — same kind throughout,
2133    // span identical before the edit and shifted by `delta` after it. A mismatch
2134    // means the reparse reshaped the block structure, which only a full rebuild
2135    // renders correctly.
2136    for (i, (m, pl)) in blocks.iter().zip(&prev_layout.blocks).enumerate() {
2137        if m.kind != pl.kind {
2138            return None;
2139        }
2140        if i == k {
2141            continue;
2142        }
2143        let want = if i < k {
2144            pl.span.clone()
2145        } else {
2146            (pl.span.start as isize + delta) as usize..(pl.span.end as isize + delta) as usize
2147        };
2148        if m.span != want {
2149            return None;
2150        }
2151    }
2152    // The dirty block itself: start unchanged (the edit is inside it, past its
2153    // start), end moved by exactly the delta.
2154    let pk_start = prev_layout.blocks[k].span.start;
2155    let pk_end = prev_layout.blocks[k].span.end;
2156    let pk_sep = prev_layout.blocks[k].sep_rows;
2157    let pk_content = prev_layout.blocks[k].content_rows;
2158    if blocks[k].span.start != pk_start || blocks[k].span.end != (pk_end as isize + delta) as usize
2159    {
2160        return None;
2161    }
2162
2163    // Re-render the dirty block from its subtree. A table makes the splice
2164    // bookkeeping unsafe, so bail if one appears.
2165    let subtree = fetch_subtree(blocks[k].node_id);
2166    if subtree.is_empty() {
2167        return None;
2168    }
2169    let mut sub = Builder {
2170        nodes: &subtree,
2171        source,
2172        wrap,
2173        rows: Vec::new(),
2174        tables: Vec::new(),
2175        last_off: 0,
2176        stepped_over: 0,
2177        surface,
2178        break_glyph: Cell::new(' '),
2179        preserve_soft,
2180        reveal: reveal.clone(),
2181        pending_mark_ends: RefCell::new(Vec::new()),
2182        pending_math: RefCell::new(Vec::new()),
2183        saw_math: Cell::new(false),
2184        presentation: Presentation::default(),
2185        faces: RefCell::new(FaceTable::default()),
2186    };
2187    sub.block(0, &[], &[]);
2188    // A table, or content that renders outside the block's span (a degenerate
2189    // inline span), makes the shift bookkeeping unsound — fall back.
2190    if !sub.tables.is_empty() || !rows_within(&sub.rows, &blocks[k].span) {
2191        return None;
2192    }
2193    // The face table starts from the previous map's, because every row this
2194    // path keeps was built against it and its glyphs' ids still mean what they
2195    // meant. The re-rendered block adds whatever it met. An id the edit took
2196    // the last glyph of stays in the table, naming nothing — the price of not
2197    // walking the rows this path exists to avoid walking.
2198    let mut faces = prev.faces;
2199    faces.merge(&sub.faces.into_inner());
2200    let sub_saw_math = sub.saw_math.get();
2201    let new_content = sub.rows;
2202    let new_content_len = new_content.len();
2203    let new_stops = collect_stops(&new_content);
2204    let new_mark_ends = collect_mark_ends(&new_content);
2205
2206    // Row span of the dirty block's CONTENT. Its leading separator stays in the
2207    // prefix: the gap before block k is unchanged, since k's start didn't move.
2208    let content_start_row: usize = prev_layout.blocks[..k]
2209        .iter()
2210        .map(|pl| pl.sep_rows + pl.content_rows)
2211        .sum::<usize>()
2212        + pk_sep;
2213    let content_end_row = content_start_row + pk_content;
2214
2215    // Splice rows: [prefix | new content | suffix + delta]. The prefix moves
2216    // untouched; the suffix shifts in place — integer adds, no glyph copy.
2217    let mut rows = prev.rows;
2218    let mut suffix = rows.split_off(content_end_row);
2219    rows.truncate(content_start_row);
2220    for row in &mut suffix {
2221        shift_row_in_place(row, delta);
2222    }
2223    rows.reserve(new_content_len + suffix.len());
2224    rows.extend(new_content);
2225    rows.extend(suffix);
2226
2227    // Splice stops by offset. The old dirty block covered `[pk_start, pk_end]`:
2228    // prefix stops fall below it, suffix stops above it (shift by delta), the new
2229    // content supplies the middle. The three ranges stay disjoint and ascending,
2230    // so the result needs no re-sort.
2231    let p1 = prev.stops.partition_point(|&s| s < pk_start);
2232    let p2 = prev.stops.partition_point(|&s| s <= pk_end);
2233    let mut stops = Vec::with_capacity(p1 + new_stops.len() + (prev.stops.len() - p2));
2234    stops.extend_from_slice(&prev.stops[..p1]);
2235    stops.extend(new_stops);
2236    for &s in &prev.stops[p2..] {
2237        stops.push((s as isize + delta) as usize);
2238    }
2239    // The mark ends splice the same way: they are offsets in the same
2240    // coordinates, cut at the same block.
2241    let m1 = prev.mark_ends.partition_point(|&s| s < pk_start);
2242    let m2 = prev.mark_ends.partition_point(|&s| s <= pk_end);
2243    let mut mark_ends = Vec::with_capacity(m1 + new_mark_ends.len() + (prev.mark_ends.len() - m2));
2244    mark_ends.extend_from_slice(&prev.mark_ends[..m1]);
2245    mark_ends.extend(new_mark_ends);
2246    for &s in &prev.mark_ends[m2..] {
2247        mark_ends.push((s as isize + delta) as usize);
2248    }
2249
2250    // Record the patched layout for the next splice: spans move to the new
2251    // coordinates, and the dirty block takes its new content-row count.
2252    let mut new_blocks = prev_layout.blocks;
2253    for (pl, m) in new_blocks.iter_mut().zip(&blocks) {
2254        pl.span = m.span.clone();
2255    }
2256    new_blocks[k].content_rows = new_content_len;
2257    new_blocks[k].has_math = sub_saw_math;
2258    cache.layout = Layout {
2259        blocks: new_blocks,
2260        trailing_rows: prev_layout.trailing_rows,
2261        built_len: source.len(),
2262        has_tables: false,
2263        // Every prefix/suffix block was shift-safe last build (we bailed
2264        // otherwise) and the re-rendered block was just checked, so the patched
2265        // document is still entirely shift-safe.
2266        all_shift_safe: true,
2267        reveal,
2268    };
2269
2270    label_media_boundaries(&mut rows);
2271    let code_blocks = code_block_spans(&rows);
2272    let media = media_spans(&rows);
2273    let directives = directive_spans(&rows);
2274    let math = math_spans(&rows);
2275    Some(VisualMap {
2276        rows,
2277        // The edit was inside one block, so no block moved its start and the
2278        // lines above the first are the ones the floor was taken from.
2279        content_start: prev.content_start,
2280        stops,
2281        mark_ends,
2282        tables: Vec::new(),
2283        code_blocks,
2284        media,
2285        directives,
2286        math,
2287        faces,
2288        spelling: OnceLock::new(),
2289    })
2290}
2291
2292/// A persistent, content-keyed cache of the rows each top-level block renders
2293/// to — the [`VisualMap`] analogue of the GUI's ShapedLine cache, one level
2294/// down. Held by a [`crate::Doc`] and threaded into [`build_cached`], it is what
2295/// makes a rebuild after a keystroke cost "re-render the edited block + shift
2296/// the rest" instead of re-rendering the whole document.
2297///
2298/// A top-level block's rows are a pure function of its source bytes and the wrap
2299/// width, so an unchanged block's rows are cloned and their source offsets
2300/// shifted by the edit's byte delta rather than rebuilt glyph by glyph. Two
2301/// things make that purity hold: at the top level the render prefix is always
2302/// empty (nesting prefixes — a quote gutter, a list indent — exist only *inside*
2303/// a top-level block, within its cached unit), and a block's output never reads
2304/// the incoming `last_off` (it writes `last_off` from its own content before any
2305/// nested separator reads it). So the only thing that differs between two
2306/// positions of an unchanged block is a uniform offset shift. Keyed by a fast
2307/// hash of the block's bytes with the bytes kept for a verify-on-hit — exactly
2308/// the shape cache's weak-hash-then-compare, so a collision costs a re-render,
2309/// never a wrong row.
2310///
2311/// Tables are never cached (a block that emits any table row is always rebuilt):
2312/// their rows are cross-referenced from the map's `tables` side-table by row
2313/// index, which a blind offset-shift wouldn't fix up, and they are rare enough
2314/// that the simplicity beats the reuse.
2315#[derive(Default)]
2316pub struct BlockCache {
2317    /// The wrap width every entry was built at; a change invalidates all of
2318    /// them. `None` before the first build (distinct from `Some(None)`, the
2319    /// unwrapped GUI width).
2320    wrap: Option<Option<usize>>,
2321    /// Bumped once per [`build_cached`]. An entry reused or inserted this build
2322    /// carries the current value; stale entries are dropped at the end of it.
2323    generation: u64,
2324    /// `hash(bytes)` → the block(s) sharing that hash — a bucket because
2325    /// distinct blocks can collide, while two *identical* blocks share one entry
2326    /// (free dedup).
2327    entries: HashMap<u64, Vec<CachedBlock>>,
2328    /// The row/stop decomposition of the last build, which [`build_spliced`]
2329    /// patches in place for a single-block edit. Kept in step with whatever
2330    /// [`VisualMap`] was last produced; empty before the first build.
2331    layout: Layout,
2332}
2333
2334/// How the last build's [`VisualMap`] decomposes into top-level blocks — the
2335/// bookkeeping [`build_spliced`] needs to splice one block's rows and stops
2336/// without rebuilding the whole map. Every field describes the *previous* build,
2337/// in that build's coordinates.
2338#[derive(Default)]
2339struct Layout {
2340    /// One entry per rendered (metadata-filtered) top-level block, in order.
2341    blocks: Vec<BlockLayout>,
2342    /// Trailing blank rows past the last block (from `emit_trailing_blank_lines`).
2343    trailing_rows: usize,
2344    /// The source length this layout was built at — the reference for the edit's
2345    /// byte delta.
2346    built_len: usize,
2347    /// Whether the last build drew any table. A table's cross-referenced row
2348    /// indices don't survive a blind splice, so their presence makes
2349    /// [`build_spliced`] bail to a full rebuild.
2350    has_tables: bool,
2351    /// Whether every block rendered strictly inside its own span (see
2352    /// [`rows_within`]). A block that doesn't — a malformed Markdown inline node
2353    /// that twig leaves with a degenerate `0..0` span renders at a fixed offset
2354    /// outside its block — can't be shifted correctly, so its presence makes
2355    /// [`build_spliced`] bail to a full rebuild.
2356    all_shift_safe: bool,
2357    /// The reveal line this layout was built under (see [`Builder::reveal`]).
2358    /// A splice reuses every row it isn't re-rendering, so a reveal line that
2359    /// has moved would leave the old line still showing its delimiters and the
2360    /// new one still hiding them — [`build_spliced`] bails when this changes.
2361    reveal: Option<Reveal>,
2362}
2363
2364/// One top-level block's contribution to the last build: its span and kind (for
2365/// the structural match that proves only one block changed) and how many
2366/// separator and content rows it emitted (to locate its slice of the row
2367/// vector).
2368struct BlockLayout {
2369    span: Range<usize>,
2370    kind: Kind,
2371    sep_rows: usize,
2372    content_rows: usize,
2373    /// Whether the block holds a formula — see [`BlockCache::math_meets`].
2374    has_math: bool,
2375}
2376
2377/// One cached block: the rows it rendered to, plus what a reuse at a new
2378/// position needs to shift them. Offsets are stored absolute (as built) and
2379/// shifted by `new_start - built_start` on reuse.
2380struct CachedBlock {
2381    /// The block's exact source bytes, compared on a hash hit so a collision
2382    /// can never hand back another block's rows.
2383    bytes: Box<[u8]>,
2384    /// The offset the rows were built at (the block's `span.start`).
2385    built_start: usize,
2386    /// The block's rows, offsets absolute as built.
2387    rows: Vec<VRow>,
2388    /// `last_off` after this block was emitted, absolute as built — restored
2389    /// (shifted) on reuse so the following separator lands correctly.
2390    last_off: usize,
2391    /// `stepped_over` after this block was emitted, absolute as built — the
2392    /// hidden tail a block ends with (a `</div>`), restored with `last_off`
2393    /// so the trailing blank lines are counted from past it on a hit too.
2394    stepped_over: usize,
2395    /// Where the reveal line fell *within this block* when the rows were built,
2396    /// as a block-relative byte range — see [`reveal_key`]. Compared alongside
2397    /// `bytes` on a hit, because identical source renders to different rows
2398    /// depending on whether the caret's line is inside it: the same `*em*`
2399    /// shows its asterisks on the revealed line and hides them everywhere else.
2400    ///
2401    /// Block-relative rather than absolute so an unaffected block still hits
2402    /// after an edit shifts it, and `None` for the overwhelmingly common
2403    /// no-reveal case — which is why an entry stored under `MarkupMode::None`
2404    /// keeps hitting for every block that isn't the caret's.
2405    reveal: Option<Range<usize>>,
2406    /// Whether the block holds a formula, so a hit can say so to the layout
2407    /// without walking the rows it is re-emitting.
2408    has_math: bool,
2409    /// The named families this block's glyphs are set in — see
2410    /// [`VisualMap::faces`]. Stored with the rows because a hit re-emits them
2411    /// without walking a `data-font` again, and the map still has to be able to
2412    /// say what the id on a reused glyph names. Empty for every block that
2413    /// names no family, which is nearly all of them.
2414    faces: FaceTable,
2415    /// The build that last reused or inserted this entry (see `generation`).
2416    generation: u64,
2417}
2418
2419/// Where `reveal` falls inside a block, in block-relative bytes — the extra key
2420/// a cached block is stored and matched under.
2421///
2422/// `None` when the block doesn't meet the reveal line at all, which is every
2423/// block on every build in the two hidden modes, and all but one of them under
2424/// [`crate::MarkupMode::Full`]. So the cache keeps its hit rate as the caret
2425/// moves: only the line the caret leaves and the line it arrives at re-render.
2426fn reveal_key(reveal: &Option<Reveal>, span: &Range<usize>) -> Option<Range<usize>> {
2427    let r = reveal.as_ref()?;
2428    // The same generous intersection test `Builder::revealed` uses, so a block
2429    // is keyed as revealed exactly when its glyphs will be built that way.
2430    // Whether the line reveals markup or only math is not in the key: that is
2431    // a mode, and a mode change empties the cache.
2432    r.meets(span).then(|| {
2433        let start = r.line.start.max(span.start) - span.start;
2434        let end = r.line.end.min(span.end) - span.start;
2435        start..end
2436    })
2437}
2438
2439impl BlockCache {
2440    /// Whether the caret's `line` meets a top-level block that holds a
2441    /// formula, as of the last build — the question [`crate::Doc::reveal_line`]
2442    /// asks in the hidden markup modes before it threads the line through, so
2443    /// that only a line with something to reveal costs a rebuild.
2444    ///
2445    /// Answered from the layout rather than from twig because the layout is
2446    /// free: every build records per block whether its walk met a formula
2447    /// ([`BlockLayout::has_math`]), and a query against the tree is
2448    /// O(document) on every frame. Coarse on purpose — a block, not a line —
2449    /// since a block with a formula in it is rare, small, and the one thing
2450    /// worth re-rendering as the caret moves through it.
2451    ///
2452    /// Exact between edits, when the spans are the document's. Across an edit
2453    /// the spans are the previous revision's, so the caller checks again once
2454    /// the new layout is in and rebuilds if the answer changed.
2455    pub(crate) fn math_meets(&self, line: &Range<usize>) -> bool {
2456        self.layout
2457            .blocks
2458            .iter()
2459            .any(|b| b.has_math && b.span.start <= line.end && line.start <= b.span.end)
2460    }
2461
2462    /// Look up a block by hash, verify its bytes and reveal key, and on a hit
2463    /// stamp it used this build and hand back a borrow to shift-and-clone from.
2464    /// `None` on a miss (unknown hash, a collision whose bytes differ, or the
2465    /// same bytes built under a different reveal).
2466    fn reuse(
2467        &mut self,
2468        hash: u64,
2469        bytes: &[u8],
2470        reveal: &Option<Range<usize>>,
2471    ) -> Option<&CachedBlock> {
2472        let g = self.generation;
2473        let bucket = self.entries.get_mut(&hash)?;
2474        let e = bucket
2475            .iter_mut()
2476            .find(|e| &*e.bytes == bytes && &e.reveal == reveal)?;
2477        e.generation = g;
2478        Some(&*e)
2479    }
2480
2481    /// Cache the rows a freshly-rendered block produced (or refresh an existing
2482    /// entry for the same bytes and reveal — an identical block elsewhere, or a
2483    /// re-render).
2484    #[allow(clippy::too_many_arguments)]
2485    fn store(
2486        &mut self,
2487        hash: u64,
2488        bytes: &[u8],
2489        built_start: usize,
2490        rows: Vec<VRow>,
2491        last_off: usize,
2492        stepped_over: usize,
2493        reveal: Option<Range<usize>>,
2494        has_math: bool,
2495        faces: FaceTable,
2496    ) {
2497        let g = self.generation;
2498        let bucket = self.entries.entry(hash).or_default();
2499        if let Some(e) = bucket
2500            .iter_mut()
2501            .find(|e| &*e.bytes == bytes && e.reveal == reveal)
2502        {
2503            e.built_start = built_start;
2504            e.rows = rows;
2505            e.last_off = last_off;
2506            e.stepped_over = stepped_over;
2507            e.has_math = has_math;
2508            e.faces = faces;
2509            e.generation = g;
2510        } else {
2511            bucket.push(CachedBlock {
2512                bytes: bytes.into(),
2513                built_start,
2514                rows,
2515                last_off,
2516                stepped_over,
2517                reveal,
2518                has_math,
2519                faces,
2520                generation: g,
2521            });
2522        }
2523    }
2524}
2525
2526/// The source bytes a top-level block covers — the block cache's key material.
2527///
2528/// Clamped to the source rather than sliced by the span as twig gives it,
2529/// because that span can end *past* the last byte: the final block of a document
2530/// with no trailing newline is closed on the virtual newline the parser supplies
2531/// at EOF, so its `span.end` is `source.len() + 1`. Slicing by such a range
2532/// yields `None`, and the obvious `unwrap_or(&[])` reads that as *this block has
2533/// no bytes* — the wrong answer twice over.
2534///
2535/// Two blocks whose spans both overrun then key alike, and the second is served
2536/// the first one's rows. That is not hypothetical: a footnote definition is a
2537/// root beside `doc` merged back into the top level by [`top_blocks`], while the
2538/// `section` above it spans the definition's bytes too, so both end at EOF —
2539/// and a document ending in `[^note]: …` renders that definition as a second
2540/// copy of the heading. Even alone, a block that keeps hashing empty as the user
2541/// types in it is served the stale rows built before the edit.
2542///
2543/// Clamping hands back the bytes the block really covers, which tells both cases
2544/// apart, and costs nothing for a span that was in range to begin with.
2545fn block_bytes<'a>(source: &'a str, span: &Range<usize>) -> &'a [u8] {
2546    let bytes = source.as_bytes();
2547    let start = span.start.min(bytes.len());
2548    &bytes[start..span.end.clamp(start, bytes.len())]
2549}
2550
2551/// A fast, allocation-free content hash (FNV-1a) for a block's bytes. Weak by
2552/// design — the bytes are compared on a hit — so its only job is to spread
2553/// blocks across buckets cheaply. SipHash over every block's bytes on every
2554/// keystroke would cost more than it saves, the same lesson the shape cache
2555/// learned when it stopped hashing through the standard hasher.
2556fn block_hash(bytes: &[u8]) -> u64 {
2557    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
2558    for &x in bytes {
2559        h ^= x as u64;
2560        h = h.wrapping_mul(0x0000_0100_0000_01b3);
2561    }
2562    h
2563}
2564
2565/// Clone a cached row with every source offset advanced by `delta` — the whole
2566/// cost of reusing an unchanged block: integer adds where a rebuild would
2567/// re-shape every glyph.
2568fn shift_row(row: &VRow, delta: isize) -> VRow {
2569    let shift = |off: usize| (off as isize + delta) as usize;
2570    VRow {
2571        glyphs: row
2572            .glyphs
2573            .iter()
2574            .map(|g| Glyph {
2575                ch: g.ch,
2576                style: g.style,
2577                src: shift(g.src),
2578                stop: g.stop,
2579            })
2580            .collect(),
2581        end_src: shift(row.end_src),
2582        decoration: row.decoration,
2583        code: row.code,
2584        code_lang: row.code_lang.clone(),
2585        directive: row.directive,
2586        directive_label: row.directive_label.clone(),
2587        media: row.media.clone(),
2588        // A tick, not an offset — reuse carries it as-is, like `code_lang`.
2589        task: row.task,
2590        leaf_directive: row.leaf_directive.clone(),
2591        heading: row.heading,
2592        // Presentation, not offsets: names the author wrote, which a shifted
2593        // block still wears — like `code_lang`.
2594        align: row.align,
2595        line_height: row.line_height,
2596        // Structure, not offsets: a reused block's rows divide the same blocks
2597        // wherever the edit above moved them to.
2598        boundary: row.boundary,
2599        mark_ends: row.mark_ends.iter().map(|&o| shift(o)).collect(),
2600        // Strings and a glyph index: the glyph moved, the index into the row
2601        // did not.
2602        math: row.math.clone(),
2603    }
2604}
2605
2606/// Advance a row's source offsets by `delta` in place — the suffix half of
2607/// [`build_spliced`], where the rows are already owned and only need shifting,
2608/// not copying.
2609fn shift_row_in_place(row: &mut VRow, delta: isize) {
2610    for g in &mut row.glyphs {
2611        g.src = (g.src as isize + delta) as usize;
2612    }
2613    row.end_src = (row.end_src as isize + delta) as usize;
2614    for o in &mut row.mark_ends {
2615        *o = (*o as isize + delta) as usize;
2616    }
2617}
2618
2619/// Whether every source offset a block's rows carry falls inside the block's own
2620/// span — the precondition for reusing the block by a uniform offset shift. It
2621/// holds for well-formed blocks (their glyphs and row ends address bytes within
2622/// the block, synthetic glyphs point at the block start). It fails when a node
2623/// renders *outside* its block, which today means a malformed Markdown inline
2624/// node twig leaves with a degenerate `0..0` span: that content lands at a fixed
2625/// offset that doesn't move with the block. Such a block is re-rendered every
2626/// build instead of shifted, so the incremental map still matches a fresh one —
2627/// see [`build_cached`] and [`build_spliced`].
2628fn rows_within(rows: &[VRow], span: &Range<usize>) -> bool {
2629    rows.iter().all(|r| {
2630        r.end_src >= span.start
2631            && r.end_src <= span.end
2632            && r.glyphs
2633                .iter()
2634                .all(|g| g.src >= span.start && g.src <= span.end)
2635    })
2636}
2637
2638/// Where the rendered document begins when a leading `metadata` block is all
2639/// there is — the end of that hidden frontmatter, past the newline that closes
2640/// its last line so the floor sits at the start of the (empty) body rather than
2641/// on the closing `---`.
2642///
2643/// With a real block after it the frontmatter's end is never needed: the floor
2644/// is that block's start, and the rows begin there. With nothing after it, both
2645/// the caret floor and the trailing-blank-line count would otherwise fall back
2646/// to offset 0 — inside the hidden frontmatter — which put the caret *before*
2647/// the metadata and made typing land ahead of the opening `---`.
2648fn hidden_prefix_end(source: &str, meta_end: Option<usize>) -> usize {
2649    let Some(end) = meta_end else { return 0 };
2650    let end = end.min(source.len());
2651    let rest = &source[end..];
2652    if rest.starts_with("\r\n") {
2653        end + 2
2654    } else if rest.starts_with('\n') {
2655        end + 1
2656    } else {
2657        end
2658    }
2659}
2660
2661/// The caret floor: the first block's start, or the first blank line above it
2662/// when those lines draw rows ([`Builder::emit_leading_blank_lines`]).
2663fn floor_of(rows: &[VRow], first_start: usize) -> usize {
2664    rows.first()
2665        .map_or(first_start, |r| r.end_src.min(first_start))
2666}
2667
2668/// The end of the document's hidden frontmatter: the last `metadata` child of
2669/// `doc`, which is what [`top_level`] and [`Builder::blocks`] drop. `None` when
2670/// there is none.
2671fn metadata_end_of(nodes: &[FlatNode], doc: usize) -> Option<usize> {
2672    let mut end = None;
2673    let mut child = nodes[doc].first_child;
2674    while let Some(cid) = child {
2675        let n = &nodes[cid.0 as usize];
2676        if n.kind == Kind::Metadata {
2677            end = Some(n.span.end);
2678        }
2679        child = n.next_sibling;
2680    }
2681    end
2682}
2683
2684/// The document's rendered top-level blocks, as node indices in source order.
2685///
2686/// Not simply `doc`'s children, for two reasons. Frontmatter (a leading
2687/// `metadata` block) is document metadata rather than prose and is dropped, the
2688/// way [`Builder::blocks`] drops it. And a **footnote definition** (`[^1]: …`)
2689/// is not a child of `doc` at all: twig parses it as a root of its own, a
2690/// *sibling* of the document node with `parent == None`. A walk that starts at
2691/// `doc` therefore never reaches one, which is why a definition — and every
2692/// byte of its body — used to render as nothing at all. Merging the roots back
2693/// in by `span.start` puts each definition on screen exactly where it was
2694/// written, which is what keeps rows, stops, and offsets monotonic.
2695///
2696/// A **link reference definition** (`[foo]: /url`) is a root of the same kind,
2697/// and is merged for the opposite reason: it draws *nothing*, and the walk has
2698/// to know where it stands to step over it. A definition closing a README —
2699/// the `[links]: …` block under the prose — left no block over its lines, so
2700/// the separator logic read them as blank lines and drew an empty paragraph
2701/// per definition. Merged in, it is a hidden block like a comment, and
2702/// [`Builder::block_or_hidden`] moves the walk past it. One with no span
2703/// (`0..0`, what twig before 3.3.3 reported for every one) has nowhere to be
2704/// merged, and is left out as before.
2705///
2706/// Only those roots are merged. twig also leaves stray orphan `str` nodes
2707/// parented to nothing (the `*` of an emphasis run, for one); those are already
2708/// rendered as part of the subtree that owns their bytes, and re-emitting them
2709/// here would double them.
2710fn top_level(nodes: &[FlatNode], doc: usize) -> Vec<usize> {
2711    let mut out = Vec::new();
2712    let mut child = nodes[doc].first_child;
2713    while let Some(cid) = child {
2714        let n = &nodes[cid.0 as usize];
2715        if n.kind != Kind::Metadata {
2716            out.push(cid.0 as usize);
2717        }
2718        child = n.next_sibling;
2719    }
2720    out.extend(
2721        nodes
2722            .iter()
2723            .enumerate()
2724            .filter(|(_, n)| n.parent.is_none() && is_placed_definition(&n.kind, &n.span))
2725            .map(|(i, _)| i),
2726    );
2727    out.sort_by_key(|&i| nodes[i].span.start);
2728    out
2729}
2730
2731/// Is a parentless node of `kind` at `span` a definition the top-level walk
2732/// merges in — a footnote definition, or a link reference definition that
2733/// knows where it stands? Shared by [`top_level`] and [`top_blocks`] so the
2734/// two walks cannot disagree about what the top-level blocks are.
2735fn is_placed_definition(kind: &Kind, span: &Range<usize>) -> bool {
2736    match *kind {
2737        Kind::Footnote => true,
2738        Kind::Reference => span.end > span.start,
2739        _ => false,
2740    }
2741}
2742
2743/// The top-level blocks to hand [`build_cached`] / [`build_spliced`] — the
2744/// incremental path's twin of [`top_level`], which the two must agree with block
2745/// for block or the render paths diverge.
2746///
2747/// `child_spans(None)` gives `doc`'s children, which is all of them for an
2748/// ordinary document. A **footnote definition** is not one: twig parses `[^1]: …`
2749/// as a root beside `doc` with no parent, and indexes it at no offset either —
2750/// `node_at` inside its bytes answers `doc`, and a `query("footnote")` selector
2751/// finds nothing. Leaf used to discover them by marshalling the whole arena with
2752/// `nodes()` — the very cost the incremental path exists to avoid — behind a
2753/// byte-scan gate that gave documents with no `[^…]:` line a substring search
2754/// instead. twig 3.0's `definitions()` asks the library the question directly,
2755/// so both the marshal and the gate are gone.
2756///
2757/// The link reference definitions `definitions()` also reports are merged on
2758/// the same terms as [`top_level`] merges them — see [`is_placed_definition`].
2759///
2760/// This is the one part of the render that needs an [`Editor`] rather than a
2761/// marshalled node array. The builders themselves stay editor-free; this only
2762/// prepares their input.
2763pub(crate) fn top_blocks(editor: &mut Editor) -> Vec<QueryMatch> {
2764    let mut top = editor.child_spans(None).unwrap_or_default();
2765    let defs: Vec<QueryMatch> = definitions(editor)
2766        .into_iter()
2767        .filter(|m| is_placed_definition(&m.kind, &m.span))
2768        .collect();
2769    if defs.is_empty() {
2770        return top;
2771    }
2772    top.extend(defs);
2773    // Source order — what every offset-keyed thing downstream (rows, stops, the
2774    // splice path's block-for-block match) is built to assume.
2775    top.sort_by_key(|m| m.span.start);
2776    top
2777}
2778
2779/// Every `[^label]: …` definition in the document, in whatever order twig
2780/// reports them.
2781///
2782/// Filtered to [`Kind::Footnote`]: `definitions()` also reports the *link*
2783/// reference definitions (`[foo]: /url`), which are [`top_blocks`]'s business
2784/// and not [`crate::Doc::footnote_at_caret`]'s.
2785///
2786/// Empty when the document can't be walked, which leaves [`top_blocks`] with
2787/// the ordinary top-level children and [`crate::Doc::footnote_at_caret`] with an
2788/// undefined reference — in both cases the same answer as a document that has
2789/// no definitions, which is the right way to degrade.
2790pub(crate) fn footnote_definitions(editor: &mut Editor) -> Vec<QueryMatch> {
2791    definitions(editor)
2792        .into_iter()
2793        .filter(|m| m.kind == Kind::Footnote)
2794        .collect()
2795}
2796
2797/// Every definition twig resolves by label rather than by position — footnote
2798/// and link reference definitions both — or nothing when the document can't be
2799/// walked.
2800fn definitions(editor: &mut Editor) -> Vec<QueryMatch> {
2801    let Ok(mut doc) = editor.document() else {
2802        return Vec::new();
2803    };
2804    doc.definitions().unwrap_or_default()
2805}
2806
2807/// The last line of a block whose span ends at `span_end` — a thematic break,
2808/// a page break — as the two offsets the rest of the crate means by it: where
2809/// the line's text ends, and the home past it — past the newline that ends the
2810/// line, the start of the line under it (or the text's end, with no newline to
2811/// pass). A rule's row ends at that home.
2812///
2813/// Read off the span less the newline djot's span takes in, since Markdown's
2814/// stops before it. Measured from djot's span end, the home after a rule landed
2815/// past the blank line under it, on the next block's first character.
2816pub(crate) fn block_line(source: &str, span_end: usize) -> (usize, usize) {
2817    let span_end = span_end.min(source.len());
2818    let text_end = source[..span_end]
2819        .strip_suffix('\n')
2820        .map_or(span_end, |s| s.strip_suffix('\r').unwrap_or(s).len());
2821    let rest = &source[text_end..];
2822    let newline = if rest.starts_with("\r\n") {
2823        2
2824    } else {
2825        usize::from(rest.starts_with('\n'))
2826    };
2827    (text_end, text_end + newline)
2828}
2829
2830/// The label of the footnote definition starting at `start` — the `1` in
2831/// `[^1]: …`. twig gives the `footnote` node no label of its own (no `text`, no
2832/// `name`), and the bytes that spell it belong to no child node either — the
2833/// body `para` starts its *content* past them — so the source is the only place
2834/// to read it from. `None` when what's there isn't a definition after all.
2835pub(crate) fn footnote_label(source: &str, start: usize) -> Option<&str> {
2836    let rest = source.get(start..)?.strip_prefix("[^")?;
2837    let end = rest.find("]:")?;
2838    Some(&rest[..end])
2839}
2840
2841/// Where the body of the footnote definition spanning `span` sits in `source` —
2842/// everything past the `[^1]:` marker, which is the part a reader actually wants
2843/// when they follow a reference.
2844///
2845/// Source bytes, verbatim but for the whitespace trimmed off each end: a note
2846/// that says `see *later*` answers with the asterisks in. Rendering that body is
2847/// a frontend's business the same way painting a [`Role`] is, and a caller that
2848/// wants it laid out already has the definition on screen where it was written.
2849///
2850/// The trim is what makes the common case read right — `[^1]: text` has a space
2851/// after the colon that belongs to the marker, not the note, and a definition's
2852/// span runs to the newline ending it.
2853///
2854/// The span is taken at its word, which it has only been safe to do since twig
2855/// 3.1: a djot definition's span used to run *past* its own last line, through
2856/// the blank line separating it from the next block and into that block's first
2857/// byte, so `[^2a]: a note.` came back as `"a note.\n\n["` and the offsets named
2858/// the following note's rows as well as this one's — a reader asking about one
2859/// footnote was shown two. leaf measured the body itself to get around that, and
2860/// paid for it: the scan stopped at the first blank line, so a note with a second
2861/// indented paragraph lost it. Both halves go away with the fix, since a blank
2862/// line *inside* a definition was always interior to the span and still is.
2863///
2864/// A range rather than a slice because "go to note" needs the *position* as much
2865/// as the text, and it needs the position of the body specifically: a
2866/// definition's `[^1]:` marker is decoration the caret can't occupy (the rich
2867/// view draws it as `[1] ` and gives it no stop), so aiming a caret at the
2868/// definition's first byte lands it on the nearest real stop instead — which is
2869/// up in the paragraph *above* the note. The body's first byte is a stop, and is
2870/// where a reader following a reference wants to arrive anyway.
2871pub(crate) fn footnote_body_span(source: &str, span: Range<usize>) -> Option<Range<usize>> {
2872    let rest = source.get(span.clone())?.strip_prefix("[^")?;
2873    let marker = rest.find("]:")?;
2874    // `span.start` + `[^` + the label + `]:`.
2875    let after_marker = span.start + 2 + marker + 2;
2876    let raw = source.get(after_marker..span.end)?;
2877    // Written as a start plus a length so an all-whitespace body lands on an
2878    // empty range at the end rather than an inverted one.
2879    let start = after_marker + (raw.len() - raw.trim_start().len());
2880    Some(start..start + raw.trim().len())
2881}
2882
2883/// The label of the footnote *reference* spanning `span` — the `1` in `[^1]`.
2884///
2885/// The peer of [`footnote_label`] for the other half of the pair, and needed for
2886/// the same reason: a reference whose node carries neither a `content_span` nor
2887/// a `text` still spells its label plainly in the source. `None` when the bytes
2888/// aren't a reference after all.
2889pub(crate) fn footnote_reference_label(source: &str, span: Range<usize>) -> Option<&str> {
2890    let rest = source.get(span)?.strip_prefix("[^")?;
2891    let end = rest.find(']')?;
2892    Some(&rest[..end])
2893}
2894
2895/// Where a heading's *content* starts — past the `#`s and the space the rich
2896/// view hides, for an ATX heading; the block's own start for a setext one (which
2897/// has no leading marker) and for a format that spells headings some other way.
2898///
2899/// Only an empty heading needs asking: with any content at all, the row ends on
2900/// its last glyph. Bounded to the heading's own first line so a marker-less
2901/// heading can't scan into the text under it.
2902fn heading_content_start(source: &str, span: &Range<usize>) -> usize {
2903    let end = span.end.min(source.len());
2904    let Some(line) = source.get(span.start..end) else {
2905        return span.start;
2906    };
2907    let line = line.split('\n').next().unwrap_or("");
2908    let hashes = line.len() - line.trim_start_matches('#').len();
2909    if hashes == 0 {
2910        return span.start;
2911    }
2912    let after = &line[hashes..];
2913    span.start + hashes + (after.len() - after.trim_start_matches([' ', '\t']).len())
2914}
2915
2916struct Builder<'a> {
2917    nodes: &'a [FlatNode],
2918    /// The document source, consulted to place blank-line rows at the source
2919    /// offsets the caret should occupy on them (the AST drops blank lines).
2920    source: &'a str,
2921    /// The word-wrap column budget, or `None` to emit each block as a single
2922    /// unwrapped row (the frontend wraps).
2923    wrap: Option<usize>,
2924    rows: Vec<VRow>,
2925    /// Built alongside `rows`, never instead of them — see [`TableInfo`].
2926    tables: Vec<TableInfo>,
2927    /// The end offset of the last content emitted — the anchor for blank
2928    /// separator rows so the caret never snaps onto one.
2929    last_off: usize,
2930    /// The end of the last block the walk stepped over without drawing — a
2931    /// comment, which the rich view hides. `last_off` moves past it too, for the
2932    /// separators; this is kept apart so the trailing blank lines can be counted
2933    /// from it without also being counted from a code block's closing fence,
2934    /// which `last_off` likewise ends after. `0` until a hidden block is met.
2935    stepped_over: usize,
2936    /// How many rows each block image reserves, keyed by its destination — the
2937    /// frontend's per-image height, threaded in from [`crate::Doc::set_media_rows`]
2938    /// so [`Builder::block_media`] can size the placeholder without core doing any
2939    /// I/O. A destination absent from the map (or a `0`/`1` entry) reserves the
2940    /// bare one-row placeholder, which is the whole-document default and what
2941    /// every existing test — passing an empty map — still gets.
2942    surface: &'a Surface,
2943    /// The glyph a hard break renders as while the current inline run is built:
2944    /// a space in prose (a break folds into the flow the frontend wraps), but a
2945    /// newline (`\n`) inside a table cell, where a row is one source line and the
2946    /// only break it can carry is an explicit one that must show as a line of its
2947    /// own. Set around [`Builder::row_cells`] and otherwise left at `' '`.
2948    break_glyph: Cell<char>,
2949    /// Render a soft break (a bare newline inside a paragraph) as a line break
2950    /// where it was written, rather than folding it into the reflowed paragraph
2951    /// — the `LineFlow::Preserve` behaviour. A soft break emits a `'\n'` glyph
2952    /// (like a hard break in a cell), which [`Builder::emit_wrapped`] turns into
2953    /// a fresh visual row. `false` is the flowing-prose default. Inside a table
2954    /// cell (where `break_glyph` is already `'\n'`) it has no effect: a cell is
2955    /// one line and folds its own soft breaks regardless.
2956    preserve_soft: bool,
2957    /// The source byte range of the one line that should render its markup
2958    /// *raw* — the caret's line under `MarkupMode::Full` (see
2959    /// [`crate::Doc::reveal_line`]). `None` in every other mode and view, which
2960    /// is the delimiters-always-hidden behaviour every build had before the
2961    /// preference existed.
2962    ///
2963    /// Read only by [`Builder::revealed`], which every delimiter-bearing arm of
2964    /// [`Builder::inline`] consults. A range rather than a bare caret offset
2965    /// because the decision is per-*node*, not per-caret: a node is revealed
2966    /// when its span meets this line, so `*em*` shows both its asterisks even
2967    /// with the caret at one end of it.
2968    reveal: Option<Reveal>,
2969    /// The content ends of the hidden marks rendered since the last row was
2970    /// pushed — recorded as the inline walk meets each mark, and drained onto
2971    /// the rows as they are emitted (see [`Builder::take_mark_ends`]). A cell
2972    /// rather than a `&mut`, for the reason `break_glyph` is: the inline walk
2973    /// borrows the builder shared.
2974    pending_mark_ends: RefCell<Vec<usize>>,
2975    /// The inline atoms rendered since the last row was pushed, keyed by the
2976    /// formula's start offset — the offset the atom glyph carries, which is
2977    /// how [`Builder::take_math`] pairs each with its glyph once the wrap has
2978    /// decided which row it landed on. Drained the way `pending_mark_ends` is.
2979    pending_math: RefCell<Vec<(usize, MathMark)>>,
2980    /// Whether this walk met a formula at all, atom, block, or revealed — the
2981    /// fact [`BlockCache`] keeps per block so [`crate::Doc::reveal_line`] can
2982    /// tell whether the caret's line has anything to reveal without walking.
2983    saw_math: Cell<bool>,
2984    /// The presentation vocabulary in force at the block being walked — the
2985    /// keys the `div`s around it carry, folded together with the nearest
2986    /// winning, and [`Presentation::default`] at the top level.
2987    ///
2988    /// Saved and restored around each `div` in [`Builder::block`], so a block
2989    /// reads its own attributes over whatever its containers said and nothing
2990    /// leaks sideways to the block after it. It is per-*build* state rather
2991    /// than a parameter because every one of the dozen call sites of `block`
2992    /// would otherwise thread a value none of them care about.
2993    presentation: Presentation,
2994    /// The named families this walk has met, by the id its glyphs carry — see
2995    /// [`VisualMap::faces`]. A `RefCell` for [`pending_mark_ends`]'s reason:
2996    /// the inline walk borrows the builder shared, and a span's `data-font` is
2997    /// read from inside it.
2998    ///
2999    /// [`pending_mark_ends`]: Builder::pending_mark_ends
3000    faces: RefCell<FaceTable>,
3001}
3002
3003/// The six presentation keys as the walker carries them down a block tree —
3004/// the two that are the block's ([`Align`], [`LineHeight`]) and the three that
3005/// are a run's but may be written on the block ([`FontSize`], [`FaceRef`],
3006/// [`TextColor`]).
3007///
3008/// `Copy` and five `Option`s, because folding is the whole of what it does:
3009/// [`under`](Presentation::under) reads a container's attributes over an
3010/// existing set and a key the container does not name keeps the value it had.
3011/// That is the "nearest wins" rule stated once, rather than at each of the
3012/// three levels a key can be written at. A name and a value fold alike: the
3013/// nearer node wins whichever of the two forms either of them wrote.
3014#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3015struct Presentation {
3016    align: Option<Align>,
3017    line_height: Option<LineHeight>,
3018    size: Option<FontSize>,
3019    font: Option<FaceRef>,
3020    color: Option<TextColor>,
3021}
3022
3023impl Presentation {
3024    /// This set with whatever `attrs` names written over it — the nearer node's
3025    /// answer where it has one, the outer node's where it hasn't.
3026    ///
3027    /// `faces` is the build's intern table, which a named family is recorded in
3028    /// on the way past: the glyph carries the id and the table carries the
3029    /// string. Shared rather than `&mut` because the inline walk this feeds
3030    /// borrows the builder shared, the way `pending_mark_ends` does.
3031    fn under(self, attrs: &[(String, Option<String>)], faces: &RefCell<FaceTable>) -> Self {
3032        Self {
3033            align: Align::from_attrs(attrs).or(self.align),
3034            line_height: LineHeight::from_attrs(attrs).or(self.line_height),
3035            size: FontSize::from_attrs(attrs).or(self.size),
3036            font: faces.borrow_mut().face_from_attrs(attrs).or(self.font),
3037            color: TextColor::from_attrs(attrs).or(self.color),
3038        }
3039    }
3040
3041    /// `base` carrying the three run-level keys — the style a block's glyphs
3042    /// start from, which an attributed span inside it then writes over.
3043    fn over(self, base: Style) -> Style {
3044        base.size(self.size).font(self.font).color(self.color)
3045    }
3046}
3047
3048impl Builder<'_> {
3049    /// Note that the mark `id` closes with a hidden delimiter, so its content
3050    /// end is a caret home — unless the mark is empty, where the end is the
3051    /// start and there is nothing to extend.
3052    fn note_mark_end(&self, id: usize) {
3053        let node = &self.nodes[id];
3054        if let Some(content) = &node.content_span
3055            && content.end < node.span.end
3056            && !content.is_empty()
3057        {
3058            self.pending_mark_ends.borrow_mut().push(content.end);
3059        }
3060    }
3061
3062    /// The pending mark ends at or before `end_src`, for the row ending there
3063    /// — every mark rendered so far that closes on it. A mark's end never
3064    /// exceeds the end of the row its last glyph is on, so the leftovers are
3065    /// those of rows still to come.
3066    fn take_mark_ends(&self, end_src: usize) -> Vec<usize> {
3067        let mut pending = self.pending_mark_ends.borrow_mut();
3068        let (taken, kept): (Vec<usize>, Vec<usize>) =
3069            pending.drain(..).partition(|&o| o <= end_src);
3070        *pending = kept;
3071        taken
3072    }
3073
3074    /// The pending inline atoms whose glyph is on the row `glyphs` is about
3075    /// to become — each paired with the index of the [`Role::Math`] glyph
3076    /// carrying its offset, in glyph order. An atom whose glyph landed on an
3077    /// earlier row was taken then; one on a later row is left for it. The
3078    /// peer of [`take_mark_ends`](Self::take_mark_ends), and why an atom is
3079    /// keyed by offset: the wrap decides the row, and the offset is what the
3080    /// glyph still carries once it has.
3081    fn take_math(&self, glyphs: &[Glyph]) -> Vec<MathMark> {
3082        let mut pending = self.pending_math.borrow_mut();
3083        if pending.is_empty() {
3084            return Vec::new();
3085        }
3086        let mut out = Vec::new();
3087        for (i, g) in glyphs.iter().enumerate() {
3088            if g.style.role != Role::Math || !g.stop {
3089                continue;
3090            }
3091            if let Some(at) = pending.iter().position(|(src, _)| *src == g.src) {
3092                let (_, mut mark) = pending.remove(at);
3093                mark.glyph = Some(i);
3094                out.push(mark);
3095            }
3096        }
3097        out
3098    }
3099    /// Whether `span` belongs to the line that is showing its raw markup. True
3100    /// only when a reveal line is set *for markup* (`MarkupMode::Full`) and the
3101    /// two ranges actually meet — see [`Reveal::meets`] for what meeting is.
3102    fn revealed(&self, span: &Range<usize>) -> bool {
3103        self.reveal
3104            .as_ref()
3105            .is_some_and(|r| r.markup && r.meets(span))
3106    }
3107
3108    /// Whether a formula at `span` shows its TeX rather than its picture: it
3109    /// meets the reveal line, in *any* mode. A formula's content is its source
3110    /// and not its picture, so for it the choice is not between a clean
3111    /// surface and a raw one but between editable and not — which is why this
3112    /// does not read [`Reveal::markup`] the way [`revealed`](Self::revealed)
3113    /// does.
3114    fn math_revealed(&self, span: &Range<usize>) -> bool {
3115        self.reveal.as_ref().is_some_and(|r| r.meets(span))
3116    }
3117
3118    /// The `(opening, closing)` source byte ranges of a node's delimiters — the
3119    /// bytes its `span` holds that its `content_span` doesn't.
3120    ///
3121    /// This is how *every* inline delimiter is recovered, rather than a table of
3122    /// spellings per kind: twig gives `*em*` a span of `13..17` and a content
3123    /// span of `14..16`, so the gaps at each end are the delimiters, whatever
3124    /// they happen to be. That matters because one kind has many spellings —
3125    /// `*em*` and `_em_` are both emphasis, `` `x` `` and ``` ``x`` ``` both
3126    /// verbatim — and re-deriving the text from the source is the only way to
3127    /// show back what the author actually typed. It also gets a link's
3128    /// asymmetric `[` / `](dest)` right for free.
3129    ///
3130    /// `None` when the node has no content span, or when content and span
3131    /// coincide (nothing was elided, so there is nothing to reveal).
3132    fn delims(&self, id: usize) -> Option<(Range<usize>, Range<usize>)> {
3133        let node = &self.nodes[id];
3134        let content = node.content_span.clone()?;
3135        let span = node.span.clone();
3136        // A content span that escapes its own node's span means the two are
3137        // describing different things; reveal nothing rather than slice wildly.
3138        if content.start < span.start || content.end > span.end {
3139            return None;
3140        }
3141        let (open, close) = (span.start..content.start, content.end..span.end);
3142        // A delimiter that spans a newline isn't this line's to reveal — a setext
3143        // heading's `\n=====` underline is the case that arises in practice. It
3144        // would also inject a `'\n'` glyph, which `emit_wrapped` reads as a hard
3145        // row break, so the row would split where the author wrote no break.
3146        let multiline =
3147            |r: &Range<usize>| self.source.get(r.clone()).is_some_and(|s| s.contains('\n'));
3148        if multiline(&open) || multiline(&close) {
3149            return None;
3150        }
3151        (!open.is_empty() || !close.is_empty()).then_some((open, close))
3152    }
3153
3154    /// Emit the source bytes of `range` as revealed markup — real glyphs, each
3155    /// mapped to its own source byte and each a caret stop, so a delimiter shown
3156    /// is a delimiter that can be selected, edited and deleted like any other
3157    /// text. Styled [`Role::Delimiter`] on top of the run's own style, which is
3158    /// how a frontend tells scaffolding from prose and dims it.
3159    ///
3160    /// Deliberately *not* [`push_escaped_text`]: this is raw source, not parsed
3161    /// text, so there is no escape-driven drift between the two to correct.
3162    fn push_delim(&self, out: &mut Vec<Glyph>, range: &Range<usize>, base: Style) {
3163        let Some(text) = self.source.get(range.clone()) else {
3164            return;
3165        };
3166        push_text(out, text, range.start, base.role(Role::Delimiter));
3167    }
3168
3169    /// Render an inline node's children wrapped in its raw delimiters when the
3170    /// node is on the revealed line, and bare (delimiters resolved away) when it
3171    /// isn't — the shared body of every delimiter-bearing arm of
3172    /// [`inline`](Self::inline).
3173    ///
3174    /// `style` is the resolved styling the content still gets in *both* modes:
3175    /// revealing `*em*` shows the asterisks *and* keeps the text italic, the
3176    /// live-preview behaviour. Showing the markup is not the same as turning the
3177    /// rendering off — that is what [`crate::View::Source`] is for.
3178    fn inline_delimited(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
3179        let show = self
3180            .revealed(&self.nodes[id].span)
3181            .then(|| self.delims(id))
3182            .flatten();
3183        if let Some((open, _)) = &show {
3184            self.push_delim(out, open, style);
3185        }
3186        self.recurse(id, style, out);
3187        match &show {
3188            Some((_, close)) => self.push_delim(out, close, style),
3189            // Hidden, so the content's end has no glyph after it: give the
3190            // caret its home there.
3191            None => self.note_mark_end(id),
3192        }
3193    }
3194
3195    /// A verbatim span — or a formula drawn as its TeX — in the code style:
3196    /// its text at its content's offset, bracketed by its raw delimiters when
3197    /// `show` says the line is revealed and by nothing (plus the caret's home
3198    /// at the content's end) when it isn't.
3199    ///
3200    /// Not [`inline_delimited`](Self::inline_delimited): verbatim has no child
3201    /// nodes to recurse into — its content is its own `text` — so the fences
3202    /// bracket a [`push_text`] instead. The fences themselves keep
3203    /// `Role::Code`'s sibling treatment via [`push_delim`]'s role override.
3204    ///
3205    /// [`push_delim`]: Self::push_delim
3206    fn inline_verbatim(&self, id: usize, base: Style, out: &mut Vec<Glyph>, show: bool) {
3207        let node = &self.nodes[id];
3208        // The interior begins at `content_span.start` — past however many
3209        // backticks the fence used, which `span.start + 1` only guessed right
3210        // for a single one. Fall back to that guess if it's absent.
3211        let at = node
3212            .content_span
3213            .as_ref()
3214            .map_or(node.span.start + 1, |c| c.start);
3215        let style = base.role(Role::Code);
3216        let show = show.then(|| self.delims(id)).flatten();
3217        if let Some((open, _)) = &show {
3218            self.push_delim(out, open, style);
3219        }
3220        push_text(out, node.text.as_deref().unwrap_or(""), at, style);
3221        match &show {
3222            Some((_, close)) => self.push_delim(out, close, style),
3223            None => self.note_mark_end(id),
3224        }
3225    }
3226
3227    fn children(&self, id: usize) -> Vec<usize> {
3228        let mut out = Vec::new();
3229        let mut c = self.nodes[id].first_child;
3230        while let Some(cid) = c {
3231            out.push(cid.0 as usize);
3232            c = self.nodes[cid.0 as usize].next_sibling;
3233        }
3234        out
3235    }
3236
3237    /// Render a node's block children, a blank separator between each. `tight`
3238    /// suppresses the *fabricated* separator between adjacent children that share
3239    /// a source line boundary — a tight list item and the sub-list nested in it —
3240    /// while a real blank source line between them still opens a gap.
3241    fn blocks(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph], tight: bool) {
3242        // Frontmatter (a leading `metadata` block) is document metadata, not
3243        // prose: hide it entirely in the rich-text view. Skipping it here means
3244        // no phantom blank rows for its lines and no separator before the first
3245        // real block — the document opens straight into its content.
3246        let kids: Vec<usize> = self
3247            .children(id)
3248            .into_iter()
3249            .filter(|&c| self.nodes[c].kind != Kind::Metadata)
3250            .collect();
3251        let mut above: Option<BlockClass> = None;
3252        for child in kids {
3253            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
3254            let before_sep = self.rows.len();
3255            if let Some(above) = above {
3256                self.emit_separators_before(
3257                    self.nodes[child].span.start,
3258                    pc,
3259                    !tight,
3260                    Boundary { above, below },
3261                );
3262            }
3263            // The first *drawn* child wears the first-row prefix (a bullet, a
3264            // footnote label), not the first child: a comment opening a list
3265            // item draws nothing, and the bullet belongs to what follows it.
3266            let first = if above.is_none() { pf } else { pc };
3267            if self.block_or_hidden(child, before_sep, first, pc) {
3268                above = Some(below);
3269            }
3270        }
3271    }
3272
3273    /// Render `child` after the separator [`Builder::emit_separators_before`]
3274    /// spelled for it from row `before_sep` on, and say whether it drew
3275    /// anything.
3276    ///
3277    /// A block that draws no rows — an HTML comment, which the rich view hides
3278    /// the way it hides frontmatter — is still *there* in the source, and the
3279    /// walk has to step over it: `last_off` moves past it so the next separator
3280    /// counts the blank lines from its end, not from wherever the last drawn
3281    /// block stopped. Left where it was, the separator counted every line of the
3282    /// comment as a blank row; and the cached path, whose per-block builder
3283    /// starts at offset 0, handed back a `last_off` of 0 and counted every line
3284    /// of the *document* — one phantom blank row per source line, once per
3285    /// comment. The separator drawn for it is taken back too, so a hidden block
3286    /// leaves no gap of its own: what stands either side of it meets across one
3287    /// boundary, as if the comment were not there.
3288    fn block_or_hidden(
3289        &mut self,
3290        child: usize,
3291        before_sep: usize,
3292        pf: &[Glyph],
3293        pc: &[Glyph],
3294    ) -> bool {
3295        let after_sep = self.rows.len();
3296        self.block(child, pf, pc);
3297        if self.rows.len() > after_sep {
3298            return true;
3299        }
3300        self.rows.truncate(before_sep);
3301        let end = self.nodes[child].span.end;
3302        self.last_off = self.last_off.max(end);
3303        self.stepped_over = self.stepped_over.max(end);
3304        false
3305    }
3306
3307    /// Render an explicit, ordered list of top-level blocks — [`Builder::blocks`]
3308    /// for a walk that isn't "the children of one node". The document's top level
3309    /// no longer is: a footnote definition is a root beside `doc`, not under it,
3310    /// and [`top_level`] merges it into this list by source position.
3311    ///
3312    /// The separator between blocks is spelled by the same
3313    /// [`Builder::emit_separators_before`] the incremental top-level walk in
3314    /// [`build_cached`] uses, so the two paths can't drift on how a boundary
3315    /// looks.
3316    ///
3317    /// Returns the class of the last block that drew anything — what the
3318    /// trailing blank lines close — or `None` when nothing did.
3319    fn top_blocks(&mut self, ids: &[usize], hidden_end: usize) -> Option<BlockClass> {
3320        let mut above: Option<BlockClass> = None;
3321        for &child in ids {
3322            let below = BlockClass::from_node_kind(&self.nodes[child].kind);
3323            let before_sep = self.rows.len();
3324            if let Some(above) = above {
3325                self.emit_separators_before(
3326                    self.nodes[child].span.start,
3327                    &[],
3328                    true,
3329                    Boundary { above, below },
3330                );
3331            } else {
3332                let from = self.leading_from(hidden_end);
3333                self.emit_leading_blank_lines(from, self.nodes[child].span.start, below);
3334            }
3335            if self.block_or_hidden(child, before_sep, &[], &[]) {
3336                above = Some(below);
3337            }
3338        }
3339        above
3340    }
3341
3342    /// Emit the blank separator row(s) that sit between a block ending at the
3343    /// current `last_off` and the next block starting at `next_start`, wearing
3344    /// the continuation prefix `pc`. Shared by [`Builder::blocks`] and the
3345    /// incremental top-level walk so the two can't drift on how a boundary is
3346    /// spelled.
3347    ///
3348    /// The blank line(s) between two blocks are real caret stops, each needing
3349    /// its *own* source offset — one strictly past the previous block's content,
3350    /// else it collides with that block's last row and `pos_of_offset`
3351    /// (first-match-wins) would resolve the caret onto the wrong row, pinning
3352    /// downward motion there.
3353    ///
3354    /// One row *per* blank source line, not a single collapsed separator: an
3355    /// empty paragraph opened between two blocks (Enter in the gap,
3356    /// `…\n\n\n\n…`) must be a navigable empty row, not vanish — else the caret
3357    /// in it snaps onto the *next* block's start and Enter looks like it did
3358    /// nothing.
3359    fn emit_separators_before(
3360        &mut self,
3361        next_start: usize,
3362        pc: &[Glyph],
3363        synthetic: bool,
3364        boundary: Boundary,
3365    ) {
3366        let mut offs = self.blank_rows_between(self.last_off, next_start);
3367        // Under a `</div>` the first blank line is the one Markdown needs to
3368        // end the div, not a line the author opened. Preserve flow drew it as
3369        // one, and Backspace there took it and glued the block below onto the
3370        // closing tag, as raw HTML.
3371        if self.preserve_soft && offs.first().is_some_and(|&o| self.closes_div_above(o)) {
3372            offs.remove(0);
3373            if offs.is_empty() {
3374                return;
3375            }
3376        }
3377        if offs.is_empty() {
3378            if !synthetic {
3379                // A tight list item's own text sits directly above the sub-list
3380                // nested in it — no fabricated gap. The "breathe" row belongs
3381                // between free-standing blocks, not between an item and its
3382                // child list, which the source writes on the very next line. A
3383                // real blank source line (a loose list) still lands a gap below,
3384                // because `blank_rows_between` found it and we never reach here.
3385                return;
3386            }
3387            // A tight gap with no blank line (e.g. a heading directly above its
3388            // text): keep the one conventional separator row so blocks still
3389            // breathe, as they always have.
3390            offs.push(self.blank_line_offset(self.last_off, next_start));
3391        }
3392        let last = offs.len() - 1;
3393        for (k, end_src) in offs.into_iter().enumerate() {
3394            // Only the drawn-only rows carry the boundary: the navigable blank
3395            // lines between them (and every blank line under preserve-soft flow)
3396            // are somewhere text can go, not a gap between blocks, and a frontend
3397            // that shrank one would be shrinking a line the author is typing on.
3398            let drawn = !self.preserve_soft && (k == 0 || k == last);
3399            // The blank line a boundary is *drawn* with isn't a place text can
3400            // go. The first one closes the block above and the last one opens the
3401            // block below — with a single blank line, the usual case, doing both
3402            // at once. Typing on either just continues the paragraph it abuts,
3403            // since the blank line it would need to be a paragraph of its own is
3404            // the very line being typed on. So they're a gap, like a table's
3405            // border: drawn, clickable, never a caret's home.
3406            //
3407            // The lines *between* them are the real ones. That's what Enter
3408            // opens: it inserts a paragraph break (`\n\n`), which leaves a blank
3409            // line spare on each side and the caret on the navigable line
3410            // between them.
3411            //
3412            // Preserve flow is the exception: there a bare `\n` is a visible line
3413            // break the author edits directly, so a lone blank line *is* a caret
3414            // home — typing on it makes the soft break the mode exists to show,
3415            // and Enter at a line's end lands the caret on exactly this row. So no
3416            // separator is drawn-only; every blank line is navigable.
3417            self.rows.push(VRow {
3418                glyphs: pc.to_vec(),
3419                end_src,
3420                decoration: drawn,
3421                code: false,
3422                code_lang: None,
3423                directive: false,
3424                directive_label: None,
3425                media: None,
3426                task: None,
3427                leaf_directive: None,
3428                heading: None,
3429                // A line the author can type on is a line of the block
3430                // around it, and keeps its spacing and alignment.
3431                align: (!drawn).then_some(self.presentation.align).flatten(),
3432                line_height: (!drawn).then_some(self.presentation.line_height).flatten(),
3433                boundary: drawn.then_some(boundary),
3434                mark_ends: Vec::new(),
3435                math: Vec::new(),
3436            });
3437        }
3438    }
3439
3440    /// The blank lines above the first block that draws anything, from `from`
3441    /// — the first line past any hidden frontmatter or comment — to the line
3442    /// holding `next_start`. [`Builder::emit_trailing_blank_lines`] turned
3443    /// upside down: nothing above needs a gap, so every line is an empty
3444    /// paragraph but the last, which is the gap that opens the block below.
3445    ///
3446    /// One blank line is only that gap, and draws nothing, which keeps the
3447    /// usual line under frontmatter out of sight. Two are the empty paragraph
3448    /// Enter opens at the first block's start (`\n\nHello`), which drew
3449    /// nothing either: the caret stayed with the text and the text stayed put.
3450    /// Preserve flow draws every line, as it does between blocks, but the one
3451    /// under frontmatter, which is the frontmatter's and not the author's.
3452    fn emit_leading_blank_lines(&mut self, from: usize, next_start: usize, below: BlockClass) {
3453        let next_line_start = self.source[..next_start].rfind('\n').map_or(0, |p| p + 1);
3454        let mut offs = Vec::new();
3455        let mut start = from;
3456        while start < next_line_start {
3457            offs.push(start);
3458            match self.source[start..next_line_start].find('\n') {
3459                Some(k) => start += k + 1,
3460                None => break,
3461            }
3462        }
3463        if self.preserve_soft {
3464            if from > 0 && !offs.is_empty() {
3465                offs.remove(0);
3466            }
3467        } else if offs.len() < 2 {
3468            return;
3469        }
3470        let last = offs.len().saturating_sub(1);
3471        for (k, end_src) in offs.into_iter().enumerate() {
3472            let drawn = !self.preserve_soft && k == last;
3473            self.rows.push(VRow {
3474                glyphs: Vec::new(),
3475                end_src,
3476                decoration: drawn,
3477                code: false,
3478                code_lang: None,
3479                directive: false,
3480                directive_label: None,
3481                media: None,
3482                task: None,
3483                leaf_directive: None,
3484                heading: None,
3485                align: None,
3486                line_height: None,
3487                boundary: drawn.then_some(Boundary {
3488                    above: BlockClass::Paragraph,
3489                    below,
3490                }),
3491                mark_ends: Vec::new(),
3492                math: Vec::new(),
3493            });
3494        }
3495    }
3496
3497    /// Whether the line above the one starting at `line` is a `</div>`.
3498    fn closes_div_above(&self, line: usize) -> bool {
3499        let Some(above) = self.source[..line].strip_suffix('\n') else {
3500            return false;
3501        };
3502        let above = above.strip_suffix('\r').unwrap_or(above);
3503        let start = above.rfind('\n').map_or(0, |p| p + 1);
3504        above[start..].trim() == "</div>"
3505    }
3506
3507    /// The blank lines between a `<div>`'s last block and its closing tag,
3508    /// drawn inside the div, as the lines between two of its blocks are.
3509    ///
3510    /// One blank line is the one Markdown needs before `</div>`, and two are
3511    /// that and the gap, so neither draws (in Preserve flow, which has no
3512    /// gap, the second does). A third is the empty paragraph
3513    /// Enter opens at the end of the div's last block — the end of a line
3514    /// with a line height or an alignment on it — which drew nothing: the
3515    /// key looked dead, and each press left another line nobody could see.
3516    fn emit_div_trailing_lines(&mut self, id: usize, pc: &[Glyph]) {
3517        let Some(&last) = self.children(id).last() else {
3518            return;
3519        };
3520        if self.rows.is_empty() {
3521            return;
3522        }
3523        let end = self.nodes[id].span.end.min(self.source.len());
3524        let from = block_line(self.source, self.last_off).1;
3525        if from >= end {
3526            return;
3527        }
3528        let Some(close) = self.source[from..end].rfind("</div>") else {
3529            return;
3530        };
3531        let close_line = self.source[..from + close].rfind('\n').map_or(0, |p| p + 1);
3532        let mut offs = Vec::new();
3533        let mut start = from;
3534        while start < close_line {
3535            if !self.source[start..close_line]
3536                .lines()
3537                .next()
3538                .unwrap_or("")
3539                .trim()
3540                .is_empty()
3541            {
3542                return;
3543            }
3544            offs.push(start);
3545            match self.source[start..close_line].find('\n') {
3546                Some(k) => start += k + 1,
3547                None => break,
3548            }
3549        }
3550        // Preserve flow draws every blank line but the one `</div>` needs.
3551        if offs.len() < if self.preserve_soft { 2 } else { 3 } {
3552            return;
3553        }
3554        offs.pop();
3555        let above = BlockClass::from_node_kind(&self.nodes[last].kind);
3556        for (k, end_src) in offs.into_iter().enumerate() {
3557            let drawn = !self.preserve_soft && k == 0;
3558            self.rows.push(VRow {
3559                glyphs: pc.to_vec(),
3560                end_src,
3561                decoration: drawn,
3562                code: false,
3563                code_lang: None,
3564                directive: false,
3565                directive_label: None,
3566                media: None,
3567                task: None,
3568                leaf_directive: None,
3569                heading: None,
3570                align: (!drawn).then_some(self.presentation.align).flatten(),
3571                line_height: (!drawn).then_some(self.presentation.line_height).flatten(),
3572                boundary: drawn.then_some(Boundary {
3573                    above,
3574                    below: BlockClass::Paragraph,
3575                }),
3576                mark_ends: Vec::new(),
3577                math: Vec::new(),
3578            });
3579        }
3580    }
3581
3582    /// Where the lines above the first drawn block begin: past the hidden
3583    /// frontmatter, or past the line of the last hidden block the walk
3584    /// stepped over, whichever is later.
3585    fn leading_from(&self, hidden_end: usize) -> usize {
3586        if self.last_off == 0 {
3587            return hidden_end;
3588        }
3589        block_line(self.source, self.last_off).1.max(hidden_end)
3590    }
3591
3592    /// One block, drawn under whatever presentation the containers around it
3593    /// impose.
3594    ///
3595    /// A container named `div` with `Element` origin is transparent already —
3596    /// its children draw as themselves — and it now also *contributes* its
3597    /// vocabulary keys to every block it holds. That is the reading side of
3598    /// twig's own rule for where a Markdown block's attributes live: there is
3599    /// no attribute syntax to put on the paragraph, so `set_block_attrs` writes
3600    /// a `<div …>` around it, and reading one back has to look through the div.
3601    /// `<div class="center">` around three paragraphs centres all three, which
3602    /// is what the author of that HTML meant, and around one is the sole-child
3603    /// shape twig writes.
3604    ///
3605    /// Saved and restored rather than pushed onto a stack, so a nested div
3606    /// reads its own keys over its parent's and the block *after* the div is
3607    /// unaffected.
3608    fn block(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
3609        if element_tag(&self.nodes[id]) == Some("div") {
3610            let saved = self.presentation;
3611            self.presentation = saved.under(&self.nodes[id].attrs, &self.faces);
3612            self.block_kind(id, pf, pc);
3613            self.emit_div_trailing_lines(id, pc);
3614            self.presentation = saved;
3615            // Step the walk past the closing `</div>`, as the fenced-div arm
3616            // below anchors past its `:::`. The tag sits on a line of its own
3617            // after the last child and the blank line under it, and the rich
3618            // view draws nothing for it — so left where the last child ended,
3619            // the separator logic read the tag's line as a blank line between
3620            // the div and the block below, and drew a navigable empty row there
3621            // that the author never opened and Backspace could not close; and
3622            // at the end of the document the trailing count read it as an empty
3623            // paragraph the author had left. It is hidden markup the walk steps
3624            // over, which is what `stepped_over` records, so both counts start
3625            // past it.
3626            let end = self.nodes[id].span.end;
3627            self.last_off = self.last_off.max(end);
3628            self.stepped_over = self.stepped_over.max(end);
3629            return;
3630        }
3631        self.block_kind(id, pf, pc);
3632    }
3633
3634    fn block_kind(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
3635        let node = &self.nodes[id];
3636        match node.kind.as_str() {
3637            "doc" | "section" => self.blocks(id, pf, pc, false),
3638            "heading" => {
3639                // A heading whose only visible content is a single image — a
3640                // banner set in an `<h1>` (`<h1><picture><img></picture></h1>`),
3641                // or `# ![](banner.png)` — is a block picture, not text. Render
3642                // it as one; anything with real heading text falls through.
3643                if let Some((m, kind)) = self.media_only(id) {
3644                    self.block_media(m, kind, id, pf);
3645                    return;
3646                }
3647                let level = node.level.unwrap_or(1);
3648                // A `data-size` on a heading scales the *heading's* ramp, not
3649                // the body's — the role and the step compose rather than
3650                // compete, which is the same thing a colour does to a link.
3651                let pres = self.presentation.under(&node.attrs, &self.faces);
3652                let style = pres.over(heading_style(level));
3653                let mut glyphs = Vec::new();
3654                // On the revealed line the `# ` comes back as real, editable
3655                // text in front of the heading. Only the opening marker: a
3656                // closing `#`-run (`## title ##`) is covered by the same
3657                // `delims` pair, and a setext underline is excluded there for
3658                // being on another line entirely.
3659                if let Some((open, close)) =
3660                    self.revealed(&node.span).then(|| self.delims(id)).flatten()
3661                {
3662                    self.push_delim(&mut glyphs, &open, style);
3663                    glyphs.extend(self.inline_children_with_trailing(id, style));
3664                    self.push_delim(&mut glyphs, &close, style);
3665                } else {
3666                    glyphs = self.inline_children_with_trailing(id, style);
3667                }
3668                // An *empty* heading — `# ` with nothing typed after it, which is
3669                // what the toolbar's H1 leaves on a blank line — has no glyph for
3670                // its row to end on, so the fallback below is the row's whole
3671                // extent: its only caret stop, and the offset every row after it
3672                // is measured from. The block's start is the wrong answer for
3673                // both, because it sits *in front of* the `# ` the rich view
3674                // hides: the caret drew (and typed) before the hashes, and the
3675                // rows below inherited an offset short by the marker's length,
3676                // which put the caret on one of them the moment the heading grew
3677                // text. Its content's start is where the caret belongs.
3678                let home = heading_content_start(self.source, &node.span);
3679                let first = self.rows.len();
3680                self.emit_wrapped(glyphs, home, pf, pc);
3681                // Stamp the level on every row the heading just emitted — a
3682                // wrapped heading's continuation rows as much as its first, and
3683                // an empty one's single glyphless row, which is the whole point
3684                // (see [`VRow::heading`]).
3685                for row in &mut self.rows[first..] {
3686                    row.heading = Some(level.min(255) as u8);
3687                    row.align = pres.align;
3688                    row.line_height = pres.line_height;
3689                }
3690            }
3691            "block_quote" => {
3692                let (start, end) = (node.span.start, node.span.end);
3693                let gutter = synth("│ ", Role::QuoteGutter, start);
3694                let f = concat(pf, &gutter);
3695                let c = concat(pc, &gutter);
3696                // A childless quote — a bare `> ` on an otherwise blank line,
3697                // which is what the toolbar's Quote button leaves there — has no
3698                // inner block to carry the gutter or a caret home, so `blocks`
3699                // emitted *nothing at all*: the quote didn't merely draw
3700                // unstyled, it disappeared, and a document that was only `> `
3701                // rendered zero rows with the caret nowhere to stand. Emit the
3702                // gutter row itself, ending just past the marker, exactly as an
3703                // empty `list_item` emits its bare bullet.
3704                if self.children(id).is_empty() {
3705                    self.push_row_at(f, end.min(self.source.len()));
3706                } else {
3707                    self.blocks(id, &f, &c, false);
3708                    self.emit_quote_trailing_lines(&c, end);
3709                }
3710            }
3711            // A generic `:::name{.class}` fenced-div container (twig's
3712            // `directive`, container form). Core is agnostic of `name` — it's
3713            // the host app's vocabulary (diaryx's `vis` for audience
3714            // visibility, say) and isn't available here regardless: twig only
3715            // threads an `element`'s tag name through `FlatNode::name`, not a
3716            // directive's own identifier. Every row gets marked `directive` (a
3717            // frontend draws a tinted panel around each maximal run, the
3718            // `code`/`code_block` recipe) and the first row carries a label —
3719            // the way a code fence's language rides only its first row.
3720            //
3721            // The label reads BOTH attribute conventions diaryx content
3722            // actually uses: twig's own dot-prefixed classes (`{.public
3723            // .family}`, one combined `class` attr) and bare pandoc-style
3724            // words with no leading dot (`{public family}` — the syntax
3725            // `diaryx_core::visibility`'s hand-rolled publish-time filter and
3726            // apps/web's directive serializer both write; twig parses each
3727            // bare word as its own attribute with an empty value, per
3728            // `languages/markdown/attributes.zig`). Reading only `.class`
3729            // would leave every *existing* diaryx `:::vis{...}` block
3730            // unlabeled.
3731            // Only the *container* form is the panel below. A `text` directive
3732            // is inline and never reaches the block walker (see `is_inline`); a
3733            // `leaf` one is a standalone block with no body, drawn as a
3734            // placeholder the way an image is.
3735            "container"
3736                if container_is_directive(node)
3737                    && node.directive_form == Some(DirectiveForm::Leaf) =>
3738            {
3739                self.block_directive(id, pf);
3740            }
3741            // HTML and AsciiDoc spell `insert_directive`'s page break in ways
3742            // of their own — `<page-break></page-break>`, an *element* with
3743            // no form at all, and `<<<`, a directive with none — so neither
3744            // meets the arm above. Both are named `page-break` and empty, and
3745            // both draw the same placeholder, for the same reason djot's
3746            // fence below does: a frontend that paginates on the mark must
3747            // not be able to tell which format the file is in. Narrow to the
3748            // one name: an arbitrary empty custom element is not a leaf
3749            // directive.
3750            "container"
3751                if node.name.as_deref() == Some(crate::doc::PAGE_BREAK)
3752                    && node.directive_form.is_none()
3753                    && node.origin.is_some()
3754                    && self.children(id).is_empty() =>
3755            {
3756                self.block_directive(id, pf);
3757            }
3758            // djot has no *leaf* directive form. `insert_directive` spells the
3759            // same document as an empty `::: page-break` fence — a container
3760            // with nothing in it — and the name comes back as the fence's one
3761            // class rather than as the node's name, because djot's div is
3762            // anonymous. Draw it as the placeholder Markdown's `::page-break`
3763            // gets, so a frontend that paginates on a `page-break`
3764            // [`DirectiveMark`] cannot tell which format the file is in.
3765            //
3766            // Narrow on purpose: only an *anonymous* empty fence. A Markdown
3767            // `:::note` with nothing in it keeps the reading it has, because
3768            // its name is its own and nothing about it says "a block with no
3769            // body" the way djot's spelling of a leaf directive does.
3770            "container"
3771                if container_is_directive(node)
3772                    && node.directive_form == Some(DirectiveForm::Container)
3773                    && node.name.as_deref().unwrap_or_default().is_empty()
3774                    && self.children(id).is_empty()
3775                    && !leaf_directive_identity(node).0.is_empty() =>
3776            {
3777                self.block_directive(id, pf);
3778            }
3779            "container" if container_is_directive(node) => {
3780                let label = directive_attr_label(&node.attrs);
3781                let start_row = self.rows.len();
3782                self.blocks(id, pf, pc, false);
3783                for (i, row) in self.rows[start_row..].iter_mut().enumerate() {
3784                    row.directive = true;
3785                    if i == 0 {
3786                        row.directive_label = label.clone();
3787                    }
3788                }
3789                // Anchor the block's end past its closing `:::` fence, exactly as
3790                // the code-block arm anchors past its ```` ``` ````. A container's
3791                // last content row ends at its last *child*, before the fence and
3792                // the blank line under it, so the separator logic counted the
3793                // fence line as a blank row of its own and drew a second boundary
3794                // — one gap's worth of margin twice, under every fenced div.
3795                self.last_off = node.span.end;
3796            }
3797            "bullet_list" | "ordered_list" | "task_list" => {
3798                let ordered = node.kind == Kind::OrderedList;
3799                let mut item_no = 0usize;
3800                let kids = self.children(id);
3801                for (i, child) in kids.iter().copied().enumerate() {
3802                    let kind = &self.nodes[child].kind;
3803                    if *kind == Kind::ListItem || *kind == Kind::TaskListItem {
3804                        let start = self.nodes[child].span.start;
3805                        item_no += 1;
3806                        // A task item's box replaces the bullet rather than
3807                        // joining it. The `[ ] ` that spells it is markup twig
3808                        // has already consumed — the item's paragraph *content*
3809                        // starts past it — so without a drawn box a task item
3810                        // was indistinguishable from a plain bullet, ticked or
3811                        // not. `☐`/`☑` is the marker for the same reason `•` is:
3812                        // it stands where the source's own marker stands. Which
3813                        // way it faces is `checked`, straight off the node.
3814                        let checked = self.nodes[child].checked;
3815                        let marker = match (checked, ordered) {
3816                            (Some(true), _) => "☑ ".to_string(),
3817                            (Some(false), _) => "☐ ".to_string(),
3818                            (None, true) => format!("{item_no}. "),
3819                            (None, false) => "• ".to_string(),
3820                        };
3821                        let bullet = synth(&marker, Role::ListMarker, start);
3822                        let indent = synth(&" ".repeat(text_width(&marker)), Role::Body, start);
3823                        let first_row = self.rows.len();
3824                        self.block(child, &concat(pc, &bullet), &concat(pc, &indent));
3825                        // On the item's first row, the way `code_lang` rides the
3826                        // first row of its block.
3827                        if let (Some(c), Some(row)) = (checked, self.rows.get_mut(first_row)) {
3828                            row.task = Some(c);
3829                        }
3830                    } else {
3831                        // twig can nest a *following* top-level block as a direct
3832                        // child of the list rather than a sibling of it — e.g.
3833                        // `- item\n\n> quote` parses the block quote under the
3834                        // `bullet_list`. It isn't a list item, so render it de-nested:
3835                        // no bullet, at the list's own prefix, with the usual block
3836                        // separator — never `• │ quote`.
3837                        if i > 0 {
3838                            self.emit_separators_before(
3839                                self.nodes[child].span.start,
3840                                pc,
3841                                true,
3842                                Boundary {
3843                                    above: BlockClass::from_node_kind(
3844                                        &self.nodes[kids[i - 1]].kind,
3845                                    ),
3846                                    below: BlockClass::from_node_kind(&self.nodes[child].kind),
3847                                },
3848                            );
3849                        }
3850                        self.block(child, pc, pc);
3851                    }
3852                }
3853            }
3854            "list_item" | "task_list_item" => {
3855                // A childless item — the empty bullet you get the instant you
3856                // press Enter to open a new one — has no inner block to carry the
3857                // marker prefix or a caret home, so `blocks` would emit nothing
3858                // and the new bullet simply wouldn't appear until something was
3859                // typed into it. Emit the prefixed row itself, ending at a caret
3860                // stop just past the marker (the item's `span.end`), the way an
3861                // empty paragraph emits its one prefixed row via `emit_wrapped`.
3862                if self.children(id).is_empty() {
3863                    let home = self.nodes[id].span.end.min(self.source.len());
3864                    self.push_row_at(pf.to_vec(), home);
3865                } else {
3866                    // Tight: an item's text and the list nested under it butt
3867                    // together (`• a` / `  • b`), no fabricated blank row between —
3868                    // a loose item's real blank line still parts them.
3869                    self.blocks(id, pf, pc, true);
3870                }
3871            }
3872            // A footnote *definition* (`[^1]: the note`). It reaches this walker
3873            // only because [`top_level`] merges it back in — twig hangs it off no
3874            // parent at all, so a walk from `doc` never sees one and every byte
3875            // of its body used to render as nothing.
3876            //
3877            // Drawn as a hanging-indent item, the way a list item is: the marker
3878            // reads `[1] `, matching the `[1]` its references render as, so the
3879            // two can be paired by eye, and the body wraps under it. The marker
3880            // is synthetic decoration (one shared offset, never a caret stop) —
3881            // the `[^1]: ` that spells it in the source is markup, hidden like a
3882            // heading's `# `.
3883            "footnote" => {
3884                let (start, end) = (node.span.start, node.span.end);
3885                let source = self.source;
3886                let marker = format!("[{}] ", footnote_label(source, start).unwrap_or(""));
3887                let indent = " ".repeat(text_width(&marker));
3888                let f = concat(pf, &synth(&marker, Role::ListMarker, start));
3889                let c = concat(pc, &synth(&indent, Role::Body, start));
3890                if self.children(id).is_empty() {
3891                    // A definition with no body yet — the instant `[^1]: ` has
3892                    // been typed and nothing after it. `blocks` would emit
3893                    // nothing and the definition simply wouldn't appear, so emit
3894                    // the marker row itself with a caret home just past it,
3895                    // exactly as an empty list item does.
3896                    self.push_row_at(f, end.min(source.len()));
3897                } else {
3898                    self.blocks(id, &f, &c, false);
3899                }
3900            }
3901            // A link reference definition (`[foo]: /url`): resolved by label
3902            // into the links that use it, and drawn nowhere — the rich view has
3903            // no more use for its line than for a comment's. It is walked at all
3904            // (see [`top_level`]) so [`Builder::block_or_hidden`] can step the
3905            // walk past its bytes rather than count them as blank lines.
3906            "reference" => {}
3907            "table" => self.table(id, pf, pc),
3908            "code_block" => {
3909                let style = Style::default().role(Role::Code);
3910                let text = node.text.clone().unwrap_or_default();
3911                // Cut the block's *terminator*, not every trailing newline. A
3912                // block whose last line is empty spells that as a second `\n`,
3913                // and `trim_end_matches` ate it along with the terminator: the
3914                // Return that made the line got no row, so the caret placed on
3915                // it fell through to the paragraph below and typing landed
3916                // outside the block. twig's `content_span` is `text` less
3917                // exactly this one newline, so cutting one and no more is also
3918                // what keeps `code_line_offsets` lined up.
3919                let lines: Vec<&str> = text
3920                    .strip_suffix('\n')
3921                    .unwrap_or(text.as_str())
3922                    .split('\n')
3923                    .collect();
3924                // Each line at its own source offset, so the caret can walk the
3925                // code a character at a time like any other text. Where the
3926                // lines can't be lined up with the source there's no honest
3927                // offset to give, so the block maps coarsely to its start (and
3928                // stays a source-view job, as all of it once was).
3929                let offs = node
3930                    .content_span
3931                    .as_ref()
3932                    .and_then(|c| self.code_line_offsets(c, &lines));
3933                // The fence's info string, carried on the block's first row as
3934                // its language label (`None` for an indented block or a bare
3935                // fence). Kept on the row so it rides the block cache.
3936                let lang = code_language(self.source, node.span.start);
3937                // The block's syntax highlighting, a token per byte range of
3938                // each line — `None` unless the fence names a language the
3939                // grammars know (and unless the `syntax` feature is on). Done
3940                // here, once per build of the block, because the rows it
3941                // colours ride the block cache: an edit elsewhere in the
3942                // document reuses them, tokens and all.
3943                let tokens = lang.as_deref().and_then(|l| code_tokens(l, &lines));
3944                for (i, raw) in lines.iter().enumerate() {
3945                    let at = offs.as_ref().map_or(node.span.start, |o| o[i]);
3946                    // No gutter glyph: the block is set apart by the border and
3947                    // tint a frontend draws around the whole run of `code` rows,
3948                    // not by a per-line mark. Just the block prefix (a list
3949                    // indent, a quote gutter) and the code text.
3950                    let mut glyphs: Vec<Glyph> = pf.to_vec();
3951                    match tokens.as_ref().and_then(|t| t.get(i)) {
3952                        Some(spans) => push_code_text(&mut glyphs, raw, at, style, spans),
3953                        None => push_text(&mut glyphs, raw, at, style),
3954                    }
3955                    // Explicitly past the line's *text*: a blank code line has no
3956                    // glyph, and any prefix's offset would put the row's end
3957                    // inside the next line.
3958                    self.push_row_at(glyphs, at + raw.len());
3959                    if let Some(row) = self.rows.last_mut() {
3960                        row.code = true;
3961                        if i == 0 {
3962                            row.code_lang = lang.clone();
3963                        }
3964                    }
3965                }
3966                // Anchor the block's end past its closing fence. Its last content
3967                // row ends at the last code line, before the ``` and the blank
3968                // line under it; without this the separator logic would count the
3969                // closing-fence line as its own blank row and open a phantom
3970                // second gap below the block.
3971                self.last_off = node.span.end;
3972            }
3973            "thematic_break" => {
3974                let full = self.wrap.unwrap_or(UNWRAPPED_RULE_WIDTH);
3975                let w = full.saturating_sub(prefix_width(pf)).max(4);
3976                let mut glyphs = pf.to_vec();
3977                for _ in 0..w {
3978                    glyphs.push(Glyph {
3979                        ch: '─',
3980                        style: Style::default().role(Role::Rule),
3981                        src: node.span.start,
3982                        // A rule is a block the caret can sit on, as it always
3983                        // has; it maps coarsely to the block's start.
3984                        stop: true,
3985                    });
3986                }
3987                // The dashes share one caret home in front of the atomic block,
3988                // while the row's end is the second home, past the newline that
3989                // ends the rule's line. Without that trailing stop a final rule
3990                // made the document end unreachable: Right could not cross it
3991                // and a click in the empty space below it snapped back before
3992                // the rule.
3993                let (text_end, after_line) = block_line(self.source, node.span.end);
3994                self.push_row_at(glyphs, after_line);
3995                // The walk stands at the rule itself, though, as it stands at
3996                // the end of any other block's last line: the lines under a
3997                // rule are counted from the newline that ends it. Counted from
3998                // the home past that newline, every gap under a rule came up a
3999                // line short, and the empty paragraph Enter opens beneath one
4000                // drew as nothing at all.
4001                self.last_off = text_end;
4002            }
4003            // A block-level image node with no wrapping paragraph — a promoted
4004            // top-level HTML `<img>` lands as a direct `doc` child like this
4005            // (a Markdown `![](…)` comes wrapped in a `para`, handled below).
4006            "image" => self.block_media(id, MediaKind::Image, id, pf),
4007            // The same case for a promoted top-level `<video>`/`<audio>`, which
4008            // arrives as a generic `container` rather than a node kind of its
4009            // own. It can't be found by the `media_only` scan below the way a
4010            // wrapped one is: that scan looks at a wrapper's *children*, and here
4011            // the media element is itself the block.
4012            "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
4013                let kind = match element_tag(node) {
4014                    Some("audio") => MediaKind::Audio,
4015                    _ => MediaKind::Video,
4016                };
4017                self.block_media(id, kind, id, pf);
4018            }
4019            _ => {
4020                // A container of blocks, or an inline-bearing paragraph.
4021                let kids = self.children(id);
4022                // A block-level image: a paragraph (or other wrapper — a
4023                // `<picture>`, an `<h1>` banner) whose only visible content is a
4024                // single `image` node. Render it as a placeholder row + record an
4025                // [`MediaInfo`] a capable frontend replaces. An image mixed with
4026                // real text or other images on the line isn't block-level and
4027                // falls through to the inline path below, still as its alt text.
4028                if let Some((m, kind)) = self.media_only(id) {
4029                    self.block_media(m, kind, id, pf);
4030                    return;
4031                }
4032                // A display formula on lines of its own — a paragraph whose
4033                // only visible content is one `display_math` — promotes the
4034                // same way, to a placeholder row and a [`MathMark`].
4035                if let Some(m) = self.math_only(id) {
4036                    self.block_math(m, pf, pc);
4037                    return;
4038                }
4039                let inline = !kids.is_empty() && kids.iter().all(|&c| is_inline(&self.nodes[c]));
4040                if inline || kids.is_empty() {
4041                    // The block's own attributes over its containers' — the
4042                    // three run-level keys become the style its glyphs start
4043                    // from, and the two line-level ones ride every row it
4044                    // emits, a wrapped paragraph's continuations included.
4045                    let pres = self.presentation.under(&node.attrs, &self.faces);
4046                    let glyphs =
4047                        self.inline_children_with_trailing(id, pres.over(Style::default()));
4048                    if !glyphs.is_empty() {
4049                        let first = self.rows.len();
4050                        self.emit_wrapped(glyphs, node.span.start, pf, pc);
4051                        for row in &mut self.rows[first..] {
4052                            row.align = pres.align;
4053                            row.line_height = pres.line_height;
4054                        }
4055                    }
4056                } else {
4057                    self.blocks(id, pf, pc, false);
4058                }
4059            }
4060        }
4061    }
4062
4063    /// Render a table as a box-drawn grid: every column as wide as its widest
4064    /// cell, the header bold and ruled off, each cell padded to its column's
4065    /// alignment. This is the *default* monospace rendering (see
4066    /// [`VisualMap::rows`]); the same cells are also published structurally as
4067    /// [`TableInfo`], so a frontend that lays the grid out in its own units draws
4068    /// from there and skips the picture built here.
4069    ///
4070    /// The alignment comes from twig's `cell.alignment` — the delimiter row
4071    /// (`|:--|--:|`) that spells it out is consumed by the parser and leaves no
4072    /// node, so the snapshot is the only source for it.
4073    ///
4074    /// Borders and padding are *decoration*: they carry the source offset of the
4075    /// text they surround, so a click lands in that cell, but they're never
4076    /// caret stops — the caret steps cell-to-cell instead of into the box art.
4077    fn table(&mut self, id: usize, pf: &[Glyph], pc: &[Glyph]) {
4078        let node_end = self.nodes[id].span.end;
4079        // twig's shape is `[caption, row, row, …]`: the caption is always
4080        // present (usually empty in Markdown) and is not part of the grid.
4081        let row_ids: Vec<usize> = self
4082            .children(id)
4083            .into_iter()
4084            .filter(|&c| self.nodes[c].kind == Kind::Row)
4085            .collect();
4086        if row_ids.is_empty() {
4087            return;
4088        }
4089        // Lay every cell out first — the column widths depend on all of them.
4090        let grid: Vec<Vec<TableCell>> = row_ids.iter().map(|&r| self.row_cells(r)).collect();
4091        let heads: Vec<bool> = row_ids
4092            .iter()
4093            .map(|&r| self.nodes[r].head.unwrap_or(false))
4094            .collect();
4095        let cols = grid.iter().map(|r| r.len()).max().unwrap_or(0);
4096        if cols == 0 {
4097            return;
4098        }
4099        let mut widths = vec![0usize; cols];
4100        for row in &grid {
4101            for (c, cell) in row.iter().enumerate() {
4102                widths[c] = widths[c].max(cell_width(&cell.glyphs));
4103            }
4104        }
4105        // Every column at its widest cell is only the *wish*; a grid wider than
4106        // the surface has its far side hanging off the edge where no amount of
4107        // caret motion can reach it. Cut it down to what's actually there, and
4108        // let the cells wrap into the space they're given.
4109        if let Some(w) = self.wrap {
4110            fit_widths(&mut widths, w.saturating_sub(prefix_width(pc)));
4111        }
4112
4113        // Where the picture starts, so a frontend drawing its own grid knows
4114        // which rows to skip. Recorded before the first border goes down.
4115        let rows_start = self.rows.len();
4116
4117        let anchor = grid[0].first().map(|c| c.start).unwrap_or(node_end);
4118        self.push_rule(&rule_text(&widths, '┌', '┬', '┐'), anchor, pf);
4119        for (ri, row) in grid.iter().enumerate() {
4120            self.push_table_row(row, &widths, pc);
4121            // The rule under the header: only where the head actually ends.
4122            let ends_head = heads[ri] && heads.get(ri + 1) == Some(&false);
4123            if ends_head {
4124                let next = grid[ri + 1].first().map(|c| c.start).unwrap_or(node_end);
4125                self.push_rule(&rule_text(&widths, '├', '┼', '┤'), next, pc);
4126            }
4127        }
4128        // The bottom border is the one rule the caret can rest on: its end is
4129        // the table's trailing stop, the caret home just past the block — the
4130        // peer of a block picture's second stop, and of a rule's row end. Without
4131        // it a document ending in a table ended *inside* it: nothing after the
4132        // last cell was a stop, so Right could not leave the table, and a click
4133        // in the blank space under it snapped back into the last cell — or, on a
4134        // surface that resolved the click onto the border row, to the table's
4135        // first cell, since a decoration row's only stop is the nearest one.
4136        // Typing at the stop opens a paragraph first, as at a picture's — see
4137        // `Doc::open_paragraph_at_block_edge`. The glyphs stay non-stops at
4138        // `node_end`, so a click anywhere on the border lands past the table.
4139        self.push_rule_with_home(&rule_text(&widths, '└', '┴', '┘'), node_end, pc);
4140
4141        // The same cells the picture above was drawn from, published unwrapped
4142        // and unpadded for a frontend that lays them out in pixels.
4143        self.tables.push(TableInfo {
4144            rows_span: rows_start..self.rows.len(),
4145            end_src: node_end,
4146            // The *continuation* prefix: `pf` opens the block and only its first
4147            // row wears it, but every row of a grid is a continuation of the
4148            // block the table sits in.
4149            prefix: pc.to_vec(),
4150            grid: grid
4151                .into_iter()
4152                .zip(heads)
4153                .map(|(cells, head)| TableRow { head, cells })
4154                .collect(),
4155        });
4156        // The table's own end anchors whatever separator follows it; the border
4157        // rows deliberately don't move `last_off` (they hold no content).
4158        self.last_off = node_end;
4159    }
4160
4161    /// One row of laid-out cells, in column order.
4162    fn row_cells(&self, row: usize) -> Vec<TableCell> {
4163        // A cell is one source line, so a break within it is an explicit line
4164        // break (an inline `<br>`) that must render as a line of its own — not the
4165        // flow-folding space a break is in prose.
4166        self.break_glyph.set('\n');
4167        let cells = self
4168            .children(row)
4169            .into_iter()
4170            .filter(|&c| self.nodes[c].kind == Kind::Cell)
4171            .enumerate()
4172            .map(|(col, c)| {
4173                let n = &self.nodes[c];
4174                let style = if n.head.unwrap_or(false) {
4175                    Style::default().bold()
4176                } else {
4177                    Style::default()
4178                };
4179                // Only `content_span` bounds a cell's text, and an EMPTY cell
4180                // has none at all — twig records no interior for it — so both
4181                // offsets would fall back to the cell's `span.start`: on the
4182                // pipe that opens it, or (under a twig that gave every cell
4183                // the whole row's span) the row's start, where every empty
4184                // cell collapses onto one spot before the first `│` and a
4185                // caret there types *before* the table. Derive the interior
4186                // from the span's own pipes and this cell's column instead,
4187                // so each empty cell has a distinct, editable caret home.
4188                let span = n.content_span.clone().unwrap_or_else(|| {
4189                    let off = empty_cell_offset(
4190                        &self.source[n.span.start.min(self.source.len())
4191                            ..n.span.end.min(self.source.len())],
4192                        n.span.start,
4193                        col,
4194                    );
4195                    off..off
4196                });
4197                TableCell {
4198                    glyphs: self.inline_children(c, style),
4199                    start: span.start,
4200                    end: span.end,
4201                    align: n.alignment.unwrap_or(Alignment::Default),
4202                }
4203            })
4204            .collect();
4205        self.break_glyph.set(' ');
4206        cells
4207    }
4208
4209    /// A horizontal rule between/around rows — entirely decoration.
4210    fn push_rule(&mut self, text: &str, src: usize, prefix: &[Glyph]) {
4211        self.push_rule_row(text, src, prefix, true);
4212    }
4213
4214    /// A table's bottom border: drawn like the other rules, but a row the caret
4215    /// can rest on, its end (`src`) being the table's trailing stop.
4216    fn push_rule_with_home(&mut self, text: &str, src: usize, prefix: &[Glyph]) {
4217        self.push_rule_row(text, src, prefix, false);
4218    }
4219
4220    fn push_rule_row(&mut self, text: &str, src: usize, prefix: &[Glyph], decoration: bool) {
4221        let glyphs = concat(prefix, &synth(text, Role::Rule, src));
4222        self.rows.push(VRow {
4223            glyphs,
4224            end_src: src,
4225            decoration,
4226            code: false,
4227            code_lang: None,
4228            directive: false,
4229            directive_label: None,
4230            media: None,
4231            task: None,
4232            leaf_directive: None,
4233            heading: None,
4234            align: None,
4235            line_height: None,
4236            boundary: None,
4237            mark_ends: Vec::new(),
4238            math: Vec::new(),
4239        });
4240    }
4241
4242    /// One `│ a │ b │` row of the grid: real cell text between decoration.
4243    ///
4244    /// A row of cells is not a row of the screen — a cell wrapped to its column
4245    /// spans several, each one `│`-divided across the full width so the grid
4246    /// stays square. Cells in the same row are laid out independently and run
4247    /// out at their own heights; a column that has run dry pads out as
4248    /// decoration while its neighbours keep going.
4249    fn push_table_row(&mut self, cells: &[TableCell], widths: &[usize], prefix: &[Glyph]) {
4250        let fallback = cells.last().map(|c| c.end).unwrap_or(0);
4251        let laid: Vec<Vec<Vec<Glyph>>> = cells
4252            .iter()
4253            .enumerate()
4254            .map(|(ci, c)| wrap_glyphs(&c.glyphs, widths.get(ci).copied().unwrap_or(0)))
4255            .collect();
4256        let height = laid.iter().map(|l| l.len()).max().unwrap_or(1).max(1);
4257
4258        for j in 0..height {
4259            let mut glyphs = prefix.to_vec();
4260            for (ci, &w) in widths.iter().enumerate() {
4261                let cell = cells.get(ci);
4262                let line = laid.get(ci).and_then(|l| l.get(j));
4263                // The divider before this column belongs to the cell it
4264                // introduces, so clicking it lands in that cell — on this line
4265                // of it, which is what's next to the divider being clicked.
4266                let at = line
4267                    .and_then(|l| l.first().map(|g| g.src))
4268                    .or_else(|| cell.map(|c| c.start))
4269                    .unwrap_or(fallback);
4270                glyphs.extend(synth("│", Role::Rule, at));
4271                match (cell, line) {
4272                    (Some(cell), Some(line)) => {
4273                        let pad = w.saturating_sub(glyphs_width(line));
4274                        let (lead, trail) = match cell.align {
4275                            Alignment::Right => (pad, 0),
4276                            Alignment::Center => (pad / 2, pad - pad / 2),
4277                            Alignment::Left | Alignment::Default => (0, pad),
4278                        };
4279                        // Every line renders at least one space after its text
4280                        // (the gutter before `│`), so there is always somewhere
4281                        // to put the "after the last character" caret a line
4282                        // needs. It's the one padding glyph that is a stop: on
4283                        // the cell's last line that's the cell's end, and on any
4284                        // other it's the space the wrap consumed.
4285                        let last = laid[ci].len() == j + 1;
4286                        let end = match last {
4287                            true => cell.end,
4288                            false => line
4289                                .last()
4290                                .map(|g| g.src + g.ch.len_utf8())
4291                                .unwrap_or(cell.end),
4292                        };
4293                        glyphs.extend(synth(&" ".repeat(lead + 1), Role::Body, at));
4294                        glyphs.extend(line.iter().cloned());
4295                        glyphs.push(Glyph {
4296                            ch: ' ',
4297                            style: Style::default(),
4298                            src: end,
4299                            stop: true,
4300                        });
4301                        glyphs.extend(synth(&" ".repeat(trail), Role::Body, end));
4302                    }
4303                    // A ragged row, or a column whose cell ended higher up: pad
4304                    // it out so the grid stays square.
4305                    _ => {
4306                        let at = cell.map(|c| c.end).unwrap_or(fallback);
4307                        glyphs.extend(synth(&" ".repeat(w + 2), Role::Body, at));
4308                    }
4309                }
4310            }
4311            glyphs.extend(synth("│", Role::Rule, fallback));
4312            // The row ends where its last stop does. A table row has no gap
4313            // between its final cell and the border, so inventing an end past
4314            // that would be a stop with nothing under it.
4315            let end_src = glyphs
4316                .iter()
4317                .rev()
4318                .find(|g| g.stop)
4319                .map_or(fallback, |g| g.src);
4320            let mark_ends = self.take_mark_ends(end_src);
4321            let math = self.take_math(&glyphs);
4322            self.rows.push(VRow {
4323                glyphs,
4324                end_src,
4325                decoration: false,
4326                code: false,
4327                code_lang: None,
4328                directive: false,
4329                directive_label: None,
4330                media: None,
4331                task: None,
4332                leaf_directive: None,
4333                heading: None,
4334                align: None,
4335                line_height: None,
4336                boundary: None,
4337                mark_ends,
4338                math,
4339            });
4340        }
4341    }
4342
4343    /// Render a block-level image, video, or audio as one placeholder row: the
4344    /// `🖼 alt` / `🎬 alt` / `🔊 alt` label styled [`Role::Image`], every glyph
4345    /// mapped to the media's start offset and a caret stop there (they share the
4346    /// offset, so the stop table dedups them to a single home in front of it, as
4347    /// a rule's dashes do), and the row's end stop set past it so the caret can
4348    /// also rest after it. The row carries a [`MediaMark`] so [`media_spans`]
4349    /// publishes it as a [`MediaInfo`] a capable frontend replaces with the real
4350    /// picture or player; a plain surface paints the label as-is. `pf` is the
4351    /// block prefix (a list indent, a quote gutter) the row opens with, exactly
4352    /// as every other block honours it.
4353    fn block_media(&mut self, img: usize, kind: MediaKind, wrapper: usize, pf: &[Glyph]) {
4354        let node = &self.nodes[img];
4355        let start = node.span.start;
4356        let end = node.span.end;
4357        // An `image`'s URL is twig's `destination`; a `<video>`/`<audio>` is a
4358        // generic element, so its URL is the `src` attribute — and may be absent
4359        // entirely, the element naming its candidates in child `<source>`s.
4360        let destination = match kind {
4361            MediaKind::Image => node.destination.clone().unwrap_or_default(),
4362            MediaKind::Video | MediaKind::Audio => attr_of(node, "src").unwrap_or_default(),
4363        };
4364        let poster = match kind {
4365            MediaKind::Video => attr_of(node, "poster").unwrap_or_default(),
4366            MediaKind::Image | MediaKind::Audio => String::new(),
4367        };
4368        // The `<source>`s under the media element itself, not under `wrapper`: a
4369        // `<video>` is its own container, unlike an `<img>`, whose `<picture>`
4370        // alternatives are its *siblings* and so only reachable from the wrapper.
4371        let sources = match kind {
4372            MediaKind::Image => self.media_sources(wrapper),
4373            MediaKind::Video | MediaKind::Audio => self.media_sources(img),
4374        };
4375        let alt = self.image_alt(img);
4376        let sigil = kind.sigil();
4377        let label = if alt.is_empty() {
4378            // With no alt, name the file — but a `<video>` with neither `src` nor
4379            // alt has only its `<source>`s to be named by, so fall back to the
4380            // first candidate rather than labelling the row a bare sigil.
4381            let named = if destination.is_empty() {
4382                sources
4383                    .first()
4384                    .map(|s| s.srcset.as_str())
4385                    .unwrap_or_default()
4386            } else {
4387                &destination
4388            };
4389            format!("{sigil} {}", media_label(named))
4390        } else {
4391            format!("{sigil} {alt}")
4392        };
4393        let style = Style::default().role(Role::Image);
4394        let mut glyphs = pf.to_vec();
4395        for ch in label.chars() {
4396            glyphs.push(Glyph {
4397                ch,
4398                style,
4399                src: start,
4400                stop: true,
4401            });
4402        }
4403        // How many rows the frontend wants for this picture: the label row plus
4404        // the blank fillers below it. Absent (a GUI that lays images out in
4405        // pixels, an image that didn't resolve, or a plain surface) means the
4406        // bare one-row placeholder.
4407        let rows = self
4408            .surface
4409            .media_rows
4410            .get(&destination)
4411            .copied()
4412            .unwrap_or(1)
4413            .max(1);
4414        // End past the image so the caret has a stop after it: the last glyph's
4415        // offset is the image *start*, not its extent, so `push_row`'s
4416        // last-glyph rule would strand the end stop inside the markup.
4417        self.push_row_at(glyphs, end);
4418        if let Some(row) = self.rows.last_mut() {
4419            row.media = Some(MediaMark {
4420                kind,
4421                destination,
4422                sources,
4423                alt,
4424                poster,
4425                rows,
4426            });
4427        }
4428        // Reserve the picture's remaining height as blank `decoration` rows: drawn
4429        // (so the frontend has the vertical room to paint the raster over them),
4430        // but holding no caret and contributing no stops — vertical motion steps
4431        // over them and the caret's only homes stay the stop in front of the image
4432        // and the one just past it, both on the label row above. They anchor at the
4433        // image's end offset so a click on the picture's lower half lands after it,
4434        // the nearest caret home. Mirrors how a table's box-rule rows reserve space
4435        // without ever holding the caret.
4436        for _ in 1..rows {
4437            self.rows.push(VRow {
4438                glyphs: Vec::new(),
4439                end_src: end,
4440                decoration: true,
4441                code: false,
4442                code_lang: None,
4443                directive: false,
4444                directive_label: None,
4445                media: None,
4446                task: None,
4447                leaf_directive: None,
4448                heading: None,
4449                align: None,
4450                line_height: None,
4451                boundary: None,
4452                mark_ends: Vec::new(),
4453                math: Vec::new(),
4454            });
4455        }
4456        self.last_off = end;
4457    }
4458
4459    /// The `<picture>` alternatives inside block-image `wrapper`, in document
4460    /// order — every `<source>` element in its subtree. Empty when there's no
4461    /// `<picture>`. Each is a `<source>`'s `media` + `srcset`; core keeps them
4462    /// verbatim and picks none (see [`MediaSource`]). A `<source>` with no
4463    /// `srcset` is dropped (nothing to load); its `media` may be empty (an
4464    /// unconditional override), which a frontend treats as always-matching.
4465    ///
4466    /// It scans the wrapper's whole subtree (via the forward `first_child` /
4467    /// `next_sibling` links, the reliable ones) rather than the `<img>`'s parent,
4468    /// for two reasons. A `<picture>` reaches core in two shapes: twig promotes a
4469    /// block `<picture>` to an `element(picture)` wrapping `[source, img]`, but
4470    /// leaves an inline one's tags as raw siblings — `[raw "<picture>", source,
4471    /// img, raw "</picture>"]` — so the `<source>`s sit at different depths in
4472    /// the two. And the editor's flat arena leaves a promoted inline node's
4473    /// `parent` back-pointer dangling on a phantom root, so only the wrapper
4474    /// (known at the call site) is a trustworthy anchor. A block image is the
4475    /// sole visible content of its wrapper, so every `<source>` under it is its
4476    /// picture's.
4477    fn media_sources(&self, wrapper: usize) -> Vec<MediaSource> {
4478        let mut out = Vec::new();
4479        self.collect_sources(wrapper, &mut out);
4480        out
4481    }
4482
4483    fn collect_sources(&self, id: usize, out: &mut Vec<MediaSource>) {
4484        for c in self.children(id) {
4485            let node = &self.nodes[c];
4486            if node.name.as_deref() == Some("source") {
4487                // `<picture>` spells its candidate `srcset`, `<video>`/`<audio>`
4488                // spell it `src`. Both mean "the URL to load", so they normalise
4489                // onto one field; `srcset` wins where (illegally) both appear.
4490                let url = attr_of(node, "srcset").or_else(|| attr_of(node, "src"));
4491                if let Some(srcset) = url {
4492                    out.push(MediaSource {
4493                        media: attr_of(node, "media").unwrap_or_default(),
4494                        srcset,
4495                        mime: attr_of(node, "type").unwrap_or_default(),
4496                    });
4497                }
4498            }
4499            self.collect_sources(c, out);
4500        }
4501    }
4502
4503    /// The single block-level media `id`'s subtree resolves to, or `None`.
4504    ///
4505    /// A wrapper is a block picture when the only *visible* thing under it is one
4506    /// image: whitespace-only text and structure-only elements (a `<picture>`'s
4507    /// `<source>`, which declares an alternate but paints nothing) don't count,
4508    /// and the search descends through wrapping elements (`<picture>`, a linking
4509    /// `<a>`). This is what makes `<p><img></p>`, a bare `<img>`, and
4510    /// `<h1><picture>…<img></picture></h1>` all render as one framed picture.
4511    /// Any real text, or a second image, means it isn't image-only — it falls
4512    /// back to inline rendering, where the image still shows as its alt text.
4513    ///
4514    /// [`FlatNode`]'s snapshot doesn't carry an element's tag name, so a
4515    /// `<source>` can't be skipped by name — but it needs no special case:
4516    /// contributing no image and no text, it's simply invisible to the scan.
4517    fn media_only(&self, id: usize) -> Option<(usize, MediaKind)> {
4518        let mut found = None;
4519        let mut count = 0usize;
4520        let mut has_text = false;
4521        self.scan_visual(id, &mut found, &mut count, &mut has_text);
4522        (count == 1 && !has_text).then(|| found.unwrap())
4523    }
4524
4525    /// Walk `id`'s subtree tallying visible leaves for [`media_only`]: each
4526    /// image, `<video>`, or `<audio>` (remembering the last, counting the total)
4527    /// and whether any non-whitespace text appears. Media isn't descended into —
4528    /// an image's inline children are alt text, and a `<video>`'s are its
4529    /// no-support fallback and its `<source>` declarations, none of which is
4530    /// document content.
4531    ///
4532    /// [`media_only`]: Self::media_only
4533    fn scan_visual(
4534        &self,
4535        id: usize,
4536        found: &mut Option<(usize, MediaKind)>,
4537        count: &mut usize,
4538        has_text: &mut bool,
4539    ) {
4540        for c in self.children(id) {
4541            let node = &self.nodes[c];
4542            match node.kind.as_str() {
4543                "image" => {
4544                    *found = Some((c, MediaKind::Image));
4545                    *count += 1;
4546                }
4547                // A `<video>`/`<audio>` reaches core as a generic `container`
4548                // (twig gives neither a semantic node, so `html_elements`
4549                // promotion leaves the tag name on `name`). Counted as media and
4550                // *not* descended into, so its `<source>` children and its
4551                // "your browser does not support…" fallback text neither add a
4552                // second count nor make the block look like text.
4553                "container" if matches!(element_tag(node), Some("video") | Some("audio")) => {
4554                    let kind = match element_tag(node) {
4555                        Some("audio") => MediaKind::Audio,
4556                        _ => MediaKind::Video,
4557                    };
4558                    *found = Some((c, kind));
4559                    *count += 1;
4560                }
4561                // Text leaves: only non-whitespace counts as visible content.
4562                // (Twig keeps the whitespace `str`s between HTML tags — the
4563                // newlines and indentation inside a `<picture>` — as real nodes.)
4564                "str" | "smart_punctuation" | "verbatim" | "inline_math" | "display_math" => {
4565                    if node.text.as_deref().is_some_and(|t| !t.trim().is_empty()) {
4566                        *has_text = true;
4567                    }
4568                }
4569                // Structural breaks carry no visible glyph of their own.
4570                "soft_break" | "hard_break" | "non_breaking_space" => {}
4571                // Any other wrapper (emphasis, a link, a `<picture>`) is
4572                // transparent to the scan — descend into it.
4573                _ => self.scan_visual(c, found, count, has_text),
4574            }
4575        }
4576    }
4577
4578    /// The single `display_math` that is all of `id`'s visible content, or
4579    /// `None` — [`media_only`](Self::media_only) for a formula. Whitespace-only
4580    /// text around it does not count (twig keeps the newlines either side of a
4581    /// `$$` on its own lines as `str`s); any other text, or a second formula,
4582    /// means the paragraph is prose with math in it, and falls through to the
4583    /// inline path.
4584    fn math_only(&self, id: usize) -> Option<usize> {
4585        let mut found = None;
4586        let mut count = 0usize;
4587        for c in self.children(id) {
4588            let node = &self.nodes[c];
4589            match node.kind.as_str() {
4590                "display_math" => {
4591                    found = Some(c);
4592                    count += 1;
4593                }
4594                "str" | "smart_punctuation" => {
4595                    if node.text.as_deref().is_some_and(|t| !t.trim().is_empty()) {
4596                        return None;
4597                    }
4598                }
4599                "soft_break" | "hard_break" | "non_breaking_space" => {}
4600                _ => return None,
4601            }
4602        }
4603        (count == 1).then(|| found.unwrap())
4604    }
4605
4606    /// A display formula on lines of its own, drawn on
4607    /// [`block_media`](Self::block_media)'s recipe: one placeholder row —
4608    /// `∑` and the TeX on one line, every glyph [`Role::Math`] at the
4609    /// formula's start and a caret stop there, the row ending past the
4610    /// formula so the caret can rest after it too — carrying a [`MathMark`]
4611    /// for [`math_spans`] to publish, and under it as many blank decoration
4612    /// rows as the frontend said the picture is tall
4613    /// ([`Surface::math_rows`]).
4614    ///
4615    /// On the caret's line the block is its source instead: the `$$`
4616    /// delimiters in [`Role::Delimiter`] and the TeX between them in
4617    /// [`Role::Code`], line for line, the way a fence draws — so a formula is
4618    /// edited where it stands and folds back to its picture when the caret
4619    /// leaves. That is the same rule an inline formula follows, and it is
4620    /// what makes a block-level formula need no equivalent of
4621    /// [`VisualMap::block_media_stop`]: both of the placeholder's caret homes
4622    /// are on the formula's own lines, and standing on either reveals it.
4623    fn block_math(&mut self, math: usize, pf: &[Glyph], pc: &[Glyph]) {
4624        self.saw_math.set(true);
4625        let node = &self.nodes[math];
4626        let (start, end) = (node.span.start, node.span.end);
4627        let tex = node.text.clone().unwrap_or_default();
4628        if self.math_revealed(&node.span) {
4629            let mut glyphs = Vec::new();
4630            self.inline_verbatim(math, Style::default(), &mut glyphs, true);
4631            self.emit_wrapped(glyphs, start, pf, pc);
4632            self.last_off = end;
4633            return;
4634        }
4635        let style = Style::default().role(Role::Math);
4636        let mut glyphs = pf.to_vec();
4637        // One line of label: the TeX with its newlines folded, so the row
4638        // reads as one thing however the source laid it out.
4639        let label: String = tex.split_whitespace().collect::<Vec<_>>().join(" ");
4640        for ch in format!("{MATH_ATOM} {label}").chars() {
4641            glyphs.push(Glyph {
4642                ch,
4643                style,
4644                src: start,
4645                stop: true,
4646            });
4647        }
4648        let rows = self
4649            .surface
4650            .math_rows
4651            .get(&tex)
4652            .copied()
4653            .unwrap_or(1)
4654            .max(1);
4655        self.push_row_at(glyphs, end);
4656        if let Some(row) = self.rows.last_mut() {
4657            row.math = vec![MathMark {
4658                tex,
4659                display: true,
4660                glyph: None,
4661                rows,
4662            }];
4663        }
4664        for _ in 1..rows {
4665            self.rows.push(VRow {
4666                glyphs: Vec::new(),
4667                end_src: end,
4668                decoration: true,
4669                code: false,
4670                code_lang: None,
4671                directive: false,
4672                directive_label: None,
4673                media: None,
4674                task: None,
4675                leaf_directive: None,
4676                heading: None,
4677                align: None,
4678                line_height: None,
4679                boundary: None,
4680                mark_ends: Vec::new(),
4681                math: Vec::new(),
4682            });
4683        }
4684        self.last_off = end;
4685    }
4686
4687    /// A leaf directive (`::name{…}`) as one placeholder row — the
4688    /// [`block_media`](Self::block_media) recipe, for the same reason: it is a
4689    /// block that renders as *a thing*, not as text, and the frontend paints
4690    /// whatever the host app's vocabulary makes of it.
4691    ///
4692    /// The row's glyphs are a `⧉ label` (or `⧉ name`) stand-in a plain surface
4693    /// paints as-is, every glyph anchored at the directive's start with a caret
4694    /// stop there, and the row ending past it so the caret can also rest after
4695    /// it. It carries a [`DirectiveMark`] for [`directive_spans`], and is marked
4696    /// [`directive`](VRow::directive) so a frontend already drawing the
4697    /// container form's panel frames this one identically for free.
4698    ///
4699    /// Before this, a leaf directive emitted no rows at all: it was invisible,
4700    /// held no caret, and vertical motion crossed a void where it stood.
4701    fn block_directive(&mut self, id: usize, pf: &[Glyph]) {
4702        let node = &self.nodes[id];
4703        let (start, end) = (node.span.start, node.span.end);
4704        let (name, attrs) = leaf_directive_identity(node);
4705        let label = self.image_alt(id); // its `[label]` children, flattened
4706        let shown = if label.is_empty() { &name } else { &label };
4707        let style = Style::default().role(Role::Image);
4708        let mut glyphs = pf.to_vec();
4709        for ch in format!("⧉ {shown}").chars() {
4710            glyphs.push(Glyph {
4711                ch,
4712                style,
4713                src: start,
4714                stop: true,
4715            });
4716        }
4717        // End past the directive so the caret has a stop after it — the same
4718        // reason `block_media` anchors its row at the image's end.
4719        self.push_row_at(glyphs, end);
4720        if let Some(row) = self.rows.last_mut() {
4721            row.directive = true;
4722            row.leaf_directive = Some(DirectiveMark {
4723                name,
4724                attrs,
4725                label,
4726                rows: 1,
4727            });
4728        }
4729        self.last_off = end;
4730    }
4731
4732    /// An image's alt text: the flattened text of its inline descendants (an
4733    /// image's children *are* its alt content), empty when it has none. Also a
4734    /// leaf directive's `[label]`, which is the same shape — inline children
4735    /// standing for the block.
4736    fn image_alt(&self, id: usize) -> String {
4737        let mut out = String::new();
4738        self.collect_text(id, &mut out);
4739        out
4740    }
4741
4742    /// Append every descendant's `text` to `out`, in document order. Inline text
4743    /// (`str`) nodes are leaves, so a node never contributes both its own text and
4744    /// a child's — no double counting.
4745    fn collect_text(&self, id: usize, out: &mut String) {
4746        for c in self.children(id) {
4747            if let Some(t) = &self.nodes[c].text {
4748                out.push_str(t);
4749            }
4750            self.collect_text(c, out);
4751        }
4752    }
4753
4754    fn inline_children(&self, id: usize, base: Style) -> Vec<Glyph> {
4755        let mut out = Vec::new();
4756        for c in self.children(id) {
4757            self.inline(c, base, &mut out);
4758        }
4759        out
4760    }
4761
4762    /// [`inline_children`](Self::inline_children) plus any trailing whitespace the
4763    /// block carries past its inline content (see [`trailing_ws_glyphs`]). Used
4764    /// for the leaf inline blocks — paragraphs and headings — whose own `span`
4765    /// bounds exactly one line of text, so the trailing gap is theirs. *Not* for
4766    /// a table cell, whose `span` is the whole row and would swallow the
4767    /// delimiters and neighbours between it and the row's end.
4768    ///
4769    /// [`trailing_ws_glyphs`]: Self::trailing_ws_glyphs
4770    fn inline_children_with_trailing(&self, id: usize, base: Style) -> Vec<Glyph> {
4771        let mut out = self.inline_children(id, base);
4772        out.extend(self.trailing_ws_glyphs(id, base));
4773        out
4774    }
4775
4776    /// Glyphs for whatever trailing whitespace a block's source carries past its
4777    /// last inline node — the space(s) at the end of `hello ` that Markdown and
4778    /// Djot drop from the `str` node as insignificant. twig still records them:
4779    /// a block's `content_span` ends at its last meaningful character while its
4780    /// `span` runs to the end of the line's text (before the terminating
4781    /// newline), so the gap between the two *is* that trailing whitespace.
4782    ///
4783    /// Emitting it as real caret-stop glyphs is what lets the caret be drawn
4784    /// past the last visible character. Without it, typing a space at the end of
4785    /// a paragraph moved the caret in the source but not on screen — the caret
4786    /// stuck on the last glyph until the next visible character reparsed the
4787    /// space into an interior `str` node that finally carried it.
4788    ///
4789    /// Restricted to spaces: only they are safe to synthesize one-cell-per-byte,
4790    /// and only they are what the parser silently strips. Anything else in the
4791    /// gap means the span accounting isn't what this assumes, so it's left alone.
4792    fn trailing_ws_glyphs(&self, id: usize, style: Style) -> Vec<Glyph> {
4793        let node = &self.nodes[id];
4794        let Some(content) = &node.content_span else {
4795            return Vec::new();
4796        };
4797        let (from, to) = (content.end, node.span.end);
4798        let Some(slice) = (from < to).then(|| self.source.get(from..to)).flatten() else {
4799            return Vec::new();
4800        };
4801        if slice.is_empty() || slice.bytes().any(|b| b != b' ') {
4802            return Vec::new();
4803        }
4804        slice
4805            .bytes()
4806            .enumerate()
4807            .map(|(i, _)| Glyph {
4808                ch: ' ',
4809                style,
4810                src: from + i,
4811                stop: true,
4812            })
4813            .collect()
4814    }
4815
4816    fn inline(&self, id: usize, base: Style, out: &mut Vec<Glyph>) {
4817        let node = &self.nodes[id];
4818        match node.kind.as_str() {
4819            "str" | "smart_punctuation" => push_escaped_text(
4820                out,
4821                node.text.as_deref().unwrap_or(""),
4822                node.span.clone(),
4823                self.source,
4824                base,
4825            ),
4826            "soft_break" | "hard_break" | "non_breaking_space" => {
4827                // A break renders as a real, caret-navigable glyph — but twig
4828                // gives it no span of its own (`0..0`), so the offset comes from
4829                // the text in front of it: one *past* the last glyph, which is
4830                // the newline the break stands for. Past, not on: sharing the
4831                // previous glyph's offset would put two stops on one byte, and a
4832                // caret that can't change offset can't move.
4833                let src = if node.span.start != 0 {
4834                    node.span.start
4835                } else {
4836                    out.last().map(|g| g.src + g.ch.len_utf8()).unwrap_or(0)
4837                };
4838                // A *hard* break renders as this run's break glyph — a newline
4839                // inside a table cell (its own line), the same space in prose the
4840                // frontend re-wraps. A soft break normally folds into a space;
4841                // under `LineFlow::Preserve` it renders as a `'\n'` too, so the
4842                // author's line break shows where it was written. Never inside a
4843                // cell (`break_glyph` is `'\n'` there): a cell is one line and
4844                // folds its own soft breaks regardless.
4845                let ch = if node.kind == Kind::HardBreak {
4846                    self.break_glyph.get()
4847                } else if node.kind == Kind::SoftBreak
4848                    && self.preserve_soft
4849                    && self.break_glyph.get() == ' '
4850                {
4851                    '\n'
4852                } else {
4853                    ' '
4854                };
4855                out.push(Glyph {
4856                    ch,
4857                    style: base,
4858                    src,
4859                    stop: true,
4860                });
4861            }
4862            // A cell's only spelling for an in-line break is a raw `<br>`; read it
4863            // back as one (outside a cell it stays the literal text it falls to
4864            // below). The tag's bytes carry no stop of their own — the line it
4865            // ends stops just before it, the next just after.
4866            "raw_inline" if self.break_glyph.get() == '\n' && is_br(node.text.as_deref()) => {
4867                out.push(Glyph {
4868                    ch: '\n',
4869                    style: base,
4870                    src: node.span.start,
4871                    stop: true,
4872                });
4873            }
4874            "emph" => self.inline_delimited(id, base.italic(), out),
4875            "strong" => self.inline_delimited(id, base.bold(), out),
4876            // A coloured highlight's emoji is spelling, not content: twig strips
4877            // it and records the colour on the node, so the glyphs are the
4878            // author's words and the colour rides the role. Revealed markup
4879            // still shows the emoji, because `delims` reads the source bytes
4880            // between the span and the content span — which is exactly the
4881            // `==🔴 ` the author typed.
4882            "mark" => {
4883                let color = MarkColor::from_attrs(&node.attrs);
4884                self.inline_delimited(id, base.role(Role::Mark(color)), out)
4885            }
4886            "insert" => self.inline_delimited(id, base.underline(), out),
4887            "delete" => self.inline_delimited(id, base.strikethrough(), out),
4888            // The one pair whose whole meaning is *where the glyphs sit*. Drawn
4889            // in the surrounding style otherwise, so `^**2**^` stays bold and a
4890            // superscript inside a heading keeps the heading's role — which is
4891            // exactly why this is a `Baseline` and not a `Role`.
4892            "superscript" => self.inline_delimited(id, base.baseline(Baseline::Super), out),
4893            "subscript" => self.inline_delimited(id, base.baseline(Baseline::Sub), out),
4894            "verbatim" => self.inline_verbatim(id, base, out, self.revealed(&node.span)),
4895            // A formula in a line. Three renderings, in order of preference:
4896            //
4897            // - On the caret's line it is its TeX in the code style with its
4898            //   delimiters shown — in *every* markup mode, because the
4899            //   content is not the picture and hiding the `$` alone would
4900            //   leave nothing to edit. `math_revealed` is `revealed` without
4901            //   the mode gate.
4902            // - On a surface that paints pictures in a line it is one atom
4903            //   glyph, `stop: true` at the formula's start, standing for the
4904            //   whole thing; the [`MathMark`] drained onto the row by
4905            //   [`take_math`](Self::take_math) says what the frontend draws
4906            //   there. The caret has the stop on the atom and the next glyph's
4907            //   past it, and nothing inside the markup.
4908            // - Elsewhere — a terminal — it is the code-styled TeX with the
4909            //   delimiters hidden, exactly the verbatim treatment, and what
4910            //   `inline_math` rendered as before there was anything else.
4911            //   `display_math` had no arm at all and fell to the default one,
4912            //   which pushed its text at the *node's* start, three bytes short
4913            //   of where the text sits.
4914            "inline_math" | "display_math" => {
4915                self.saw_math.set(true);
4916                if self.math_revealed(&node.span) {
4917                    self.inline_verbatim(id, base, out, true);
4918                } else if self.surface.inline_pictures {
4919                    let tex = node.text.clone().unwrap_or_default();
4920                    self.pending_math.borrow_mut().push((
4921                        node.span.start,
4922                        MathMark {
4923                            tex,
4924                            display: node.kind == Kind::DisplayMath,
4925                            glyph: None,
4926                            rows: 1,
4927                        },
4928                    ));
4929                    out.push(Glyph {
4930                        ch: MATH_ATOM,
4931                        style: base.role(Role::Math),
4932                        src: node.span.start,
4933                        stop: true,
4934                    });
4935                } else {
4936                    self.inline_verbatim(id, base, out, false);
4937                }
4938            }
4939            // An attributed span — the run-level half of the presentation
4940            // vocabulary. djot's `[text]{…}`, AsciiDoc's `[.a]#text#`, HTML's
4941            // and Markdown's `<span …>`: one node with a name twig hands back
4942            // for two of the four (see [`is_run_span`]), all four carrying the
4943            // author's `data-size`, `data-font` and `data-color` on the run
4944            // they cover.
4945            //
4946            // The keys are written over the surrounding style rather than
4947            // replacing it, so a span inside a block that names its own size
4948            // wins on size and keeps the block's face — the nearest-wins rule
4949            // the block walker applies through a `div`. A key the span does not
4950            // name is one the block still says.
4951            //
4952            // A `data-color` here is the text's *foreground*, where the same key
4953            // on a `mark` is a highlight's background: same vocabulary, same
4954            // enum, and no collision, because a `mark` is a `mark` and a span is
4955            // a span.
4956            //
4957            // Otherwise this is the plain `recurse` an anonymous container has
4958            // always had — no delimiters, because the `{…}` is markup and the
4959            // span's text is the author's words.
4960            "container" if is_run_span(node) && !self.children(id).is_empty() => {
4961                self.recurse(id, run_style(node, base, &self.faces), out)
4962            }
4963            // A text directive (`:name[label]{…}`) — the inline form of a generic
4964            // directive. Its `[label]` children are the visible text; the name and
4965            // the `{…}` attributes are the host app's vocabulary (diaryx's
4966            // `:vis[…]`) and stay hidden markup, exactly as a link's `](dest)` is.
4967            // Drawn in the surrounding style: a role of its own would need one
4968            // every frontend maps, and the bug this fixes is that the text was
4969            // invisible, not that it was unstyled.
4970            "container" if container_is_directive(node) && !self.children(id).is_empty() => {
4971                self.recurse(id, base, out)
4972            }
4973            // No `[label]`, so there are no children to render and recursing
4974            // emitted *nothing*: the directive's bytes vanished from the document
4975            // and left no caret stop behind. What to draw instead turns on
4976            // whether the syntax looks deliberate.
4977            //
4978            // Bare `:word` almost never is. twig matches a colon followed by any
4979            // letter-led word (`scanTextDirective`, deliberately matching remark),
4980            // so ordinary prose is full of them — `:see below`, a `:smile:`
4981            // shortcode, a stray colon before a word. Those are prose, and prose
4982            // renders as itself: every byte visible, every byte a caret stop, so a
4983            // colon typed by accident can be seen and deleted. Hiding them behind
4984            // a placeholder would be the invisible-and-unreachable failure this
4985            // arm exists to fix, just wearing a nicer glyph.
4986            "container" if container_is_directive(node) && node.attrs.is_empty() => {
4987                let span = node.span.clone();
4988                push_text(
4989                    out,
4990                    self.source.get(span.clone()).unwrap_or(""),
4991                    span.start,
4992                    base,
4993                );
4994            }
4995            // `{…}` attributes, though, are unmistakably deliberate — nobody
4996            // types `:vis{.family}` by accident, and diaryx writes exactly that
4997            // inline. So an attribute-bearing directive with no label draws as a
4998            // chip on `block_directive`'s recipe (`⧉ name attrs`, `Role::Image`),
4999            // the inline peer of the leaf form's placeholder row.
5000            //
5001            // Only the first glyph is a caret stop, and the whole chip shares the
5002            // directive's start offset: the caret treats it as one atomic thing
5003            // rather than walking hidden markup a byte at a time, and a paragraph
5004            // holding nothing but a chip still has a stop to be navigated to.
5005            "container" if container_is_directive(node) => {
5006                let start = node.span.start;
5007                let name = node.name.clone().unwrap_or_default();
5008                let shown = match directive_attr_label(&node.attrs) {
5009                    Some(attrs) if !name.is_empty() => format!("⧉ {name} {attrs}"),
5010                    Some(attrs) => format!("⧉ {attrs}"),
5011                    None => format!("⧉ {name}"),
5012                };
5013                let style = base.role(Role::Image);
5014                for (i, ch) in shown.chars().enumerate() {
5015                    out.push(Glyph {
5016                        ch,
5017                        style,
5018                        src: start,
5019                        stop: i == 0,
5020                    });
5021                }
5022            }
5023            // A footnote reference (`[^1]`). The label bracketed is what a reader
5024            // needs — bare, `note1` reads as a typo rather than a reference — so
5025            // the `^` is hidden as the spelling artefact it is (a link's
5026            // `](dest)` goes the same way) and the brackets are kept as
5027            // decoration: one shared offset, never a caret stop, like a table's
5028            // borders, so the caret walks the label alone.
5029            //
5030            // Styled `Role::Link`: a reference *is* a link to its definition, and
5031            // every frontend already paints that role. A role of its own would
5032            // need one in each of them, and what a frontend needs to tell the two
5033            // apart is not a paint colour but an answer to "what does clicking
5034            // here do" — which is [`Doc::footnote_at_caret`]'s job, not a glyph's.
5035            //
5036            // Raised, though, because that a reference is *set* differently from
5037            // the prose it interrupts is exactly what makes it read as a
5038            // reference. `[1]` at body size reads as bracketed text.
5039            "footnote_reference" => {
5040                let style = base.role(Role::Link);
5041                // Revealed, the reference is just its source bytes: the `^` that
5042                // is normally elided comes back and every byte becomes a real
5043                // stop, so the brackets stop being decoration and start being
5044                // text. That's the whole point of the mode, and it replaces the
5045                // hand-built chip below rather than decorating it — including the
5046                // raised baseline, since what's on screen there is source, and
5047                // source is set as prose.
5048                if self.revealed(&node.span) {
5049                    self.push_delim(out, &node.span, style);
5050                    return;
5051                }
5052                let style = style.baseline(Baseline::Super);
5053                // The label's own span, so its glyphs map to their true bytes.
5054                // Absent one, it starts past the `[^` that opens the reference.
5055                let (label, at) = match &node.content_span {
5056                    Some(c) => (self.source.get(c.clone()).unwrap_or(""), c.start),
5057                    None => (node.text.as_deref().unwrap_or(""), node.span.start + 2),
5058                };
5059                out.push(Glyph {
5060                    ch: '[',
5061                    style,
5062                    src: node.span.start,
5063                    stop: false,
5064                });
5065                push_text(out, label, at, style);
5066                out.push(Glyph {
5067                    ch: ']',
5068                    style,
5069                    src: node.span.end.saturating_sub(1),
5070                    stop: false,
5071                });
5072            }
5073            "link" | "url" | "email" => {
5074                let style = base.role(Role::Link);
5075                if self.children(id).is_empty() {
5076                    // A bare autolink (`<a@b.c>`, a naked URL): the destination
5077                    // *is* the visible text, so there is nothing elided to
5078                    // reveal and both modes draw the same thing.
5079                    push_text(
5080                        out,
5081                        node.destination
5082                            .as_deref()
5083                            .or(node.text.as_deref())
5084                            .unwrap_or("link"),
5085                        node.span.start,
5086                        style,
5087                    );
5088                } else {
5089                    // An inline link reveals asymmetrically — `[` before the
5090                    // label, `](dest)` after it — which the generic
5091                    // span-minus-content derivation already produces.
5092                    self.inline_delimited(id, style, out);
5093                }
5094            }
5095            _ => {
5096                if self.children(id).is_empty() {
5097                    if let Some(t) = &node.text {
5098                        push_text(out, t, node.span.start, base);
5099                    }
5100                } else {
5101                    self.recurse(id, base, out);
5102                }
5103            }
5104        }
5105    }
5106
5107    fn recurse(&self, id: usize, style: Style, out: &mut Vec<Glyph>) {
5108        for c in self.children(id) {
5109            self.inline(c, style, out);
5110        }
5111    }
5112
5113    /// Lay a block's inline `glyphs` into visual rows, prefixing the first with
5114    /// `pf` and the rest with `pc`. A preserved soft break arrives as a `'\n'`
5115    /// glyph (see the `soft_break` arm): a hard row boundary that splits the
5116    /// glyphs so each run lays out on its own and the author's line structure
5117    /// shows on screen. The `'\n'` is dropped from the row it closes and its
5118    /// source offset becomes that row's end stop — exactly how a table cell's
5119    /// in-line `<br>` is handled — so the caret can rest at the line's end
5120    /// without a zero-width control char leaking into what the frontends render.
5121    /// With no `'\n'` present (the folding default, and every build that isn't
5122    /// `LineFlow::Preserve`) there is one run and this is byte-identical to
5123    /// laying the glyphs out directly.
5124    fn emit_wrapped(&mut self, glyphs: Vec<Glyph>, block_start: usize, pf: &[Glyph], pc: &[Glyph]) {
5125        if !glyphs.iter().any(|g| g.ch == '\n') {
5126            self.emit_line(glyphs, block_start, pf, pc, None);
5127            return;
5128        }
5129        // Each run up to a '\n' is a line of its own: the first wears the block's
5130        // opening prefix, every later one the continuation prefix, and the break's
5131        // own offset ends the run's last row. The break glyph is dropped. A
5132        // trailing '\n' flushes its run and leaves nothing behind, so no spurious
5133        // blank row follows it.
5134        let mut run: Vec<Glyph> = Vec::new();
5135        let mut first = true;
5136        for g in glyphs {
5137            if g.ch == '\n' {
5138                let lead = if first { pf } else { pc };
5139                self.emit_line(std::mem::take(&mut run), block_start, lead, pc, Some(g.src));
5140                first = false;
5141            } else {
5142                run.push(g);
5143            }
5144        }
5145        if !run.is_empty() {
5146            let lead = if first { pf } else { pc };
5147            self.emit_line(run, block_start, lead, pc, None);
5148        }
5149    }
5150
5151    /// Word-wrap a single line of `glyphs` (no interior line breaks) to the
5152    /// available width and push the visual rows, prefixing the first with `pf`
5153    /// and the rest with `pc`. `end`, when set, is the source offset that ends
5154    /// the line's final row — the offset of the break that terminated it, which
5155    /// the caller has already stripped from `glyphs`; when `None` the row ends
5156    /// just past its last glyph, as an unbroken block's does.
5157    fn emit_line(
5158        &mut self,
5159        glyphs: Vec<Glyph>,
5160        block_start: usize,
5161        pf: &[Glyph],
5162        pc: &[Glyph],
5163        end: Option<usize>,
5164    ) {
5165        // The line's final row ends at `end` when a break gave one, else just
5166        // past its last glyph (`push_row`'s default).
5167        let push_last = |b: &mut Self, row: Vec<Glyph>| match end {
5168            Some(e) => b.push_row_at(row, e),
5169            None => b.push_row(row, block_start),
5170        };
5171
5172        // No column budget: emit the whole line as one row and let the frontend
5173        // wrap it at its own (pixel) width.
5174        let Some(width) = self.wrap else {
5175            let row = if glyphs.is_empty() {
5176                pf.to_vec()
5177            } else {
5178                concat(pf, &glyphs)
5179            };
5180            push_last(self, row);
5181            return;
5182        };
5183
5184        // Split into words (maximal non-space runs), each carrying the space
5185        // glyph that followed it (so its source offset is preserved).
5186        let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
5187        let mut word: Vec<Glyph> = Vec::new();
5188        for g in glyphs {
5189            if g.ch == ' ' {
5190                words.push((std::mem::take(&mut word), Some(g)));
5191            } else {
5192                word.push(g);
5193            }
5194        }
5195        if !word.is_empty() {
5196            words.push((word, None));
5197        }
5198        if words.is_empty() {
5199            // An empty block (or an empty preserved line) still occupies one
5200            // (prefixed) row.
5201            push_last(self, pf.to_vec());
5202            return;
5203        }
5204
5205        let mut line: Vec<Glyph> = Vec::new();
5206        let mut used = 0usize;
5207        let mut first = true;
5208        for (w, space) in words {
5209            let avail = width
5210                .saturating_sub(prefix_width(if first { pf } else { pc }))
5211                .max(1);
5212            let cells = glyphs_width(&w);
5213            if used > 0 && used + cells > avail {
5214                let row = concat(if first { pf } else { pc }, &line);
5215                self.push_row(row, block_start);
5216                line = Vec::new();
5217                used = 0;
5218                first = false;
5219            }
5220            used += cells;
5221            line.extend(w);
5222            if let Some(sp) = space {
5223                used += 1;
5224                line.push(sp);
5225            }
5226        }
5227        let row = concat(if first { pf } else { pc }, &line);
5228        push_last(self, row);
5229    }
5230
5231    /// The source offset of each line of a code block's `text`.
5232    ///
5233    /// `content` is the block's `content_span` — where twig says the body lives
5234    /// in the source, fences already excluded. Its lines run 1:1 with the
5235    /// rendered `text` lines, so no search is needed; each is anchored at the
5236    /// *end* of its source line, which places it past whatever indent `text` had
5237    /// stripped (a fenced block's fences, an indented one's leading spaces)
5238    /// without having to know how much there was.
5239    ///
5240    /// `None` when the body and the rendered lines don't line up — a coarse
5241    /// fallback the caller turns into the block's start offset.
5242    fn code_line_offsets(&self, content: &Range<usize>, lines: &[&str]) -> Option<Vec<usize>> {
5243        let mut src_lines: Vec<(usize, &str)> = Vec::new();
5244        let mut at = content.start;
5245        for l in self.source.get(content.start..content.end)?.split('\n') {
5246            src_lines.push((at, l));
5247            at += l.len() + 1;
5248        }
5249        if src_lines.len() != lines.len() {
5250            return None;
5251        }
5252        Some(
5253            lines
5254                .iter()
5255                .zip(&src_lines)
5256                .map(|(l, (start, sl))| start + sl.len().saturating_sub(l.len()))
5257                .collect(),
5258        )
5259    }
5260
5261    fn push_row(&mut self, glyphs: Vec<Glyph>, fallback: usize) {
5262        // Step past the character the *source* holds at the last glyph's offset,
5263        // not past the glyph's own `ch`. The two agree for ordinary text, but a
5264        // glyph is not always the character it stands on: `synth` decoration and
5265        // a substituted run (an image's `⧉ label`) share one offset by design.
5266        // Trusting `ch` there yields an offset inside a multi-byte character,
5267        // which every later slice of `source` panics on.
5268        let end_src = glyphs
5269            .last()
5270            .map(|g| {
5271                let at = g.src.min(self.source.len());
5272                at + self.source[at..].chars().next().map_or(0, char::len_utf8)
5273            })
5274            .unwrap_or(fallback);
5275        self.push_row_at(glyphs, end_src);
5276    }
5277
5278    /// Push a row with an explicit end stop, for content that knows its own
5279    /// extent better than its last glyph does.
5280    fn push_row_at(&mut self, glyphs: Vec<Glyph>, end_src: usize) {
5281        self.last_off = end_src;
5282        let mark_ends = self.take_mark_ends(end_src);
5283        let math = self.take_math(&glyphs);
5284        self.rows.push(VRow {
5285            glyphs,
5286            end_src,
5287            decoration: false,
5288            code: false,
5289            code_lang: None,
5290            directive: false,
5291            directive_label: None,
5292            media: None,
5293            task: None,
5294            leaf_directive: None,
5295            heading: None,
5296            align: None,
5297            line_height: None,
5298            boundary: None,
5299            mark_ends,
5300            math,
5301        });
5302    }
5303
5304    /// Where the last row's line ends — what the lines under it are counted
5305    /// from: the row's own end, or the walk's where that stands short of it.
5306    /// Only a thematic break's does, whose row ends at the caret's home past
5307    /// the newline under the rule while the walk stands at the rule itself
5308    /// (see its arm). Every other block leaves the walk at its last row's end
5309    /// or past it — past a closing fence, say, which the counts below reach
5310    /// by other means.
5311    fn last_line_end(&self) -> Option<usize> {
5312        self.rows.last().map(|r| r.end_src.min(self.last_off))
5313    }
5314
5315    /// The quote's own trailing marker lines: the `>` / `> ` lines that lie past
5316    /// its last child but inside its span, one gutter row each.
5317    ///
5318    /// Pressing Enter at the end of `> a` writes `> a\n>\n> \n` — twig's
5319    /// spelling, and the right one. Those last two lines hold no block (a
5320    /// `block_quote`'s `content_span` still stops at its last child) so the
5321    /// children walk never reaches them, and they used to fall all the way to
5322    /// the document-level [`Builder::emit_trailing_blank_lines`], which knows no
5323    /// prefix: the gutter simply stopped, and a writer adding a line to a quote
5324    /// watched it draw as plain prose.
5325    ///
5326    /// This is only answerable since twig 3.2.0, where a Markdown `block_quote`'s
5327    /// span covers its own trailing marker lines (it reported `0..3` for that
5328    /// source and now reports `0..8`). Before that the lines belonged to no node
5329    /// at any level, and the only way to draw them was to sniff `>` off the raw
5330    /// source and re-derive the nesting depth by counting markers — format
5331    /// inference this crate exists to keep out of the render path.
5332    ///
5333    /// Each row is a real caret home rather than a decoration gap: the writer
5334    /// spelled every one of these lines with a marker of its own, so each is a
5335    /// line of the quote to stand on, not the spacing between two blocks (which
5336    /// is [`Builder::emit_separators_before`]'s, and falls *between* children
5337    /// where this never looks).
5338    fn emit_quote_trailing_lines(&mut self, pc: &[Glyph], end: usize) {
5339        let end = end.min(self.source.len());
5340        let mut at = self.last_line_end().unwrap_or(0);
5341        // Walk line by line from the last child's end to the quote's, taking each
5342        // line's *end* as the row's offset — the caret home at the end of a line
5343        // is where one on an empty quoted line belongs, and it keeps every row's
5344        // offset distinct from its neighbours'.
5345        while at < end {
5346            let Some(k) = self.source[at..end].find('\n') else {
5347                break;
5348            };
5349            let line_start = at + k + 1;
5350            let line_end = self.source[line_start..end]
5351                .find('\n')
5352                .map_or(end, |i| line_start + i);
5353            self.push_row_at(pc.to_vec(), line_end);
5354            at = line_end;
5355        }
5356    }
5357
5358    /// The source offset the caret rests at on the blank line separating a block
5359    /// that ends at `prev_end` from the next block starting at `next_start`:
5360    /// just past the newline that terminates the previous block, but kept
5361    /// strictly before the next block so the offset is unique to this row.
5362    fn blank_line_offset(&self, prev_end: usize, next_start: usize) -> usize {
5363        let after_nl = self.source[prev_end..]
5364            .find('\n')
5365            .map_or(prev_end, |p| prev_end + p + 1);
5366        after_nl.min(next_start.saturating_sub(1)).max(prev_end)
5367    }
5368
5369    /// The source offset of each blank row between a block ending at `prev_end`
5370    /// and content starting at `next_start` — one per blank source line. The
5371    /// first newline terminates the previous block's line; every line it opens up
5372    /// to (but not including) the line that holds `next_start` is a blank row the
5373    /// caret can occupy. Offsets are unique and ascending so `pos_of_offset`
5374    /// resolves each to its own row. Empty when the two blocks are tight (no
5375    /// blank line between them).
5376    fn blank_rows_between(&self, prev_end: usize, next_start: usize) -> Vec<usize> {
5377        // Spans aren't always in tidy source order (e.g. a block after
5378        // frontmatter can start *before* the previous block's rendered content
5379        // ends). There's no blank line to place then — fall back to the clamped
5380        // single separator (an empty return) rather than slicing an inverted
5381        // range.
5382        if next_start <= prev_end {
5383            return Vec::new();
5384        }
5385        let gap = &self.source[prev_end..next_start];
5386        let Some(nl) = gap.find('\n') else {
5387            return Vec::new();
5388        };
5389        // The line holding `next_start` belongs to the next block; blank rows
5390        // stop before it.
5391        let next_line_start = self.source[..next_start].rfind('\n').map_or(0, |p| p + 1);
5392        let mut offs = Vec::new();
5393        let mut start = prev_end + nl + 1;
5394        while start < next_line_start {
5395            offs.push(start);
5396            match self.source[start..next_start].find('\n') {
5397                Some(k) => start += k + 1,
5398                None => break,
5399            }
5400        }
5401        offs
5402    }
5403
5404    /// Blank lines the user typed past the end of the last block (e.g. two
5405    /// `Enter`s to open a fresh paragraph) leave no AST node, so nothing renders
5406    /// and the caret appears stuck on the old line. Reconstruct one empty row
5407    /// per extra trailing newline from the source, each at its own offset, so
5408    /// the caret rides down onto the new line the moment it's created.
5409    ///
5410    /// `above` is the class of the last block in the document — the one this gap
5411    /// closes. A document with no blocks at all has nothing above these rows, and
5412    /// [`BlockClass::Paragraph`] is the honest answer there too: what they are is
5413    /// empty paragraphs, on both sides of the gap.
5414    fn emit_trailing_blank_lines(&mut self, above: BlockClass, hidden_end: usize) {
5415        // With no rows at all the count starts past any hidden frontmatter, not
5416        // at 0: its newlines are not trailing blank lines, and counting them
5417        // opened phantom rows *inside* the metadata for a frontmatter-only file.
5418        //
5419        // Or past the last hidden block, if that is later: a closing comment
5420        // draws no row, and its lines are not blank lines the author opened.
5421        //
5422        // Or past the last byte of content, if *that* is later: a fenced code
5423        // block's last row ends at its last line of code, and the closing
5424        // fence under it is markup with no row of its own — so counted from
5425        // the row, the fence's own line and terminator read as two blank lines
5426        // and opened a phantom empty paragraph whose offset was *inside* the
5427        // fence. Typing on it broke the fence. (A setext heading's underline
5428        // was the same shape.) Trailing whitespace is not content, so a line
5429        // of spaces still counts as the blank line it looks like.
5430        let last_end = self
5431            .last_line_end()
5432            .unwrap_or(hidden_end)
5433            .max(self.stepped_over)
5434            .max(self.source.trim_end().len());
5435        if last_end >= self.source.len() {
5436            return;
5437        }
5438        // The first newline after the last content just terminates that line, so
5439        // a lone trailing `\n` (an ordinary file ending) opens no blank row. A
5440        // *second* newline opens an empty paragraph: render it the way a block
5441        // boundary is rendered — a blank spacer row, then the empty paragraph row
5442        // the caret rests on — so the just-pressed-Enter view already shows the
5443        // gap it will keep once text is typed, and typing doesn't shift the line
5444        // down. One row per trailing newline (each its own caret offset), the
5445        // last landing at the document end where the caret sits.
5446        let extra = self.source[last_end..].matches('\n').count();
5447        if extra < 2 {
5448            return;
5449        }
5450        for k in 1..=extra {
5451            self.rows.push(VRow {
5452                glyphs: Vec::new(),
5453                end_src: last_end + k,
5454                // As between two blocks: the first blank row is the gap that
5455                // closes the block above, not somewhere to type. Nothing follows
5456                // to need a gap of its own, though, so every row after it is a
5457                // real empty paragraph — the end of the document bounds the last
5458                // one the way a following block would. Preserve flow makes even
5459                // that first row navigable, as it does every blank line.
5460                decoration: !self.preserve_soft && k == 1,
5461                code: false,
5462                code_lang: None,
5463                directive: false,
5464                directive_label: None,
5465                media: None,
5466                task: None,
5467                leaf_directive: None,
5468                heading: None,
5469                align: None,
5470                line_height: None,
5471                // The one drawn row here is a block boundary like any other —
5472                // "rendered the way a block boundary is rendered" is the whole
5473                // point of it — so it says so, and a frontend spacing boundaries
5474                // spaces this one the same. The rows below it are navigable empty
5475                // paragraphs, not gaps.
5476                boundary: (!self.preserve_soft && k == 1).then_some(Boundary {
5477                    above,
5478                    below: BlockClass::Paragraph,
5479                }),
5480                mark_ends: Vec::new(),
5481                math: Vec::new(),
5482            });
5483        }
5484    }
5485}
5486
5487// ── display width ────────────────────────────────────────────────────────────
5488//
5489// Two things a row can be counted in, and they are not the same number:
5490//
5491//   *glyphs*, one per codepoint — how the text is stored here, and what an
5492//   index into `VRow::glyphs` means; and
5493//   *columns*, one per terminal cell — where the text is drawn, and what every
5494//   `col` in this crate means.
5495//
5496// `你` is one glyph in two columns. Counting columns with `glyphs.len()` (or,
5497// in the source view, `chars().count()`) is the same number only for the ASCII
5498// that most fixtures are written in, and drifts one cell per wide character
5499// everywhere else — the caret drawn a column short of the text it types into.
5500// Everything below converts between the two; nothing else should have to.
5501
5502/// The display width of `s` in terminal cells.
5503///
5504/// Measured per grapheme cluster, because that is the unit a surface advances
5505/// by: `👨‍👩‍👧` is five codepoints measuring 2 + 0 + 2 + 0 + 2 cells one at a
5506/// time, but the character they spell is drawn in 2. Both frontends already
5507/// measure it that way — ratatui asks `unicode-width` per cluster, and the GUI
5508/// asks its own text system — so the caret only lands where the text is if this
5509/// agrees with them.
5510pub fn text_width(s: &str) -> usize {
5511    UnicodeWidthStr::width(s)
5512}
5513
5514/// One grapheme cluster of a laid-out row: the glyphs that spell it, and the
5515/// cells it is drawn in.
5516///
5517/// The cluster, not the glyph, is what has a width. A row's glyphs are one per
5518/// codepoint, so an accented letter or an emoji is several of them drawn in one
5519/// character's worth of cells — the glyph that opens the cluster claims those
5520/// cells, and the ones continuing it are drawn *inside* them rather than beside
5521/// them. It's the same cluster the stop table is built on: the opening glyph is
5522/// the one a caret can rest on, and so the only one whose column it can be
5523/// drawn at.
5524struct Cluster {
5525    /// Index of the glyph that opens it.
5526    glyph: usize,
5527    /// The display column it starts at.
5528    col: usize,
5529    /// How many cells it is drawn in. Zero for a cluster with no width of its
5530    /// own (a lone joiner), which therefore sits at no column at all.
5531    cells: usize,
5532}
5533
5534/// Walk a row's glyphs as the clusters they spell, in column order.
5535fn clusters(glyphs: &[Glyph]) -> Vec<Cluster> {
5536    let text: String = glyphs.iter().map(|g| g.ch).collect();
5537    let mut out = Vec::new();
5538    let (mut glyph, mut col) = (0, 0);
5539    for cluster in text.graphemes(true) {
5540        let cells = text_width(cluster);
5541        out.push(Cluster { glyph, col, cells });
5542        // One glyph per codepoint, so a cluster spans exactly its own.
5543        glyph += cluster.chars().count();
5544        col += cells;
5545    }
5546    out
5547}
5548
5549/// The display width of a run of glyphs.
5550fn glyphs_width(glyphs: &[Glyph]) -> usize {
5551    clusters(glyphs).last().map_or(0, |c| c.col + c.cells)
5552}
5553
5554/// A cell's display width — the widest of its lines, since an in-cell `\n` break
5555/// splits it into several. Sizes the column that must hold every line.
5556fn cell_width(glyphs: &[Glyph]) -> usize {
5557    glyphs
5558        .split(|g| g.ch == '\n')
5559        .map(glyphs_width)
5560        .max()
5561        .unwrap_or(0)
5562}
5563
5564/// Whether a raw inline HTML tag is a line break (`<br>`, `<br/>`, `<br />`,
5565/// case-insensitively) — the one tag a table cell reads as an in-cell break.
5566fn is_br(text: Option<&str>) -> bool {
5567    let Some(t) = text else { return false };
5568    matches!(
5569        t.trim().to_ascii_lowercase().replace(' ', "").as_str(),
5570        "<br>" | "<br/>"
5571    )
5572}
5573
5574impl VRow {
5575    /// The row's width in display columns — and so the column of the caret
5576    /// placed past its last glyph, which is the rightmost column it can occupy.
5577    fn width(&self) -> usize {
5578        glyphs_width(&self.glyphs)
5579    }
5580
5581    /// The display column glyph `i` is drawn at. Glyphs continuing a cluster
5582    /// report the column of the glyph that opened it, since that is where they
5583    /// are drawn; none of them is ever a stop, so no caret is placed by it.
5584    fn col_of_glyph(&self, i: usize) -> usize {
5585        clusters(&self.glyphs)
5586            .iter()
5587            .rev()
5588            .find(|c| c.glyph <= i)
5589            .map_or(0, |c| c.col)
5590    }
5591
5592    /// The glyph drawn at display column `col`, or `None` past the row's last
5593    /// cell.
5594    ///
5595    /// A column landing on the *second* cell of a wide glyph resolves to that
5596    /// glyph: half a character is not a place to be, so clicking either cell of
5597    /// `你` means `你`, and the caret comes to rest at its start — the column it
5598    /// would be drawn at anyway. That rule is what makes the mapping invertible:
5599    /// every offset has one column, and every column has one offset.
5600    fn glyph_at_col(&self, col: usize) -> Option<usize> {
5601        clusters(&self.glyphs)
5602            .into_iter()
5603            .find(|c| col < c.col + c.cells)
5604            .map(|c| c.glyph)
5605    }
5606}
5607
5608// ── helpers ──────────────────────────────────────────────────────────────────
5609
5610/// The caret home inside an *empty* table cell (`col`, 0-based) whose node
5611/// `span` is `src` starting at byte `start`. twig gives an empty cell no
5612/// `content_span`, so its interior is read from the pipes: the home is one
5613/// space past the pipe that opens the cell — mimicking the `| ` padding a
5614/// filled cell has — and never at or past the pipe that closes it. So
5615/// `|  |  |` gives the two cells distinct, editable homes instead of both
5616/// collapsing onto the row's start.
5617///
5618/// Two shapes of span are read. A twig from 3.3.3 gave every cell of a row
5619/// the *row's* span, so the cell's own pipes are the `col`-th and
5620/// `col+1`-th unescaped `|` in it; a later twig spans a cell from the pipe
5621/// that opens it to the one that closes it, exclusive, so the span holds at
5622/// most that one pipe, at its start, and the closing one is the byte past
5623/// its end. The two are told apart by the pipes the span holds — a row's
5624/// span has several, or one that is not at its start.
5625fn empty_cell_offset(src: &str, start: usize, col: usize) -> usize {
5626    let bytes = src.as_bytes();
5627    let mut pipes = Vec::new();
5628    for (i, &b) in bytes.iter().enumerate() {
5629        if b == b'|' && (i == 0 || bytes[i - 1] != b'\\') {
5630            pipes.push(i);
5631        }
5632    }
5633    let whole_row = pipes.len() > 1 || pipes.first().is_some_and(|&i| i != 0);
5634    let (open, close) = if whole_row {
5635        (pipes.get(col).copied(), pipes.get(col + 1).copied())
5636    } else {
5637        (pipes.first().copied(), Some(src.len()))
5638    };
5639    match (open, close) {
5640        (Some(open), Some(close)) => {
5641            let lo = open + 1; // just inside the opening pipe
5642            let hi = close.saturating_sub(1); // just inside the closing pipe
5643            let inside = if hi < lo {
5644                lo
5645            } else {
5646                (open + 2).clamp(lo, hi)
5647            };
5648            start + inside
5649        }
5650        (Some(open), None) => start + open + 1,
5651        _ => start,
5652    }
5653}
5654
5655/// One laid-out table cell: its rendered text, the source range that text
5656/// occupies (`start`/`end` are the caret anchors decoration points at), and the
5657/// column alignment its padding honours.
5658///
5659/// `glyphs` is the cell's inline content *unwrapped* — the box-drawn rows wrap
5660/// it to a column width, but a frontend laying the grid out itself needs the
5661/// text before that decision was made.
5662#[derive(Clone)]
5663pub struct TableCell {
5664    pub glyphs: Vec<Glyph>,
5665    pub start: usize,
5666    pub end: usize,
5667    pub align: Alignment,
5668}
5669
5670/// One row of a table's grid, as the document spells it — not as it's drawn.
5671#[derive(Clone)]
5672pub struct TableRow {
5673    /// A header row: drawn bold, and ruled off from the body below it.
5674    pub head: bool,
5675    pub cells: Vec<TableCell>,
5676}
5677
5678/// A table's structure, published alongside the box-drawn rows that spell it.
5679///
5680/// The rows in [`VisualMap::rows`] are the *default monospace* picture of a
5681/// table: every border a `│`, every column a whole number of character cells.
5682/// That picture is exactly right on any monospace surface, and unfixable off one
5683/// — in a proportional font the `│`s of two rows land at different x and the grid
5684/// shears. So a frontend that draws its own geometry reads this instead: the
5685/// cells, their alignment, and which rows are the head, with no opinion about
5686/// how wide a column is or what a border looks like.
5687///
5688/// Both are always built. The TUI paints `rows` and ignores this; the GUI skips
5689/// `rows` for the span in `rows_span` and draws from here. They describe the
5690/// same cells, so the caret lands on the same offsets either way.
5691#[derive(Clone)]
5692pub struct TableInfo {
5693    /// The `VisualMap::rows` this table's picture occupies, borders included —
5694    /// what a frontend drawing its own table skips over.
5695    pub rows_span: Range<usize>,
5696    /// The end of the table node's source span, and the offset its trailing
5697    /// caret stop sits at — the one caret home past the last cell, held by the
5698    /// bottom border row's end. Typing there opens a paragraph under the table
5699    /// rather than joining the block; see `Doc::open_paragraph_at_block_edge`.
5700    pub end_src: usize,
5701    /// The block prefix every row of this table carries — a blockquote's `│ `
5702    /// gutter, a list item's indent. Empty for a table at the top level.
5703    ///
5704    /// A frontend drawing its own grid has to render this and start the table
5705    /// past it, exactly as the picture does; a table nested in a quote that
5706    /// draws flush at the left margin has left the quote.
5707    pub prefix: Vec<Glyph>,
5708    pub grid: Vec<TableRow>,
5709}
5710
5711/// A fenced or indented code block, named by the [`VisualMap::rows`] it occupies.
5712///
5713/// Unlike a table, the rows *are* the block's content — a frontend still paints
5714/// them, it just draws a border and a tinted background around the whole span
5715/// and lets the code inside scroll horizontally instead of wrapping. So this
5716/// carries only the row range; there's no structural alternative to the picture
5717/// the way [`TableInfo`] is one. Derived from [`VRow::code`] — see
5718/// [`code_block_spans`].
5719#[derive(Clone, Debug, PartialEq, Eq)]
5720pub struct CodeBlockInfo {
5721    /// The contiguous run of [`VisualMap::rows`] this code block spans, blank
5722    /// code lines included.
5723    pub rows_span: Range<usize>,
5724    /// The block's language, from a fenced block's info string — what a frontend
5725    /// paints as a small label on the box (`` ```rust `` → `Some("rust")`).
5726    /// `None` for a fence written without one, or an indented block. Editing it
5727    /// goes through [`crate::Doc::set_code_language`], which re-finds the fence
5728    /// in the AST, so this stays a display string.
5729    pub lang: Option<String>,
5730}
5731
5732/// A block-level image (`![alt](url)` on its own line), named by the single
5733/// [`VisualMap::rows`] row it occupies.
5734///
5735/// Like [`CodeBlockInfo`], the row *is* the block's default rendering — a plain
5736/// surface paints the `🖼 alt` placeholder glyphs as-is. An image-capable
5737/// frontend instead **skips the row in `rows_span`** and paints the resolved
5738/// picture there, exactly as it skips a [`TableInfo`]'s box-drawn rows. Derived
5739/// from [`VRow::media`] by [`media_spans`], so it survives the row reuse of
5740/// [`BlockCache`] and [`build_spliced`].
5741#[derive(Clone, Debug, PartialEq, Eq)]
5742pub struct MediaInfo {
5743    /// The [`VisualMap::rows`] rows this media's placeholder occupies — what a
5744    /// capable frontend replaces with the picture or player.
5745    pub rows_span: Range<usize>,
5746    /// Whether this is a picture, a movie, or a sound — which widget the
5747    /// frontend builds over [`rows_span`](MediaInfo::rows_span). A frontend that
5748    /// handles only some kinds leaves the rest as core's placeholder rows, which
5749    /// already read sensibly on their own.
5750    pub kind: MediaKind,
5751    /// The media's link destination — a path, URL, or `data:` URI, verbatim from
5752    /// the AST. A frontend resolves a relative path against the document's own
5753    /// directory; core does no I/O. For a `<picture>` this is the `<img>`
5754    /// fallback — the source used when no [`sources`](MediaInfo::sources) media
5755    /// query matches (or the frontend has no theme). Empty when a `<video>`/
5756    /// `<audio>` carries no `src` and names its candidates in `<source>`s
5757    /// instead; [`resolve`](MediaInfo::resolve) already accounts for that.
5758    pub destination: String,
5759    /// The `<source>` alternatives in document order, or empty for a plain
5760    /// image. See [`MediaSource`]; a theme- or codec-aware frontend picks one and
5761    /// otherwise loads [`destination`](MediaInfo::destination).
5762    pub sources: Vec<MediaSource>,
5763    /// The media's alt text, flattened from its inline children (empty when it
5764    /// has none).
5765    pub alt: String,
5766    /// A `<video poster="…">`'s still frame, or empty when there is none — an
5767    /// image destination, resolved exactly as [`destination`] is.
5768    ///
5769    /// [`destination`]: MediaInfo::destination
5770    pub poster: String,
5771}
5772
5773/// One leaf directive (`::name{…}`) as a frontend sees it: which rows its
5774/// placeholder occupies, its type, and its attributes. A plain surface paints
5775/// the `⧉ name` placeholder glyphs as-is; a frontend that knows the host app's
5776/// vocabulary **skips the rows in `rows_span`** and paints the real thing there,
5777/// exactly as an image-capable one does with [`MediaInfo`]. Derived from
5778/// [`VRow::leaf_directive`] by [`directive_spans`].
5779///
5780/// Core resolves nothing here — it has no idea what an `embed` or a `toc` is,
5781/// and deliberately so: the directive vocabulary belongs to the app on top.
5782#[derive(Clone, Debug, PartialEq, Eq)]
5783pub struct DirectiveInfo {
5784    /// The [`VisualMap::rows`] rows this directive's placeholder occupies — the
5785    /// label row plus any blank fillers under it.
5786    pub rows_span: Range<usize>,
5787    /// The directive's type (`embed`, `toc`, `vis`), no leading colons.
5788    pub name: String,
5789    /// Its `{…}` attributes in source order; a bare one has a `None` value.
5790    pub attrs: Vec<(String, Option<String>)>,
5791    /// Its `[label]` text, flattened from its inline children (empty when it has
5792    /// none) — what the placeholder row shows.
5793    pub label: String,
5794}
5795
5796/// One formula as a frontend sees it: where its picture goes, and the TeX to
5797/// typeset for it. Two shapes, told apart by [`glyph`](MathInfo::glyph):
5798///
5799/// - An **inline atom** — `$E = mc^2$` in a line of prose — is one
5800///   [`Role::Math`] glyph on `row` at index `glyph`, standing for the whole
5801///   formula. A frontend that paints pictures in a line typesets the TeX at
5802///   the run's font size and draws the picture in the glyph's place, as wide
5803///   as the picture is and with the text baseline through it at its height —
5804///   a run delegate on Apple, an inline element on the web. The glyph is a
5805///   caret stop at the formula's start; the stop after it is the next glyph's.
5806/// - A **display block** — a paragraph holding nothing but `$$…$$` — is the
5807///   placeholder row (`∑ tex`, every glyph at the formula's start) plus the
5808///   blank fillers `rows_span` reserves under it, exactly a [`MediaInfo`]'s
5809///   shape. A frontend skips those rows and paints the picture there, centred
5810///   on the measure.
5811///
5812/// Either way the frontend supplies the *width*: core lays out in glyphs and
5813/// cannot know how wide a typeset formula is, which is why an inline atom is
5814/// one glyph and not a run of them. Only in a **column-wrapped** build does
5815/// that matter to the wrap: a terminal never asks for atoms (see
5816/// [`Surface::inline_pictures`]), and the web re-fits a row the picture
5817/// overflows.
5818///
5819/// A plain surface paints the glyphs as they are — `∑` for an atom, the
5820/// labelled row for a block — and needs none of this. Derived from
5821/// [`VRow::math`] by [`math_spans`], so it survives the row reuse of
5822/// [`BlockCache`] and [`build_spliced`].
5823#[derive(Clone, Debug, PartialEq, Eq)]
5824pub struct MathInfo {
5825    /// The [`VisualMap::rows`] rows this formula occupies: `row..row + 1` for
5826    /// an atom, the placeholder row and its fillers for a block.
5827    pub rows_span: Range<usize>,
5828    /// The row the atom glyph, or the block's placeholder label, is on.
5829    pub row: usize,
5830    /// The atom's index into that row's glyphs, or `None` for a block.
5831    pub glyph: Option<usize>,
5832    /// The TeX between the delimiters, verbatim.
5833    pub tex: String,
5834    /// Display style rather than text style — see [`MathMark::display`].
5835    pub display: bool,
5836    /// The formula's source start: where a click on its picture lands the
5837    /// caret, and the same offset every placeholder glyph carries.
5838    pub src: usize,
5839}
5840
5841impl DirectiveInfo {
5842    /// The value of attribute `key`, if it has one with a value. The convenience
5843    /// a frontend reaches for first (`info.attr("src")`), since almost every
5844    /// directive that draws as something real is pointed at by one attribute.
5845    pub fn attr(&self, key: &str) -> Option<&str> {
5846        self.attrs
5847            .iter()
5848            .find(|(k, _)| k == key)
5849            .and_then(|(_, v)| v.as_deref())
5850    }
5851}
5852
5853impl MediaInfo {
5854    /// The image URL to load under `scheme`: the first [`sources`] `<source>`
5855    /// whose media query matches, else the [`destination`] `<img>` fallback. The
5856    /// pick is a `<source>`'s first `srcset` URL or the destination — a frontend
5857    /// resolves whichever it gets against the document directory exactly as it
5858    /// resolves `destination`, and reserves/keys the picture under `destination`
5859    /// regardless, so a theme switch just re-picks without disturbing the layout.
5860    ///
5861    /// Only `prefers-color-scheme` is understood (that's what a light/dark banner
5862    /// uses); a `<source>` with any other media query is skipped, and one with no
5863    /// media at all always matches (an unconditional override). With no matching
5864    /// source — including every frontend that can't/doesn't theme and passes
5865    /// [`ColorScheme::Light`] to a dark-only picture — it's the plain `<img>`.
5866    ///
5867    /// [`sources`]: MediaInfo::sources
5868    /// [`destination`]: MediaInfo::destination
5869    pub fn resolve(&self, scheme: ColorScheme) -> &str {
5870        if let Some(url) = self
5871            .sources
5872            .iter()
5873            .find(|s| media_matches(&s.media, scheme))
5874            .and_then(|s| first_srcset_url(&s.srcset))
5875        {
5876            return url;
5877        }
5878        // A `<video>`/`<audio>` may carry no `src` of its own, naming its
5879        // candidates only in child `<source>`s — none of which matched above,
5880        // because a codec-typed `<source>` has no media query and core judges no
5881        // MIME types. Falling through to an empty destination would hand the
5882        // frontend nothing to load, so take the first candidate URL instead and
5883        // let the frontend reject it if it can't decode it. An `<img>` never
5884        // reaches this: its `src` is the picture.
5885        if self.destination.is_empty()
5886            && let Some(url) = self
5887                .sources
5888                .iter()
5889                .find_map(|s| first_srcset_url(&s.srcset))
5890        {
5891            return url;
5892        }
5893        &self.destination
5894    }
5895
5896    /// The **still picture** that stands for this media under `scheme`, for a
5897    /// frontend that can rasterize an image but not play a movie — a terminal, or
5898    /// a GUI still growing its player. `None` when there is no picture to draw,
5899    /// which is the honest answer for audio and for a poster-less video: the
5900    /// caller leaves core's labelled placeholder row, which already reads as
5901    /// *a thing that isn't text*.
5902    ///
5903    /// This exists so those frontends never hand a `.mp4` to an image decoder.
5904    /// That fails harmlessly today (a failed decode falls back to the same
5905    /// placeholder), but it spends a file read and a decode attempt per frame to
5906    /// arrive where this gets in one match.
5907    pub fn still(&self, scheme: ColorScheme) -> Option<&str> {
5908        match self.kind {
5909            MediaKind::Image => Some(self.resolve(scheme)),
5910            // A `poster` is an image destination, so it resolves the same way —
5911            // but it is named directly and has no `<source>` alternatives of its
5912            // own, so it needs no theme matching.
5913            MediaKind::Video if !self.poster.is_empty() => Some(&self.poster),
5914            MediaKind::Video | MediaKind::Audio => None,
5915        }
5916    }
5917}
5918
5919/// A frontend's active color scheme — what a `<picture>`'s `prefers-color-scheme`
5920/// `<source>`s are matched against by [`MediaInfo::resolve`]. A frontend with no
5921/// notion of theme passes [`Light`](ColorScheme::Light), the web's own default.
5922#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5923pub enum ColorScheme {
5924    Light,
5925    Dark,
5926}
5927
5928/// Whether a `<source media="…">` query applies under `scheme`. Empty media is
5929/// an unconditional `<source>` (always matches); otherwise only a
5930/// `prefers-color-scheme: dark|light` feature is understood — anything else
5931/// (a width query, `print`, …) doesn't match, so resolution falls through to the
5932/// next source or the `<img>`. Deliberately lax about the surrounding syntax
5933/// (`(prefers-color-scheme: dark)`, `screen and (prefers-color-scheme:dark)`):
5934/// it keys off the feature and its value, which is all the theme case needs.
5935fn media_matches(media: &str, scheme: ColorScheme) -> bool {
5936    let media = media.trim();
5937    if media.is_empty() {
5938        return true;
5939    }
5940    let lower = media.to_ascii_lowercase();
5941    let Some(after) = lower
5942        .split_once("prefers-color-scheme")
5943        .map(|(_, rest)| rest)
5944    else {
5945        return false;
5946    };
5947    // Skip the `:` and any spaces to reach the value word.
5948    let value = after.trim_start_matches([':', ' ', '\t']);
5949    let wanted = match scheme {
5950        ColorScheme::Light => "light",
5951        ColorScheme::Dark => "dark",
5952    };
5953    value.starts_with(wanted)
5954}
5955
5956/// The first URL in a `srcset`: its first comma-separated candidate, before any
5957/// `1x`/`2x`/width descriptor. The theme case only ever puts one URL per
5958/// `<source>`, so the first candidate is the picture.
5959fn first_srcset_url(srcset: &str) -> Option<&str> {
5960    let first = srcset.split(',').next()?.trim();
5961    first.split_whitespace().next().filter(|u| !u.is_empty())
5962}
5963
5964/// The narrowest a column may be squeezed. Below a few characters a column
5965/// stops carrying text and just shreds it one letter per line, which is worse
5966/// than letting the grid run wide.
5967const MIN_COL_WIDTH: usize = 3;
5968
5969/// Shrink `widths` until the grid fits `avail` screen columns, taking from the
5970/// widest column each time so the loss is shared out rather than falling on
5971/// whichever column happens to be last. No column goes below
5972/// [`MIN_COL_WIDTH`]; a table with more columns than the surface has room for
5973/// still overflows, which is the honest outcome — there's nothing left to give.
5974fn fit_widths(widths: &mut [usize], avail: usize) {
5975    // Chrome: each column is its content plus a gutter either side, and every
5976    // column is closed by a `│` — with one more opening the row.
5977    let budget = avail.saturating_sub(3 * widths.len() + 1);
5978    while widths.iter().sum::<usize>() > budget {
5979        let Some(w) = widths.iter_mut().filter(|w| **w > MIN_COL_WIDTH).max() else {
5980            return;
5981        };
5982        *w -= 1;
5983    }
5984}
5985
5986/// Word-wrap `glyphs` into lines of at most `width` columns, hard-breaking any
5987/// single word too long to fit.
5988///
5989/// Unlike a paragraph — where an overlong word just trails off the end of the
5990/// line — a table column is a hard boundary: a glyph past it lands on top of
5991/// the border, or on the next cell. So the width here is a promise, and a word
5992/// that won't keep it is broken.
5993///
5994/// The space at a break is dropped rather than hung past the edge. Its offset
5995/// isn't lost: the caller gives every line an end stop just past its last
5996/// glyph, which is exactly where that space was.
5997///
5998/// `width` is in display columns, and a break only ever falls between grapheme
5999/// clusters. Both matter to more than the picture: the caller anchors each
6000/// line's end stop just past its last glyph, so a line cut mid-cluster would
6001/// put a caret stop inside a character — reachable by Down or a click, and the
6002/// next Backspace would take the cluster apart from the middle.
6003///
6004/// An explicit in-cell break (a `\n` glyph, from a `<br>`) is a hard boundary:
6005/// each run between the breaks wraps on its own and the results stack. The break
6006/// glyphs are dropped — the caller's per-line end stop already sits exactly where
6007/// each break was, so no offset is lost.
6008fn wrap_glyphs(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
6009    if glyphs.iter().any(|g| g.ch == '\n') {
6010        return glyphs
6011            .split(|g| g.ch == '\n')
6012            .flat_map(|seg| wrap_segment(seg, width))
6013            .collect();
6014    }
6015    wrap_segment(glyphs, width)
6016}
6017
6018/// [`wrap_glyphs`] for a run with no explicit breaks — the word-wrap proper.
6019fn wrap_segment(glyphs: &[Glyph], width: usize) -> Vec<Vec<Glyph>> {
6020    let width = width.max(1);
6021    // Words are maximal non-space runs, each carrying the space that followed it
6022    // — which survives only if the next word joins it on this line.
6023    let mut words: Vec<(Vec<Glyph>, Option<Glyph>)> = Vec::new();
6024    let mut word: Vec<Glyph> = Vec::new();
6025    for g in glyphs {
6026        if g.ch == ' ' {
6027            words.push((std::mem::take(&mut word), Some(g.clone())));
6028        } else {
6029            word.push(g.clone());
6030        }
6031    }
6032    if !word.is_empty() {
6033        words.push((word, None));
6034    }
6035
6036    let mut lines: Vec<Vec<Glyph>> = Vec::new();
6037    let mut line: Vec<Glyph> = Vec::new();
6038    let mut used = 0usize;
6039    let mut gap: Option<Glyph> = None;
6040    for (word, space) in words {
6041        for chunk in hard_break(&word, width) {
6042            let sep = gap.is_some() as usize;
6043            let cells = glyphs_width(chunk);
6044            if !line.is_empty() && used + sep + cells > width {
6045                lines.push(std::mem::take(&mut line));
6046                used = 0;
6047                gap = None; // the break swallows the space
6048            }
6049            if let Some(sp) = gap.take() {
6050                line.push(sp);
6051                used += 1;
6052            }
6053            line.extend_from_slice(chunk);
6054            used += cells;
6055        }
6056        gap = space;
6057    }
6058    // An empty cell is still one (empty) line — it has an end the caret can
6059    // sit at, which is how you type into it.
6060    if !line.is_empty() || lines.is_empty() {
6061        lines.push(line);
6062    }
6063    lines
6064}
6065
6066/// Break a single word into pieces of at most `width` columns, cutting only
6067/// between grapheme clusters — the replacement for slicing it into fixed runs
6068/// of glyphs, which measures a wide character as one column and can cut an
6069/// emoji in half.
6070///
6071/// A cluster wider than the whole column still gets a piece to itself: there is
6072/// nowhere legal to cut it, and overflowing by a cell is better than splitting a
6073/// character. An empty word yields no pieces at all, which is what keeps a
6074/// double space from opening a line of its own.
6075fn hard_break(word: &[Glyph], width: usize) -> Vec<&[Glyph]> {
6076    let mut out = Vec::new();
6077    if word.is_empty() {
6078        return out;
6079    }
6080    let (mut start, mut used) = (0usize, 0usize);
6081    for c in clusters(word) {
6082        if used > 0 && used + c.cells > width {
6083            out.push(&word[start..c.glyph]);
6084            start = c.glyph;
6085            used = 0;
6086        }
6087        used += c.cells;
6088    }
6089    out.push(&word[start..]);
6090    out
6091}
6092
6093/// A table rule spanning `widths`, e.g. `┌──────┬─────┐`. Each column is its
6094/// content width plus the one-space gutter on either side.
6095fn rule_text(widths: &[usize], left: char, mid: char, right: char) -> String {
6096    let mut s = String::new();
6097    s.push(left);
6098    for (i, w) in widths.iter().enumerate() {
6099        if i > 0 {
6100            s.push(mid);
6101        }
6102        for _ in 0..w + 2 {
6103            s.push('─');
6104        }
6105    }
6106    s.push(right);
6107    s
6108}
6109
6110/// Push real document text: each glyph maps to its own source byte, and the one
6111/// that opens a grapheme cluster is the caret stop for the whole cluster.
6112///
6113/// Per cluster rather than per codepoint because a cluster is the character the
6114/// user sees, and it's the unit backspace and delete already step by. A stop
6115/// inside 👨‍👩‍👧 — five codepoints strung together with joiners — is a caret
6116/// parked in the middle of a character: one press of Right lands there, and the
6117/// next Backspace severs a joiner from what it joined, leaving a dangling ZWJ in
6118/// the source. The rest of the cluster still gets its glyph (it has to be
6119/// drawn); it just isn't somewhere to stand.
6120fn push_text(out: &mut Vec<Glyph>, text: &str, base_src: usize, style: Style) {
6121    for (gi, cluster) in text.grapheme_indices(true) {
6122        for (ci, ch) in cluster.char_indices() {
6123            out.push(Glyph {
6124                ch,
6125                style,
6126                src: base_src + gi + ci,
6127                stop: ci == 0,
6128            });
6129        }
6130    }
6131}
6132
6133/// [`push_text`] for one line of a highlighted code block: the same glyphs at
6134/// the same offsets, each additionally carrying the [`Token`] of the span it
6135/// falls in — `spans` being the line's entry from [`code_tokens`], ascending
6136/// byte ranges *into `text`*. A byte between spans keeps `style` as it is.
6137///
6138/// Offsets are what matters here: a token changes how a glyph is painted and
6139/// nothing about where it is or which source byte it stands on, so a caret
6140/// walks a highlighted block exactly as it walks an unhighlighted one.
6141fn push_code_text(
6142    out: &mut Vec<Glyph>,
6143    text: &str,
6144    base_src: usize,
6145    style: Style,
6146    spans: &[(Range<usize>, Token)],
6147) {
6148    let mut spans = spans.iter().peekable();
6149    for (gi, cluster) in text.grapheme_indices(true) {
6150        // Spans are ascending, so the one covering this cluster's first byte
6151        // is at or after the one that covered the last; step past those ended.
6152        while spans.peek().is_some_and(|(r, _)| r.end <= gi) {
6153            spans.next();
6154        }
6155        let token = spans
6156            .peek()
6157            .filter(|(r, _)| r.contains(&gi))
6158            .map(|(_, t)| *t);
6159        // A cluster is classed whole, by its first byte: a grammar that split
6160        // an emoji's scalars between two tokens would otherwise split the
6161        // glyph, and no grammar means to.
6162        let style = style.token(token);
6163        for (ci, ch) in cluster.char_indices() {
6164            out.push(Glyph {
6165                ch,
6166                style,
6167                src: base_src + gi + ci,
6168                stop: ci == 0,
6169            });
6170        }
6171    }
6172}
6173
6174/// One line's highlighting — `crate::syntax::LineTokens`, spelled here so the
6175/// shape exists whether or not the feature that fills it does.
6176type LineTokens = Vec<(Range<usize>, Token)>;
6177
6178/// The syntax highlighting for a code block's lines, or `None` when the fence's
6179/// language is not one the grammars know. Without the `syntax` feature nothing
6180/// is known, and every code glyph draws in the plain code colour.
6181#[cfg(feature = "syntax")]
6182fn code_tokens(lang: &str, lines: &[&str]) -> Option<Vec<LineTokens>> {
6183    crate::syntax::highlight(lang, lines)
6184}
6185
6186#[cfg(not(feature = "syntax"))]
6187fn code_tokens(_lang: &str, _lines: &[&str]) -> Option<Vec<LineTokens>> {
6188    None
6189}
6190
6191/// Emit an inline `str`/`smart_punctuation` run, mapping every visible char back
6192/// to its *true* source byte even when the source carries backslash escapes the
6193/// parsed `text` dropped (`\*` → `*`). The naive `span.start + text_offset`
6194/// mapping [`push_text`] uses drifts by one byte after each escape, so a caret or
6195/// click past an escaped `*` would land on the wrong character; walking the text
6196/// against its source keeps them aligned, and the hidden escape backslash gets no
6197/// glyph of its own (it is a spelling artefact, not something the caret lands on).
6198fn push_escaped_text(
6199    out: &mut Vec<Glyph>,
6200    text: &str,
6201    span: Range<usize>,
6202    source: &str,
6203    style: Style,
6204) {
6205    let end = span.end.min(source.len());
6206    let src = source.get(span.start..end).unwrap_or("");
6207    // Fast path — no dropped bytes, so text and source align 1:1 (the common
6208    // case: prose with no escapes). Byte lengths equal ⇒ no backslash was eaten.
6209    if src.len() == text.len() {
6210        push_text(out, text, span.start, style);
6211        return;
6212    }
6213    // Slow path: some `\` was consumed. Walk char-by-char, skipping a backslash
6214    // in the source exactly when it escapes the next visible char (a real escape),
6215    // never when it is a literal backslash the parse kept (that case has equal
6216    // lengths and takes the fast path above).
6217    let sb = src.as_bytes();
6218    let mut si = 0usize;
6219    'text: for (_, cluster) in text.grapheme_indices(true) {
6220        for (ci, ch) in cluster.char_indices() {
6221            // The text outlasted the source it is being mapped onto. In a
6222            // consistent document that cannot happen on this path: the slow path
6223            // is only entered when the two lengths differ, and everything that
6224            // makes them differ makes the *source* the longer one — an escape
6225            // backslash the parse ate, or source folded into a neighbouring node.
6226            // A `smart_punctuation` node reports its canonical ASCII spelling
6227            // (`--`, `...`, `"`), which is never longer than what was written.
6228            //
6229            // So reaching here means `span` was measured against a document that
6230            // `source` is no longer, and there is no honest offset left to give
6231            // the remaining characters. Stop: the row comes out short, which is
6232            // a wrong picture of a document that is already inconsistent. The
6233            // alternative was `si` stepping past the end and the slice below
6234            // panicking — which is what it did, in a paint loop.
6235            if si >= sb.len() {
6236                break 'text;
6237            }
6238            // Advance to the source character this one came from, stepping over
6239            // whatever the parse dropped on the way. An escape backslash is the
6240            // common case, but not the only one: a span can cover source that
6241            // was folded into a neighbouring node (smart punctuation next to a
6242            // bracket gives `text: "]"` over a source span of `"…]"`). Advancing
6243            // by the *text* character's length assumed escapes were the only
6244            // divergence, so one dropped multi-byte character desynchronized
6245            // every glyph after it — placing `]` inside the `…` before it.
6246            while si < sb.len() && !src[si..].starts_with(ch) {
6247                si += src[si..].chars().next().map_or(1, char::len_utf8);
6248            }
6249            out.push(Glyph {
6250                ch,
6251                style,
6252                src: span.start + si.min(src.len()),
6253                stop: ci == 0,
6254            });
6255            si += src[si..]
6256                .chars()
6257                .next()
6258                .map_or(ch.len_utf8(), char::len_utf8);
6259        }
6260    }
6261}
6262
6263/// Build synthetic decoration glyphs (a bullet, a gutter) all pointing at `src`,
6264/// each carrying `role` so the frontend can style it (`Role::Body` for plain
6265/// padding). Synthetic glyphs are never caret stops — they share one offset, so
6266/// the caret steps over them (a click still lands at `src`).
6267fn synth(text: &str, role: Role, src: usize) -> Vec<Glyph> {
6268    let style = Style::default().role(role);
6269    text.chars()
6270        .map(|ch| Glyph {
6271            ch,
6272            style,
6273            src,
6274            stop: false,
6275        })
6276        .collect()
6277}
6278
6279fn concat(a: &[Glyph], b: &[Glyph]) -> Vec<Glyph> {
6280    let mut v = a.to_vec();
6281    v.extend_from_slice(b);
6282    v
6283}
6284
6285/// The columns a row's prefix (a bullet, a quote gutter, an indent) takes up
6286/// before the text it introduces — what the wrap budget has left to spend.
6287fn prefix_width(prefix: &[Glyph]) -> usize {
6288    glyphs_width(prefix)
6289}
6290
6291/// The label shown for an image with no alt text: the final path segment of its
6292/// destination (`img/cat.png` → `cat.png`), the whole destination when it has no
6293/// separator, and `"image"` when it's empty. A `data:` URI (which has no useful
6294/// tail) shows its scheme so the placeholder isn't a wall of base64.
6295fn media_label(dest: &str) -> String {
6296    if dest.is_empty() {
6297        return "image".to_string();
6298    }
6299    if dest.starts_with("data:") {
6300        return "data:…".to_string();
6301    }
6302    // Trim a query/fragment so a URL's `?v=2#frag` doesn't ride along.
6303    let clean = dest.split(['?', '#']).next().unwrap_or(dest);
6304    let tail = clean
6305        .trim_end_matches('/')
6306        .rsplit(['/', '\\'])
6307        .next()
6308        .unwrap_or(clean);
6309    if tail.is_empty() {
6310        dest.to_string()
6311    } else {
6312        tail.to_string()
6313    }
6314}
6315
6316/// A directive's attributes read as a human label — what a frontend puts on a
6317/// container's tinted panel, and what an attribute-bearing inline directive
6318/// shows in its chip.
6319///
6320/// Reads BOTH conventions diaryx content actually uses: twig's own dot-prefixed
6321/// classes (`{.public .family}`, arriving as one combined `class` attr) and bare
6322/// pandoc-style words with no leading dot (`{public family}` — what
6323/// `diaryx_core::visibility`'s publish-time filter and apps/web's directive
6324/// serializer both write, and which twig parses as one valueless attribute
6325/// each). Reading only `.class` would leave every *existing* diaryx `:::vis{…}`
6326/// block unlabeled. A `key=value` attr is configuration rather than a name, so
6327/// it contributes nothing. `None` when nothing readable is left.
6328fn directive_attr_label(attrs: &[(String, Option<String>)]) -> Option<String> {
6329    let mut parts: Vec<String> = Vec::new();
6330    for (k, v) in attrs {
6331        if k == "class" {
6332            if let Some(v) = v
6333                && !v.is_empty()
6334            {
6335                parts.push(v.clone());
6336            }
6337        } else if v.as_deref().unwrap_or("").is_empty() {
6338            parts.push(k.clone());
6339        }
6340    }
6341    (!parts.is_empty()).then(|| parts.join(" "))
6342}
6343
6344fn heading_style(level: u32) -> Style {
6345    // Just the role — a frontend decides how a heading of this level *looks*
6346    // (the terminal cycles a color and bolds it, the GUI scales the font). The
6347    // author wrote no emphasis here, so core records none. `level as u8` is safe:
6348    // Markdown/Djot cap headings at 6.
6349    Style::default().role(Role::Heading(level.min(255) as u8))
6350}
6351
6352/// Is this `container` node a *directive* (`:::note{…}`, `::embed{…}`,
6353/// `:vis[…]`) rather than an HTML element (`<video>`, `<picture>`, `<div>`)?
6354///
6355/// twig 2.8 folded `div`/`span`/`directive`/`element` into one `container` kind,
6356/// and left nothing that separated them: `kind`, `name` and `directive_form` all
6357/// agree, field for field, on an HTML `<div>` and a Markdown `:::div`. Leaf
6358/// answered it by sniffing the span for whichever of `:` or `<` came first.
6359/// twig 3.0 records the answer at parse time as [`ContainerOrigin`], so this is
6360/// now the parser's own knowledge rather than a guess rebuilt from the bytes it
6361/// consumed.
6362pub(crate) fn container_is_directive(node: &FlatNode) -> bool {
6363    node.origin == Some(ContainerOrigin::Directive)
6364}
6365
6366/// The tag a `container` node carries when it is an HTML element rather than a
6367/// directive — `Some("video")` for a promoted `<video>`, `None` for a `:::note`
6368/// or for any node that is not a container at all.
6369pub(crate) fn element_tag(node: &FlatNode) -> Option<&str> {
6370    (node.origin == Some(ContainerOrigin::Element))
6371        .then_some(node.name.as_deref())
6372        .flatten()
6373}
6374
6375/// A leaf directive's name and whatever attributes are not part of spelling
6376/// it — the two things a [`DirectiveMark`] carries, which twig hands back
6377/// differently per format and which a frontend must not be able to tell apart.
6378///
6379/// Markdown's `::page-break` is a `Leaf`-form directive *named* `page-break`
6380/// with no attributes, and this returns it verbatim. Djot has no leaf form:
6381/// `insert_directive` writes the same document as an empty `::: page-break`
6382/// fence, whose container is anonymous (a djot div carries no name) and whose
6383/// name arrives as the fence's one class. So where the node has no name of its
6384/// own the first `class` token *is* the name, and whatever else the class said
6385/// — an author's `::: page-break {.wide}` — stays an attribute.
6386fn leaf_directive_identity(node: &FlatNode) -> (String, Vec<(String, Option<String>)>) {
6387    let named = node.name.clone().unwrap_or_default();
6388    if !named.is_empty() {
6389        return (named, node.attrs.clone());
6390    }
6391    let class = node
6392        .attrs
6393        .iter()
6394        .find(|(k, _)| k == "class")
6395        .and_then(|(_, v)| v.as_deref())
6396        .unwrap_or_default();
6397    let mut tokens = class.split_whitespace();
6398    let Some(name) = tokens.next().map(str::to_string) else {
6399        return (named, node.attrs.clone());
6400    };
6401    let rest = tokens.collect::<Vec<_>>().join(" ");
6402    let attrs = node
6403        .attrs
6404        .iter()
6405        .filter_map(|(k, v)| {
6406            if k != "class" {
6407                return Some((k.clone(), v.clone()));
6408            }
6409            (!rest.is_empty()).then(|| (k.clone(), Some(rest.clone())))
6410        })
6411        .collect();
6412    (name, attrs)
6413}
6414
6415/// Is this inline `container` an **attributed span** — the node leaf's run-level
6416/// vocabulary rides — rather than a named directive?
6417///
6418/// The four formats spell one span four ways and twig hands the name back for
6419/// two of them: HTML's and Markdown's `<span …>` arrive named `span` with
6420/// `Element` origin, while djot's `[text]{…}` and AsciiDoc's `[.a]#text#`
6421/// arrive anonymous (an empty name) with `Directive` origin. All four are the
6422/// same node to `wrap_range_attrs`, which is what writes them, so they are the
6423/// same node here.
6424///
6425/// A *named* directive is not one, whatever its name: a Markdown `:span[…]{…}`
6426/// is a directive the parser read as a directive, twig's own
6427/// `wrap_range_attrs` says so, and it keeps the handling it has.
6428///
6429/// **Anonymous is not enough**, and the form is what finishes the question:
6430/// a djot fenced div (`{.center}` / `:::` / … / `:::`) is anonymous too, with
6431/// the same `Directive` origin, and is a *block* — `Container` form against the
6432/// span's `Text`. Reading one as a span made every gesture and every query lie
6433/// about it: `set_text_color` over a word inside such a div copied the whole
6434/// div's attribute set — its `id` along with the rest — onto the new span, and
6435/// `alignment_at_caret` reported the div's `.center` as a *run's* answer while
6436/// the walker drew none. So the anonymous arm asks the form [`is_inline`] asks.
6437pub(crate) fn is_run_span(node: &FlatNode) -> bool {
6438    if node.kind != Kind::Container {
6439        return false;
6440    }
6441    match node.name.as_deref() {
6442        None | Some("") => node.directive_form == Some(DirectiveForm::Text),
6443        Some("span") => node.origin == Some(ContainerOrigin::Element),
6444        Some(_) => false,
6445    }
6446}
6447
6448/// `base` with an attributed span's three run-level keys written over it — the
6449/// nearest-wins fold [`is_run_span`] describes, for one span. `faces` is the
6450/// build's intern table, as it is for [`Presentation::under`].
6451fn run_style(node: &FlatNode, base: Style, faces: &RefCell<FaceTable>) -> Style {
6452    Style {
6453        size: FontSize::from_attrs(&node.attrs).or(base.size),
6454        font: faces
6455            .borrow_mut()
6456            .face_from_attrs(&node.attrs)
6457            .or(base.font),
6458        color: TextColor::from_attrs(&node.attrs).or(base.color),
6459        ..base
6460    }
6461}
6462
6463pub(crate) fn is_inline(node: &FlatNode) -> bool {
6464    // A directive is inline only in its `text` form (`:name[label]{…}`); the
6465    // `leaf` and `container` forms are blocks. All three report the same `kind`,
6466    // so the form is the only thing telling them apart — and getting it wrong
6467    // costs a whole paragraph: a text directive misread as a block makes its
6468    // paragraph fail the "all children inline" test in `block`, and the line is
6469    // then walked as a container of blocks, rendering as empty rows with no
6470    // caret home at all.
6471    //
6472    // An HTML element shares the `container` kind, and twig sets the same form
6473    // on the two tags the lightweight formats have a generic spelling for: a
6474    // `<span>` is `Text` and a `<div>` is `Container`, while a `<video>` or a
6475    // `<picture>` has no form at all. So the form answers for an element as it
6476    // answers for a directive, and the origin is not consulted — which is what
6477    // makes a `<span …>` inside a paragraph an inline node.
6478    //
6479    // It has to. `wrap_range_attrs` spells an attributed run as exactly that
6480    // span in Markdown and HTML, and a paragraph holding one whose kids were
6481    // not all inline failed the test below and was walked as a container of
6482    // blocks: the text either side of the span rendered as nothing at all.
6483    if node.kind == Kind::Container {
6484        return node.directive_form == Some(DirectiveForm::Text);
6485    }
6486    is_inline_kind(&node.kind)
6487}
6488
6489/// [`is_inline`] by kind alone — for the ancestor walks, whose `QueryMatch`es
6490/// carry no `directive_form`. It answers `false` for every directive, which its
6491/// callers must (and do) reconcile: they pair it with `is_block_container`,
6492/// which claims every directive, so the pair's verdict is the same one a form
6493/// would have given. Anything looking at a *directive itself* wants [`is_inline`]
6494/// and a real node.
6495pub(crate) fn is_inline_kind(kind: &Kind) -> bool {
6496    matches!(
6497        kind,
6498        Kind::Str
6499            | Kind::SoftBreak
6500            | Kind::HardBreak
6501            | Kind::NonBreakingSpace
6502            | Kind::Emph
6503            | Kind::Strong
6504            | Kind::Mark
6505            | Kind::Insert
6506            | Kind::Delete
6507            | Kind::Verbatim
6508            | Kind::InlineMath
6509            | Kind::DisplayMath
6510            | Kind::Url
6511            | Kind::Email
6512            | Kind::Link
6513            | Kind::Image
6514            | Kind::SmartPunctuation
6515            | Kind::Superscript
6516            | Kind::Subscript
6517            | Kind::FootnoteReference
6518    )
6519}
6520
6521/// Assert two maps are identical down to every glyph, stop, and table span — the
6522/// contract `build_cached` and `build_spliced` must hold against `build`. Lives
6523/// at module scope (not in `mod tests`) so the Doc-driven differential test in
6524/// `doc.rs` can reach it and the private `stops` field it compares.
6525#[cfg(test)]
6526pub(crate) fn assert_maps_eq(a: &VisualMap, b: &VisualMap, ctx: &str) {
6527    assert_eq!(a.rows.len(), b.rows.len(), "row count ({ctx})");
6528    for (i, (ra, rb)) in a.rows.iter().zip(&b.rows).enumerate() {
6529        assert_eq!(ra.end_src, rb.end_src, "row {i} end_src ({ctx})");
6530        assert_eq!(ra.decoration, rb.decoration, "row {i} decoration ({ctx})");
6531        // The incremental walk labels a boundary from a query match's kind
6532        // string and the whole-arena walk from a `FlatNode`'s; this is what says
6533        // the two doors reach the same answer.
6534        assert_eq!(ra.boundary, rb.boundary, "row {i} boundary ({ctx})");
6535        assert_eq!(ra.code, rb.code, "row {i} code ({ctx})");
6536        assert_eq!(ra.code_lang, rb.code_lang, "row {i} code_lang ({ctx})");
6537        assert_eq!(ra.align, rb.align, "row {i} align ({ctx})");
6538        assert_eq!(
6539            ra.line_height, rb.line_height,
6540            "row {i} line_height ({ctx})"
6541        );
6542        assert_eq!(
6543            ra.glyphs.len(),
6544            rb.glyphs.len(),
6545            "row {i} glyph count ({ctx})"
6546        );
6547        for (j, (ga, gb)) in ra.glyphs.iter().zip(&rb.glyphs).enumerate() {
6548            assert_eq!(
6549                (ga.ch, ga.src, ga.stop, ga.style),
6550                (gb.ch, gb.src, gb.stop, gb.style),
6551                "row {i} glyph {j} ({ctx})"
6552            );
6553        }
6554    }
6555    assert_eq!(a.content_start, b.content_start, "content_start ({ctx})");
6556    assert_eq!(a.stops, b.stops, "stops ({ctx})");
6557    assert_eq!(a.mark_ends, b.mark_ends, "mark_ends ({ctx})");
6558    assert_eq!(a.tables.len(), b.tables.len(), "table count ({ctx})");
6559    for (i, (ta, tb)) in a.tables.iter().zip(&b.tables).enumerate() {
6560        assert_eq!(ta.rows_span, tb.rows_span, "table {i} rows_span ({ctx})");
6561        assert_eq!(ta.end_src, tb.end_src, "table {i} end_src ({ctx})");
6562    }
6563    assert_eq!(a.code_blocks, b.code_blocks, "code_blocks ({ctx})");
6564    assert_eq!(a.media, b.media, "images ({ctx})");
6565}
6566
6567#[cfg(test)]
6568mod tests {
6569    use super::*;
6570    use crate::style::{FontFamily, LineSpacing, SizeStep};
6571    use twig::{Editor, Format, NodeId};
6572
6573    fn map(src: &str) -> VisualMap {
6574        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6575        build_t(&ed.nodes().unwrap(), src, Some(80))
6576    }
6577
6578    /// [`map`] over a Djot source. Djot is the format that spells superscript
6579    /// and subscript at all — Markdown has no syntax for either.
6580    fn map_djot(src: &str) -> VisualMap {
6581        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
6582        build_t(&ed.nodes().unwrap(), src, Some(80))
6583    }
6584
6585    /// The baseline every glyph spelling `ch` was built with, in row order —
6586    /// how a test reads a raised or lowered run off the map without caring
6587    /// which row it landed on.
6588    fn baselines_of(m: &VisualMap, ch: char) -> Vec<Baseline> {
6589        m.rows
6590            .iter()
6591            .flat_map(|r| r.glyphs.iter())
6592            .filter(|g| g.ch == ch)
6593            .map(|g| g.style.baseline)
6594            .collect()
6595    }
6596
6597    /// [`map`] at a chosen wrap width.
6598    fn map_at(src: &str, wrap: Option<usize>) -> VisualMap {
6599        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6600        build_t(&ed.nodes().unwrap(), src, wrap)
6601    }
6602
6603    /// [`map`], but with twig's `directives` extension on (off by twig's own
6604    /// default) — the `:::name{.class}` fenced-div containers leaf-core's
6605    /// `"directive"` wysiwyg arm renders.
6606    fn map_directives(src: &str) -> VisualMap {
6607        let mut ed = Editor::new_ext(
6608            src.as_bytes(),
6609            Format::Markdown,
6610            twig::MarkdownExtensions {
6611                directives: true,
6612                ..Default::default()
6613            },
6614        )
6615        .unwrap();
6616        build_t(&ed.nodes().unwrap(), src, Some(80))
6617    }
6618
6619    /// [`map`] in `format`, parsed the way every leaf document is — the
6620    /// extensions [`crate::doc::parse_extensions`] turns on, which is what
6621    /// pairs a Markdown `<div …>` with its `</div>` into a container and makes
6622    /// `::page-break` a directive rather than a paragraph of colons.
6623    fn map_leaf(src: &str, format: Format) -> VisualMap {
6624        let mut ed =
6625            Editor::new_ext(src.as_bytes(), format, crate::doc::parse_extensions()).unwrap();
6626        build_t(&ed.nodes().unwrap(), src, Some(80))
6627    }
6628
6629    /// The alignment and line spacing of every row that draws text, in order —
6630    /// how a test reads a block property off the map.
6631    fn line_facts(m: &VisualMap) -> Vec<(Option<Align>, Option<LineHeight>)> {
6632        m.rows
6633            .iter()
6634            .filter(|r| r.glyphs.iter().any(|g| !g.ch.is_whitespace()))
6635            .map(|r| (r.align, r.line_height))
6636            .collect()
6637    }
6638
6639    /// The style of the glyph spelling `ch`, first occurrence — how a test reads
6640    /// a run property off the map.
6641    fn style_of(m: &VisualMap, ch: char) -> Style {
6642        m.rows
6643            .iter()
6644            .flat_map(|r| r.glyphs.iter())
6645            .find(|g| g.ch == ch)
6646            .unwrap_or_else(|| panic!("no glyph {ch:?} in the map"))
6647            .style
6648    }
6649
6650    /// [`map`] with soft breaks preserved (`LineFlow::Preserve`).
6651    fn map_preserve(src: &str, wrap: Option<usize>) -> VisualMap {
6652        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6653        build(
6654            &ed.nodes().unwrap(),
6655            src,
6656            wrap,
6657            true,
6658            &Surface::default(),
6659            None,
6660        )
6661    }
6662
6663    /// The cache-free reference [`build`], with no per-image height overrides —
6664    /// every block image stays its default one-row placeholder. The tests that
6665    /// need a taller image drive it through [`crate::Doc::set_media_rows`] instead.
6666    fn build_t(nodes: &[FlatNode], src: &str, wrap: Option<usize>) -> VisualMap {
6667        build(nodes, src, wrap, false, &Surface::default(), None)
6668    }
6669
6670    /// An arena and a string that disagree — spans reaching past the source they
6671    /// are built against.
6672    ///
6673    /// [`crate::Doc`] keeps the two in step, so this is a "cannot happen" that
6674    /// nonetheless *did*: `examples/bench` timed a loop of `edit_range` and then
6675    /// went on handing the grown editor's spans to a builder holding the string
6676    /// from before it, and every run ended in a slice panic rather than a
6677    /// number. `push_escaped_text` was already written to survive the mismatch —
6678    /// it clamps the span's end and falls back to an empty slice — and this is
6679    /// the half of that intent it did not carry through.
6680    ///
6681    /// Rendering the wrong thing is the acceptable answer here; panicking in a
6682    /// paint loop is not.
6683    #[test]
6684    fn a_source_shorter_than_the_arena_built_over_it_renders_rather_than_panicking() {
6685        // An escape puts the run on `push_escaped_text`'s slow path — the fast
6686        // path is a length comparison that a truncated source fails anyway.
6687        let src = "alpha \\*beta\\* gamma delta epsilon\n";
6688        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6689        let nodes = ed.nodes().unwrap();
6690
6691        // Every truncation of it, so the cut lands before, inside and after the
6692        // escaped run rather than only where one hand-picked index put it.
6693        for cut in 0..=src.len() {
6694            if !src.is_char_boundary(cut) {
6695                continue;
6696            }
6697            let map = build_t(&nodes, &src[..cut], Some(80));
6698            for row in &map.rows {
6699                for g in &row.glyphs {
6700                    assert!(
6701                        g.src <= src.len(),
6702                        "cut {cut}: glyph {:?} points past the source at {}",
6703                        g.ch,
6704                        g.src
6705                    );
6706                }
6707            }
6708        }
6709    }
6710
6711    fn rendered(m: &VisualMap) -> String {
6712        m.rows
6713            .iter()
6714            .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
6715            .collect::<Vec<_>>()
6716            .join("\n")
6717    }
6718
6719    /// Render a source both ways: `build` over the whole marshalled arena (the
6720    /// reference), and `build_cached` driven the way [`crate::Doc`] drives it —
6721    /// top-level blocks from `child_spans`, per-block subtrees on a miss.
6722    fn render_both(
6723        ed: &mut Editor,
6724        src: &str,
6725        wrap: Option<usize>,
6726        cache: &mut BlockCache,
6727    ) -> (VisualMap, VisualMap) {
6728        let all = ed.nodes().unwrap();
6729        let surface = Surface::default();
6730        let plain = build(&all, src, wrap, false, &surface, None);
6731        let top = top_blocks(ed);
6732        let cached = build_cached(&top, src, wrap, false, &surface, None, cache, |id| {
6733            ed.subtree(NodeId(id)).unwrap_or_default()
6734        });
6735        (plain, cached)
6736    }
6737
6738    /// The whole correctness claim of the block cache: `build_cached` produces a
6739    /// byte-identical map to `build`, on a fresh cache *and* — the case that
6740    /// actually exercises reuse-and-shift plus per-block subtree marshalling — on
6741    /// a warm cache after the source has been edited underneath it.
6742    /// **Every glyph must stand on the character it claims.** A row's source
6743    /// extent is computed from its last glyph's offset, so a glyph carrying an
6744    /// offset that is not its own character's start yields a row end inside a
6745    /// multi-byte character — and every later slice of the source panics on it.
6746    ///
6747    /// Reproduces a real crash from a journal entry: a bracketed elision inside
6748    /// a blockquote (`[…]`) gave the closing bracket a `text` of `"]"` over a
6749    /// source span covering `"…]"`, because the parse folded the ellipsis into a
6750    /// neighbouring node. `push_escaped_text` walked that span assuming a
6751    /// dropped backslash was the only way text and source could diverge, so the
6752    /// `]` landed on the `…`'s first byte:
6753    /// `byte index 1236 is not a char boundary; it is inside '…'`.
6754    #[test]
6755    fn a_glyph_never_lands_inside_the_character_before_it() {
6756        let src = "> engage with it rather than look away. […]\n>\n> The through-line\n";
6757        let vmap = map(src);
6758        for (r, row) in vmap.rows.iter().enumerate() {
6759            assert!(
6760                src.is_char_boundary(row.end_src.min(src.len())),
6761                "row {r} ends at {} — inside a character",
6762                row.end_src
6763            );
6764            for g in &row.glyphs {
6765                assert!(
6766                    src.is_char_boundary(g.src.min(src.len())),
6767                    "row {r} has {:?} at {}, which is inside a character",
6768                    g.ch,
6769                    g.src
6770                );
6771            }
6772        }
6773        // The elision survives, and its bracket sits on the real `]`.
6774        let text: String = vmap
6775            .rows
6776            .iter()
6777            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
6778            .collect();
6779        assert!(text.contains("[…]"), "the elision should render: {text:?}");
6780        let close = vmap
6781            .rows
6782            .iter()
6783            .flat_map(|r| r.glyphs.iter())
6784            .find(|g| g.ch == ']')
6785            .expect("a closing bracket");
6786        assert_eq!(
6787            src[close.src..].chars().next(),
6788            Some(']'),
6789            "the bracket glyph should stand on the source's own `]`"
6790        );
6791    }
6792
6793    #[test]
6794    fn build_cached_matches_build() {
6795        let docs = [
6796            "# Title\n\nThe quick brown fox.\n\nAnother paragraph here.\n",
6797            "## H\n\n- one\n- two\n- three\n\n> a quote\n> continued\n",
6798            "para one\n\n```\ncode\nlines\n```\n\nafter code\n",
6799            "| a | b |\n|---|---|\n| 1 | 2 |\n\ntext after a table\n",
6800            "line\n- \nsetext?\n\nreal para\n\n\n\ntrailing blanks\n",
6801            "> quote with **bold** and a [link](https://x.dev)\n>\n> - item\n> - item2\n\ntail\n",
6802            "intro\n\n![a cat](img/cat.png)\n\nbetween\n\n![](https://x.dev/logo.svg)\n\nend\n",
6803            "- text item\n- ![alt](pic.png)\n- more text\n",
6804            // Footnotes: twig parses each definition as a root beside `doc`, so
6805            // these are the docs where the reference build and the incremental
6806            // one could disagree about what the top-level blocks even are.
6807            "A claim[^1] and another[^src].\n\n[^1]: First note.\n\n[^src]: Second.\n\ntail\n",
6808            "note[^a]\n\n[^a]: body **bold**\n    wrapped on\n    three lines\n\nafter\n",
6809            // No trailing newline. twig closes the document's last block on the
6810            // virtual newline it supplies at EOF, so that block's `span.end` is
6811            // `source.len() + 1` — a range that slices no bytes at all. Keying
6812            // the block cache off such a slice made every last block hash alike;
6813            // see [`block_bytes`].
6814            "# Title\n\nThe quick brown fox.\n\nA tail with no newline",
6815            "A claim[^1] and another[^src].\n\n[^1]: First note.\n[^src]: Second, ending the file.",
6816            // Comments draw nothing. The per-block builder the cached path
6817            // renders one with starts at offset 0 and, drawing nothing, never
6818            // moved — so the walk went on from 0 and spelled every line of the
6819            // document as a blank row. One at the start, one between blocks,
6820            // one at the end, so each position is covered.
6821            "<!-- lead -->\n\npara\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n\n<!-- trail -->\n",
6822            // A Markdown `<div>` ends with a hidden `</div>` line the walk
6823            // steps over — between blocks and closing the file, so both the
6824            // separator after it and the trailing count are covered.
6825            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
6826            "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n",
6827            // Link reference definitions: roots beside `doc` like footnotes,
6828            // but drawing nothing. Alone between blocks, glued under a
6829            // paragraph, and closing the file under a comment — the README
6830            // shape.
6831            "see [a] and [b]\n\n[a]: /a\n\nmid\n[b]: /b \"bee\"\n\nend [c]\n\n<!-- links -->\n[c]: /c\n",
6832            // A rule's row ends past the newline under it while the walk
6833            // stands at the rule, and the rule's block is never cached for
6834            // it: an empty line under one mid-document and closing it.
6835            "para\n\n---\n\n\n\nbetween rules\n\n---\n\n",
6836            // Blank lines above the first block draw rows: bare, past
6837            // frontmatter, and past a comment that draws nothing.
6838            "\n\n\nfirst\n\nsecond\n",
6839            "---\ntitle: x\n---\n\n\nafter frontmatter\n",
6840            "<!-- lead -->\n\n\n\nafter a comment\n",
6841            // An empty paragraph at the end of a div draws inside it.
6842            "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\n\n\n</div>\n\nafter\n",
6843        ];
6844        for wrap in [None, Some(80usize), Some(20)] {
6845            for src in docs {
6846                let ctx = format!("wrap={wrap:?} src={src:?}");
6847                let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
6848                let mut cache = BlockCache::default();
6849
6850                // 1) Fresh cache equals the cache-free build.
6851                let (plain, cached) = render_both(&mut ed, src, wrap, &mut cache);
6852                assert_maps_eq(&plain, &cached, &format!("fresh {ctx}"));
6853
6854                // 2) Type a char mid-document, reparse, rebuild with the now-warm
6855                //    cache: the edited block is re-marshalled and re-rendered,
6856                //    every block below it is reused shifted, and the result must
6857                //    still match a from-scratch build.
6858                let at = (src.len() / 2..=src.len())
6859                    .find(|&i| src.is_char_boundary(i))
6860                    .unwrap();
6861                ed.edit_range(at, at, "Z").unwrap();
6862                let src2 = ed.source_str().unwrap();
6863                let (plain2, cached2) = render_both(&mut ed, &src2, wrap, &mut cache);
6864                assert_maps_eq(&plain2, &cached2, &format!("after insert {ctx}"));
6865
6866                // 3) Delete it again: offsets shift back the other way, and the
6867                //    warm cache must not hand back stale shifted rows.
6868                ed.edit_range(at, at + 1, "").unwrap();
6869                let src3 = ed.source_str().unwrap();
6870                let (plain3, cached3) = render_both(&mut ed, &src3, wrap, &mut cache);
6871                assert_maps_eq(&plain3, &cached3, &format!("after delete {ctx}"));
6872            }
6873        }
6874    }
6875
6876    /// A document that does not end in a newline is the one place twig hands
6877    /// leaf a top-level span that addresses no source: the last block is closed
6878    /// on the virtual newline the parser supplies at EOF, so its `span.end` is
6879    /// `source.len() + 1`. The block cache keys on the bytes under that span, and
6880    /// reading the out-of-range slice as *no bytes* broke it two ways at once —
6881    /// [`block_bytes`] has the full account. Both ways are checked here, because
6882    /// they fail independently.
6883    #[test]
6884    fn a_block_running_past_the_last_byte_still_keys_the_cache_by_its_own_bytes() {
6885        // One: two overrunning blocks collide. A footnote definition is a root
6886        // beside `doc` that [`top_blocks`] merges into the top level, while the
6887        // `section` above it spans the definition's bytes too — so when the
6888        // definition ends the file, both blocks end past it. The second was
6889        // served the first's rows, and the definition rendered as a copy of the
6890        // heading.
6891        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.";
6892        let mut ed = Editor::new_str(src, Format::Djot).unwrap();
6893        let (plain, cached) = render_both(&mut ed, src, Some(80), &mut BlockCache::default());
6894        assert_maps_eq(&plain, &cached, "a definition ending the file");
6895        let text = rendered(&cached);
6896        assert!(
6897            text.ends_with("[note] A note with a word for a label."),
6898            "the last definition should render itself: {text:?}"
6899        );
6900        assert_eq!(
6901            text.matches("A heading with a reference").count(),
6902            1,
6903            "the heading should render exactly once: {text:?}"
6904        );
6905
6906        // Two: one overrunning block goes stale. Its bytes are its cache key, so
6907        // a block that keeps hashing the same however it is edited is served the
6908        // rows built before the edit — the whole last line frozen as the user
6909        // types in it.
6910        let mut cache = BlockCache::default();
6911        let first = "first para\n\n# A heading\n\nlast para with no newline";
6912        let mut ed = Editor::new_str(first, Format::Djot).unwrap();
6913        let (_, warm) = render_both(&mut ed, first, Some(80), &mut cache);
6914        assert!(rendered(&warm).ends_with("last para with no newline"));
6915
6916        let second = "first para\n\n# A heading\n\nDIFFERENT text without a newline";
6917        let mut ed = Editor::new_str(second, Format::Djot).unwrap();
6918        let (plain, cached) = render_both(&mut ed, second, Some(80), &mut cache);
6919        assert_maps_eq(&plain, &cached, "edited last block, warm cache");
6920        let text = rendered(&cached);
6921        assert!(
6922            text.ends_with("DIFFERENT text without a newline"),
6923            "the warm cache served the pre-edit rows: {text:?}"
6924        );
6925    }
6926
6927    #[test]
6928    fn resolves_markup_to_plain_text() {
6929        let text = rendered(&map("# Title\n\na **bold** word\n"));
6930        assert!(!text.contains('#'), "heading marker shown: {text:?}");
6931        assert!(!text.contains("**"), "strong delimiters shown: {text:?}");
6932        assert!(text.contains("Title") && text.contains("bold word"));
6933    }
6934
6935    #[test]
6936    fn every_glyph_points_at_its_source_byte() {
6937        let src = "a **bold** c\n";
6938        let m = map(src);
6939        for row in &m.rows {
6940            for g in &row.glyphs {
6941                // A real (non-synthetic) glyph's source byte is the glyph's char.
6942                if g.src < src.len()
6943                    && src.is_char_boundary(g.src)
6944                    && let Some(sc) = src[g.src..].chars().next()
6945                    && sc == g.ch
6946                {
6947                    continue;
6948                }
6949                // Synthetic prefixes (none here) would be the only exceptions.
6950                panic!("glyph {:?} at src {} doesn't match source", g.ch, g.src);
6951            }
6952        }
6953    }
6954
6955    #[test]
6956    fn offset_and_position_round_trip_on_visible_text() {
6957        let m = map("hello world\n");
6958        let (r, c) = m.pos_of_offset(6); // the 'w'
6959        assert_eq!(m.offset_of_pos(r, c), 6);
6960    }
6961
6962    #[test]
6963    fn visible_utf16_indices_count_the_text_the_system_sees() {
6964        // Hidden delimiters, a two-unit emoji, and a block gap — every way the
6965        // visible text's UTF-16 length parts company with a source byte count.
6966        let src = "a **b\u{1F600}** c\n\nd\n";
6967        let m = map(src);
6968        let end = m.snap_to_stop(src.len());
6969        let text = m.visible_text(0, end);
6970        assert_eq!(text, "a b\u{1F600} c\nd");
6971
6972        // Forward: the index of each offset is where that character sits in
6973        // the visible string, in UTF-16 units.
6974        for (i, (src_off, _)) in m.visible_items(0, end).iter().enumerate() {
6975            let expect: usize = text.chars().take(i).map(char::len_utf16).sum();
6976            assert_eq!(
6977                m.visible_utf16_len(0, *src_off),
6978                expect,
6979                "utf16 index of source offset {src_off}"
6980            );
6981            // And back: the index resolves to the offset it came from.
6982            assert_eq!(m.offset_at_visible_utf16(end, expect), Some(*src_off));
6983        }
6984        // Inside the emoji's surrogate pair resolves to the emoji.
6985        let emoji_src = src.find('\u{1F600}').unwrap();
6986        let emoji_idx = m.visible_utf16_len(0, emoji_src);
6987        assert_eq!(
6988            m.offset_at_visible_utf16(end, emoji_idx + 1),
6989            Some(emoji_src)
6990        );
6991        // At or past the end is nobody's character.
6992        let total = m.visible_utf16_len(0, end);
6993        assert_eq!(total, text.encode_utf16().count());
6994        assert_eq!(m.offset_at_visible_utf16(end, total), None);
6995    }
6996
6997    /// The documents the lookups are checked against their reference scans
6998    /// on: every shape that puts rows out of source order or a stop out of
6999    /// step with a glyph. A wrapped table, whose cells' second lines sit
7000    /// below the next column's first; a wide grapheme and an emoji outside
7001    /// the BMP; hidden delimiters and a link's hidden destination; a list
7002    /// with synthetic markers; a code block; an image row whose label glyphs
7003    /// all share one offset; an empty paragraph, a heading, and a wrapped
7004    /// paragraph — at a narrow width so the table and the prose both wrap,
7005    /// and unwrapped, which is how a GUI builds it.
7006    fn lookup_maps() -> Vec<(String, VisualMap)> {
7007        let table = "| left cell that wraps | right |\n|---|---|\n| a longer cell than the column can hold | b |\n| `k` | 你好 |\n\n";
7008        let srcs = [
7009            "hello world\n",
7010            "a **b\u{1F600}** c\n\nd\n",
7011            "- one *two*\n- three\n\n\n# Title\n\nend [link](https://e.org/x) tail\n",
7012            &format!("{table}```\nx\ny\n```\n\n![alt](a.png)\n\ntail 你好 **bold** here\n"),
7013            "one two three four five six seven eight nine ten eleven twelve thirteen\n\n| a | b |\n|-|-|\n| c d e f g h | i |\n",
7014        ];
7015        let mut out = Vec::new();
7016        for src in srcs {
7017            for wrap in [Some(14), None] {
7018                out.push((format!("{src:?} at {wrap:?}"), map_at(src, wrap)));
7019            }
7020        }
7021        out
7022    }
7023
7024    /// `pos_of_offset` as it was written before the walk learnt to dismiss a
7025    /// row from its ends: every row read through, the nearest stop kept.
7026    fn pos_of_offset_by_scan(m: &VisualMap, off: usize) -> (usize, usize) {
7027        let mut best: Option<(usize, usize, usize)> = None;
7028        for (r, row) in m.rows.iter().enumerate() {
7029            if row.decoration {
7030                continue;
7031            }
7032            let cand = row
7033                .glyphs
7034                .iter()
7035                .enumerate()
7036                .find(|(_, g)| g.stop && g.src >= off)
7037                .map(|(i, g)| (g.src, r, row.col_of_glyph(i)))
7038                .or_else(|| (row.end_src >= off).then_some((row.end_src, r, row.width())));
7039            if let Some(c) = cand
7040                && best.is_none_or(|b| c.0 <= b.0)
7041            {
7042                best = Some(c);
7043            }
7044        }
7045        match best {
7046            Some((_, r, c)) => (r, c),
7047            None => {
7048                let r = m.last_stop_row();
7049                (r, m.row_width(r))
7050            }
7051        }
7052    }
7053
7054    /// `visible_items` as it was written before the spelling was tabulated:
7055    /// every stop glyph in the range gathered, sorted, and paired up.
7056    fn visible_items_by_scan(m: &VisualMap, from: usize, to: usize) -> Vec<(usize, Option<char>)> {
7057        let (lo, hi) = m.visible_span(from, to);
7058        let from = m.snap_to_glyph_stop(from);
7059        let mut glyphs: Vec<(usize, char)> = m
7060            .rows
7061            .iter()
7062            .filter(|r| !r.decoration)
7063            .flat_map(|r| r.glyphs.iter())
7064            .filter(|g| g.stop && g.src >= from && g.src < to)
7065            .map(|g| (g.src, g.ch))
7066            .collect();
7067        glyphs.sort_by_key(|&(src, _)| src);
7068        glyphs.dedup_by_key(|&mut (src, _)| src);
7069        let cell_ends: Vec<usize> = m
7070            .tables
7071            .iter()
7072            .flat_map(|t| t.grid.iter())
7073            .flat_map(|r| r.cells.iter())
7074            .map(|c| c.end)
7075            .collect();
7076        m.stops[lo..hi]
7077            .iter()
7078            .map(|&s| {
7079                let ch = glyphs
7080                    .iter()
7081                    .find(|&&(src, _)| src == s)
7082                    .filter(|_| !cell_ends.contains(&s))
7083                    .map(|&(_, ch)| ch);
7084                (s, ch)
7085            })
7086            .collect()
7087    }
7088
7089    #[test]
7090    fn pos_of_offset_agrees_with_reading_every_row_through() {
7091        for (name, m) in lookup_maps() {
7092            let len = m.rows.iter().map(|r| r.end_src).max().unwrap_or(0) + 2;
7093            for off in 0..=len {
7094                assert_eq!(
7095                    m.pos_of_offset(off),
7096                    pos_of_offset_by_scan(&m, off),
7097                    "offset {off} of {name}"
7098                );
7099            }
7100        }
7101    }
7102
7103    #[test]
7104    fn the_tabulated_spelling_agrees_with_gathering_the_glyphs() {
7105        for (name, m) in lookup_maps() {
7106            let end = m.stops.last().copied().unwrap_or(0);
7107            // Whole text, and every window a frontend might ask for.
7108            let mut spans = vec![(0, end)];
7109            for &a in m.stops.iter().step_by(3) {
7110                spans.push((a, end));
7111                spans.push((0, a));
7112                spans.push((a, (a + 5).min(end)));
7113            }
7114            for (from, to) in spans {
7115                let items = visible_items_by_scan(&m, from, to);
7116                assert_eq!(
7117                    m.visible_items(from, to),
7118                    items,
7119                    "items {from}..{to} of {name}"
7120                );
7121                let utf16: usize = items
7122                    .iter()
7123                    .map(|(_, ch)| ch.map_or(1, char::len_utf16))
7124                    .sum();
7125                assert_eq!(
7126                    m.visible_utf16_len(from, to),
7127                    utf16,
7128                    "utf16 {from}..{to} of {name}"
7129                );
7130            }
7131            // And back: every UTF-16 index in the text resolves to the stop
7132            // that spells it, as the scan would have found it.
7133            let items = visible_items_by_scan(&m, 0, end);
7134            let mut seen = 0;
7135            for (src, ch) in &items {
7136                for u in seen..seen + ch.map_or(1, char::len_utf16) {
7137                    assert_eq!(
7138                        m.offset_at_visible_utf16(end, u),
7139                        Some(*src),
7140                        "index {u} of {name}"
7141                    );
7142                }
7143                seen += ch.map_or(1, char::len_utf16);
7144            }
7145            assert_eq!(
7146                m.offset_at_visible_utf16(end, seen),
7147                None,
7148                "past the end of {name}"
7149            );
7150        }
7151    }
7152
7153    #[test]
7154    fn visible_text_spends_exactly_one_character_on_every_stop() {
7155        // A list (whose items' ends no gap row follows), a table (whose cells'
7156        // ends draw a gutter space), and a code block (one row per line):
7157        // every place the text used to part company with the stop count, in
7158        // both directions. `UITextInput`'s tokenizer indexes this text by
7159        // that count, so the two must agree exactly between any two stops.
7160        let src = "- one\n- two\n\n| a | b |\n| - | - |\n| c | d |\n\n```\nx\ny\n```\n\nend\n";
7161        let m = map(src);
7162        let end = m.snap_to_stop(src.len());
7163        // The table's trailing stop draws no glyph, so it is spelled as a line
7164        // end too: to the system the table ends on a blank line, which is
7165        // where the caret past it stands.
7166        assert_eq!(m.visible_text(0, end), "one\ntwo\na\nb\nc\nd\n\nx\ny\nend");
7167        // Between any two stops, one character per hop.
7168        let first = m.snap_to_glyph_stop(0);
7169        let stops: Vec<usize> = std::iter::successors(Some(first), |&o| m.stop_after(o)).collect();
7170        for (i, &a) in stops.iter().enumerate() {
7171            for (j, &b) in stops.iter().enumerate().skip(i) {
7172                assert_eq!(
7173                    m.visible_text(a, b).chars().count(),
7174                    j - i,
7175                    "text between stops {a} and {b}"
7176                );
7177            }
7178        }
7179        // A cell's end is spelled as a line end, not the space it draws, so a
7180        // tap landing past `a`'s last letter has nothing to step over into `b`.
7181        let a_end = src.find("a |").unwrap() + 1;
7182        assert_eq!(m.visible_text(a_end, a_end + 1), "\n");
7183    }
7184
7185    #[test]
7186    fn unwrapped_mode_emits_one_row_per_paragraph() {
7187        // A long paragraph that would wrap under a column budget stays a single
7188        // row when wrap is None (the GUI wraps it at pixel width instead).
7189        let long = "one two three four five six seven eight nine ten eleven twelve\n";
7190        let mut ed = Editor::new_str(long, Format::Markdown).unwrap();
7191        let wrapped = build_t(&ed.nodes().unwrap(), long, Some(12));
7192        let unwrapped = build_t(&ed.nodes().unwrap(), long, None);
7193        assert!(wrapped.num_rows() > 1, "narrow column should wrap");
7194        assert_eq!(unwrapped.num_rows(), 1, "no budget should keep it one row");
7195        // Every glyph's source byte is preserved in the single row.
7196        let text: String = unwrapped.rows[0].glyphs.iter().map(|g| g.ch).collect();
7197        assert_eq!(text.trim_end(), long.trim_end());
7198    }
7199
7200    fn line_texts(m: &VisualMap) -> Vec<String> {
7201        m.rows
7202            .iter()
7203            .map(|r| {
7204                // Trim the trailing whitespace a row may carry — the zero-width
7205                // '\n' that closes a preserved line, and any space glyph left at
7206                // a wrap boundary (both real caret stops, neither visible text).
7207                r.glyphs
7208                    .iter()
7209                    .map(|g| g.ch)
7210                    .collect::<String>()
7211                    .trim_end()
7212                    .to_string()
7213            })
7214            .collect()
7215    }
7216
7217    #[test]
7218    fn preserve_lays_each_soft_break_on_its_own_row() {
7219        // A soft break (a bare newline inside a paragraph) folds into a space by
7220        // default — the whole paragraph is one reflowed row...
7221        let src = "one two\nthree four\n";
7222        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7223        let folded = build_t(&ed.nodes().unwrap(), src, None);
7224        assert_eq!(folded.num_rows(), 1, "fold: one reflowed row");
7225        assert_eq!(
7226            line_texts(&folded),
7227            vec!["one two three four"],
7228            "break folded to a space"
7229        );
7230
7231        // ...and under Preserve it renders where it was written, a row per line.
7232        let kept = map_preserve(src, None);
7233        assert_eq!(
7234            line_texts(&kept),
7235            vec!["one two", "three four"],
7236            "preserve: a row per line"
7237        );
7238    }
7239
7240    #[test]
7241    fn a_preserved_break_keeps_the_newline_offset_as_a_caret_stop() {
7242        // The break must leave a caret stop at the newline byte, or the caret
7243        // could not rest at the end of the first line. The '\n' glyph is dropped
7244        // from the row (so nothing stray renders); its offset (7 here) becomes the
7245        // row's end stop instead — the same offset the folded space would carry.
7246        let src = "one two\nthree four\n";
7247        let m = map_preserve(src, None);
7248        assert!(
7249            !m.rows[0].glyphs.iter().any(|g| g.ch == '\n'),
7250            "the break glyph is dropped"
7251        );
7252        assert_eq!(
7253            m.rows[0].end_src, 7,
7254            "the first row ends at the newline byte"
7255        );
7256        assert!(m.is_stop(7), "the newline offset is a caret stop");
7257        // Row end offsets stay strictly ascending — no two rows pin one offset.
7258        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
7259        assert!(
7260            offs.windows(2).all(|w| w[0] < w[1]),
7261            "offsets not unique: {offs:?}"
7262        );
7263    }
7264
7265    #[test]
7266    fn preserved_lines_wrap_independently() {
7267        // Each preserved line wraps to the column on its own; the break between
7268        // them is hard, so a word never crosses it — "gamma" and "delta" could
7269        // share a row on width alone but the soft break keeps them apart.
7270        let src = "alpha beta gamma\ndelta epsilon\n";
7271        let m = map_preserve(src, Some(12));
7272        assert_eq!(
7273            line_texts(&m),
7274            vec!["alpha beta", "gamma", "delta", "epsilon"],
7275            "each source line wraps on its own"
7276        );
7277    }
7278
7279    #[test]
7280    fn an_empty_paragraph_between_blocks_renders_its_own_rows() {
7281        // "A", then two blank lines (an empty paragraph opened with Enter), then
7282        // "B": the empty paragraph must be navigable rows, not collapsed onto B.
7283        // Rows: "A", spacer, empty-paragraph, spacer, "B" — each blank row a
7284        // distinct source offset.
7285        let m = map("A\n\n\n\nB\n");
7286        let text: Vec<String> = m
7287            .rows
7288            .iter()
7289            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7290            .collect();
7291        assert_eq!(text, vec!["A", "", "", "", "B"], "got {text:?}");
7292        let offs: Vec<usize> = m.rows.iter().map(|r| r.end_src).collect();
7293        // Strictly ascending — no two rows share an offset (else the caret pins).
7294        assert!(
7295            offs.windows(2).all(|w| w[0] < w[1]),
7296            "offsets not unique: {offs:?}"
7297        );
7298    }
7299
7300    #[test]
7301    fn a_tight_block_boundary_still_gets_one_separator() {
7302        // A heading directly above text (no blank line between) keeps the single
7303        // conventional separator row, as before.
7304        let m = map("# H\ntext\n");
7305        let text: Vec<String> = m
7306            .rows
7307            .iter()
7308            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7309            .collect();
7310        assert_eq!(text, vec!["H", "", "text"], "got {text:?}");
7311    }
7312
7313    #[test]
7314    fn an_escaped_delimiter_renders_without_its_backslash_and_maps_true_offsets() {
7315        // `a\*b` renders the three visible chars `a * b` — the escape backslash
7316        // is hidden — and every glyph points at its real source byte, so a caret
7317        // past the escape lands right (the `*` at source 2, `b` at source 3, not
7318        // the drifted 1/2 the naive text-offset mapping gave).
7319        let m = map("a\\*b\n");
7320        let row: Vec<(char, usize)> = m.rows[0].glyphs.iter().map(|g| (g.ch, g.src)).collect();
7321        assert_eq!(row, vec![('a', 0), ('*', 2), ('b', 3)], "got {row:?}");
7322    }
7323
7324    #[test]
7325    fn an_escaped_hash_stays_a_paragraph_and_shows_the_hash() {
7326        // `\# hi` is a paragraph beginning with a literal `#`, not a heading —
7327        // the backslash is hidden, the `#` shown at its true offset.
7328        let m = map("\\# hi\n");
7329        let text: String = m.rows[0].glyphs.iter().map(|g| g.ch).collect();
7330        assert_eq!(text, "# hi");
7331        assert_eq!(
7332            m.rows[0].glyphs[0].src, 1,
7333            "the # is at source byte 1, past the \\"
7334        );
7335    }
7336
7337    #[test]
7338    fn a_tight_nested_list_hangs_its_sublist_directly_under_the_item() {
7339        // A list item's own text and the sub-list nested under it are written on
7340        // adjacent source lines, so the rich view butts them together — no
7341        // fabricated blank row. Regression: the synthetic "breathe" separator
7342        // used to open a gap between `• a` and its `  • b`.
7343        assert_eq!(rendered(&map("- a\n  - b\n")), "• a\n  • b");
7344    }
7345
7346    #[test]
7347    fn a_loose_nested_list_keeps_its_real_blank_line() {
7348        // A genuine blank source line (a loose list) still parts the item from
7349        // its sub-list — only the *fabricated* separator is suppressed, never a
7350        // real one the author typed. The gap row wears the item's continuation
7351        // prefix (the two-space indent), so it renders as "  ", not empty.
7352        assert_eq!(rendered(&map("- a\n\n  - b\n")), "• a\n  \n  • b");
7353    }
7354
7355    #[test]
7356    fn frontmatter_is_hidden_and_the_document_opens_into_its_content() {
7357        // Leading YAML frontmatter renders nothing — no phantom blank rows for
7358        // its lines, no leading gap — and `content_start` points at the first
7359        // real block so the caret floor can keep out of the hidden metadata.
7360        let fm = "---\nconfig: prov.yaml\ncontents:\n- '[Sample](sample.md)'\n---\n";
7361        let src = format!("{fm}# leaf\n\nA line.\n");
7362        let m = map(&src);
7363        let text = rendered(&m);
7364        assert!(
7365            !text.contains("config"),
7366            "frontmatter body leaked: {text:?}"
7367        );
7368        assert!(!text.contains("prov"), "frontmatter body leaked: {text:?}");
7369        assert_eq!(
7370            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7371            "leaf"
7372        );
7373        assert_eq!(
7374            m.content_start,
7375            fm.len(),
7376            "floor should be the first real block"
7377        );
7378    }
7379
7380    #[test]
7381    fn a_frontmatter_only_document_puts_the_floor_after_the_frontmatter() {
7382        // Nothing to render, so the caret floor is the end of the hidden
7383        // frontmatter — not 0, which is *before* the opening `---` and made the
7384        // first keystroke in a fresh metadata-only note land ahead of it. And
7385        // the frontmatter's own newlines are not trailing blank lines: they used
7386        // to open phantom rows at offsets 1..4, inside the metadata.
7387        let src = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
7388        let m = map(src);
7389        assert_eq!(m.content_start, src.len(), "floor must clear the metadata");
7390        assert!(
7391            m.rows.is_empty(),
7392            "frontmatter must render no rows: {:?}",
7393            rendered(&m)
7394        );
7395        assert!(
7396            m.stops.is_empty(),
7397            "no stop may sit inside the metadata: {:?}",
7398            m.stops
7399        );
7400    }
7401
7402    #[test]
7403    fn a_frontmatter_only_document_still_counts_its_real_blank_lines() {
7404        // Two blank lines after the frontmatter are the author's empty paragraph
7405        // and still render, counted from the metadata's end rather than from 0.
7406        let fm = "---\ntitle: n\n---\n";
7407        let m = map(&format!("{fm}\n\n"));
7408        assert_eq!(m.content_start, fm.len());
7409        assert_eq!(m.rows.len(), 2, "the two trailing newlines each open a row");
7410        assert!(
7411            m.rows.iter().all(|r| r.end_src > fm.len()),
7412            "rows must sit past the frontmatter"
7413        );
7414    }
7415
7416    #[test]
7417    fn a_document_without_frontmatter_has_a_zero_floor() {
7418        let m = map("# leaf\n\nbody\n");
7419        assert_eq!(m.content_start, 0);
7420    }
7421
7422    #[test]
7423    fn trailing_spaces_become_caret_stops_so_the_caret_can_be_drawn_past_them() {
7424        // Markdown/Djot drop the trailing space in `hello ` from the `str` node,
7425        // so without help the row would end at `hello` and the caret couldn't be
7426        // drawn past column 5 — typing a space at a line's end wouldn't move it
7427        // on screen until the next visible character reparsed the space into an
7428        // interior node. The builder recovers it from the block's span/content_span
7429        // gap and emits it as a real, caret-stoppable glyph.
7430        let m = map("hello \n");
7431        assert_eq!(
7432            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7433            "hello "
7434        );
7435        assert_eq!(
7436            m.rows[0].end_src, 6,
7437            "the row now ends past the trailing space"
7438        );
7439        // The caret can rest both on and past the space.
7440        assert_eq!(m.pos_of_offset(5), (0, 5), "between 'o' and the space");
7441        assert_eq!(m.pos_of_offset(6), (0, 6), "past the space");
7442        // Two trailing spaces, both stops.
7443        let m = map("hello  \n");
7444        assert_eq!(
7445            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7446            "hello  "
7447        );
7448        assert_eq!(m.pos_of_offset(7), (0, 7));
7449    }
7450
7451    #[test]
7452    fn a_headings_trailing_space_is_a_caret_stop_too() {
7453        // The hidden `# ` marker means `# hi ` renders as `hi ` in three columns;
7454        // the caret past the trailing space lands on the third.
7455        let m = map("# hi \n");
7456        assert_eq!(
7457            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
7458            "hi "
7459        );
7460        assert_eq!(m.pos_of_offset(5), (0, 3));
7461    }
7462
7463    #[test]
7464    fn a_table_cells_trailing_padding_is_not_mistaken_for_block_trailing_space() {
7465        // A cell's own `span` is the whole row, so the trailing-whitespace
7466        // recovery must not run for cells or it would swallow the `│` delimiters
7467        // and neighbours between the cell text and the row's end. The grid stays
7468        // exactly as before.
7469        let text = rendered(&map(TABLE));
7470        assert!(
7471            text.contains("│ Pear │   3 │"),
7472            "cell padding disturbed:\n{text}"
7473        );
7474    }
7475
7476    #[test]
7477    fn a_click_below_the_last_row_lands_on_the_last_stop_not_offset_zero() {
7478        // A drag into the empty space under a short document used to resolve to
7479        // offset 0 — the wrong direction, and not even a caret stop when the
7480        // document opens on hidden frontmatter (its `content_start` floor is not
7481        // a stop), which crashed the caret invariant. It now lands on the last
7482        // stop: the end of the document, where dragging downward should reach.
7483        let fm = "---\ntitle: n\n---\n";
7484        let m = map(&format!("{fm}# Hi\n\nbody\n"));
7485        let below = m.num_rows() + 5;
7486        let off = m.offset_of_pos(below, 0);
7487        assert!(
7488            m.is_stop(off),
7489            "offset {off} from a below-content click is not a stop"
7490        );
7491        assert_eq!(
7492            off,
7493            m.stops.last().copied().unwrap(),
7494            "should be the document's last stop"
7495        );
7496        assert!(
7497            off > fm.len(),
7498            "must not fall onto the hidden frontmatter floor"
7499        );
7500    }
7501
7502    #[test]
7503    fn offset_of_pos_is_a_stop_for_every_row_including_past_the_end() {
7504        // The invariant the caret motion asserts: whatever cell a click names,
7505        // the offset it resolves to is one the caret can actually rest at.
7506        for src in [
7507            "hello \n",
7508            "# A heading here \n\nbody text goes on \n",
7509            "---\nk: v\n---\n# Title\n\nprose here that wraps a bit \n",
7510        ] {
7511            let m = map(src);
7512            for row in 0..m.num_rows() + 3 {
7513                for col in 0..30 {
7514                    let off = m.offset_of_pos(row, col);
7515                    assert!(
7516                        m.is_stop(off),
7517                        "row {row} col {col} → {off} is not a stop in {src:?}"
7518                    );
7519                }
7520            }
7521        }
7522    }
7523
7524    /// `| Name | Qty |` with Name left-aligned and Qty right-aligned.
7525    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
7526
7527    #[test]
7528    fn a_table_renders_as_an_aligned_grid() {
7529        let text = rendered(&map(TABLE));
7530        assert_eq!(
7531            text,
7532            "┌──────┬─────┐\n\
7533             │ Name │ Qty │\n\
7534             ├──────┼─────┤\n\
7535             │ Pear │   3 │\n\
7536             │ Fig  │  12 │\n\
7537             └──────┴─────┘",
7538            "got:\n{text}"
7539        );
7540    }
7541
7542    #[test]
7543    fn table_columns_honour_their_alignment() {
7544        // Centre and default(left) come straight from twig's cell.alignment —
7545        // the delimiter row it's spelled in is consumed and has no node.
7546        let text = rendered(&map("| A | Bee |\n| --- | :---: |\n| x | y |\n"));
7547        assert!(text.contains("│ x │  y  │"), "centred column: {text:?}");
7548    }
7549
7550    #[test]
7551    fn table_borders_are_decoration_the_caret_never_lands_on() {
7552        let m = map(TABLE);
7553        // The top and header rules are whole decoration rows.
7554        for r in [0, 2] {
7555            assert!(m.rows[r].decoration, "row {r} should be a decoration rule");
7556            assert!(
7557                !m.rows[r].glyphs.iter().any(|g| g.stop),
7558                "row {r} has a stop"
7559            );
7560        }
7561        // The bottom border is the exception: no glyph of it is a stop, but
7562        // its end is the table's trailing caret home — the one place the caret
7563        // can stand past the last cell.
7564        let bottom = &m.rows[5];
7565        assert!(
7566            !bottom.decoration,
7567            "the bottom border holds the trailing stop"
7568        );
7569        assert!(
7570            !bottom.glyphs.iter().any(|g| g.stop),
7571            "the bottom border's glyphs are not stops"
7572        );
7573        assert!(m.is_stop(bottom.end_src), "the trailing stop is a stop");
7574        assert!(m.table_end_stop(bottom.end_src));
7575        assert_eq!(
7576            bottom.end_src,
7577            TABLE.trim_end_matches('\n').len(),
7578            "the trailing stop is the table's own end, before its newline"
7579        );
7580        assert!(
7581            !m.table_end_stop(TABLE.rfind("12").unwrap() + 2),
7582            "a cell's end is not the trailing stop"
7583        );
7584        // A content row's `│` and padding are decoration; only the cell text
7585        // and each cell's one end-stop are stops.
7586        let header = &m.rows[1];
7587        assert!(!header.decoration);
7588        for g in &header.glyphs {
7589            if g.ch == '│' {
7590                assert!(!g.stop, "a border is not a caret stop");
7591            }
7592        }
7593        let stops: String = header
7594            .glyphs
7595            .iter()
7596            .filter(|g| g.stop)
7597            .map(|g| g.ch)
7598            .collect();
7599        assert_eq!(stops, "Name Qty ", "cell text plus one end-stop space each");
7600    }
7601
7602    #[test]
7603    fn a_cell_maps_to_its_own_source_text() {
7604        let m = map(TABLE);
7605        // "Pear" starts at byte 32 in TABLE; the caret there draws on the 'P'.
7606        let pear = TABLE.find("Pear").unwrap();
7607        let (r, c) = m.pos_of_offset(pear);
7608        assert_eq!(m.rows[r].glyphs[c].ch, 'P');
7609        assert_eq!(m.offset_of_pos(r, c), pear, "round trips");
7610    }
7611
7612    #[test]
7613    fn a_wide_table_is_cut_to_fit_and_its_cells_wrap() {
7614        // Columns wider than the surface used to run off the right edge, where
7615        // nothing could reach them. They're cut to the budget instead, and the
7616        // text wraps down inside the column — the header rule stays put, and
7617        // an alignment holds on every line of a wrapped cell, not just the first.
7618        let src = "| Ingredient | Notes |\n|---|---:|\n\
7619                   | flour milled coarse | sift it twice |\n| salt | a pinch |\n";
7620        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7621        let m = build_t(&ed.nodes().unwrap(), src, Some(30));
7622        let text = rendered(&m);
7623        assert_eq!(
7624            text,
7625            "┌──────────────┬─────────────┐\n\
7626             │ Ingredient   │       Notes │\n\
7627             ├──────────────┼─────────────┤\n\
7628             │ flour milled │     sift it │\n\
7629             │ coarse       │       twice │\n\
7630             │ salt         │     a pinch │\n\
7631             └──────────────┴─────────────┘",
7632            "got:\n{text}"
7633        );
7634        for (r, row) in m.rows.iter().enumerate() {
7635            assert!(
7636                row.glyphs.len() <= 30,
7637                "row {r} overflows: {}",
7638                row.glyphs.len()
7639            );
7640        }
7641    }
7642
7643    #[test]
7644    fn a_column_too_narrow_for_a_word_breaks_it_rather_than_spilling() {
7645        // A paragraph lets an overlong word trail off the end of the line; a
7646        // table column can't — a glyph past the border lands on the border.
7647        let src = "| A | B |\n|---|---|\n| antidisestablishmentarianism | x |\n";
7648        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
7649        let m = build_t(&ed.nodes().unwrap(), src, Some(20));
7650        for (r, row) in m.rows.iter().enumerate() {
7651            assert!(
7652                row.glyphs.len() <= 20,
7653                "row {r} overflows: {}",
7654                row.glyphs.len()
7655            );
7656        }
7657        // Broken across lines, but whole: every letter is still drawn, at its
7658        // own source byte, where the caret can reach it.
7659        let word = "antidisestablishmentarianism";
7660        let at = src.find(word).unwrap();
7661        for (i, ch) in word.char_indices() {
7662            assert!(
7663                m.rows
7664                    .iter()
7665                    .flat_map(|r| r.glyphs.iter())
7666                    .any(|g| g.stop && g.src == at + i && g.ch == ch),
7667                "{ch:?} at {} was lost to the break",
7668                at + i
7669            );
7670        }
7671    }
7672
7673    #[test]
7674    fn a_code_block_maps_each_line_to_its_own_source_text() {
7675        // Every glyph used to point at the block's start, which made the whole
7676        // block one offset — visible, but impossible to put a caret inside.
7677        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
7678        let m = map(src);
7679        for row in &m.rows {
7680            for g in row.glyphs.iter().filter(|g| g.stop) {
7681                assert_eq!(
7682                    src[g.src..].chars().next(),
7683                    Some(g.ch),
7684                    "glyph {:?} at {} isn't the source byte it claims",
7685                    g.ch,
7686                    g.src
7687                );
7688            }
7689        }
7690    }
7691
7692    #[test]
7693    fn an_indented_code_block_maps_past_its_stripped_indent() {
7694        // twig strips the four-space indent, so `text` isn't a source slice and
7695        // the lines have to be re-found. Offsets land on the code, not the indent.
7696        let src = "    indented\n    code\n";
7697        let m = map(src);
7698        let stops: Vec<(char, usize)> = m
7699            .rows
7700            .iter()
7701            .flat_map(|r| r.glyphs.iter().filter(|g| g.stop).map(|g| (g.ch, g.src)))
7702            .collect();
7703        assert_eq!(
7704            stops[0],
7705            ('i', 4),
7706            "first line should start past the indent"
7707        );
7708        assert!(
7709            stops.contains(&('c', 17)),
7710            "second line misplaced: {stops:?}"
7711        );
7712    }
7713
7714    #[test]
7715    fn a_fenced_block_whose_code_echoes_its_info_string_maps_to_the_code() {
7716        // The one case that defeats a forward search: the opening fence
7717        // ```` ```rust ```` ends with the same text as the code under it.
7718        let src = "```rust\nrust\n```\n";
7719        let m = map(src);
7720        let first = m.rows[0].glyphs.iter().find(|g| g.stop).unwrap();
7721        assert_eq!(first.src, 8, "matched the info string, not the code");
7722    }
7723
7724    #[test]
7725    fn a_code_block_carries_no_gutter_and_is_published_as_a_row_span() {
7726        // The old `▏ ` gutter is gone: a code row is the block prefix (none, at
7727        // the top level) plus the code text, and the whole run is named in
7728        // `code_blocks` so a frontend can box it.
7729        let src = "para\n\n```\ncode\nlines\n```\n\nafter\n";
7730        let m = map(src);
7731        assert_eq!(m.code_blocks.len(), 1, "one code block");
7732        let span = m.code_blocks[0].rows_span.clone();
7733        let rows: Vec<String> = m.rows[span.clone()]
7734            .iter()
7735            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7736            .collect();
7737        assert_eq!(rows, vec!["code".to_string(), "lines".to_string()]);
7738        assert!(!rendered(&m).contains('▏'), "gutter still drawn");
7739        assert!(
7740            m.rows[span].iter().all(|r| r.code),
7741            "every row in the span is flagged code"
7742        );
7743    }
7744
7745    #[test]
7746    fn an_empty_last_line_in_a_code_block_is_a_row_of_its_own() {
7747        // `trim_end_matches('\n')` cut the block's terminator *and* the newline
7748        // that spells a trailing empty line, so the row the Return had just made
7749        // never appeared and the caret on it fell through to the block below.
7750        // Every empty line is a row, wherever in the block it falls.
7751        let src = "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n";
7752        let m = map(src);
7753        let span = m.code_blocks[0].rows_span.clone();
7754        let rows: Vec<String> = m.rows[span.clone()]
7755            .iter()
7756            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7757            .collect();
7758        assert_eq!(
7759            rows,
7760            vec!["alpha".to_string(), "beta".to_string(), String::new()],
7761            "the empty last line gets a row"
7762        );
7763        assert!(
7764            m.rows[span.clone()].iter().all(|r| r.code),
7765            "the empty row is flagged code like the rest of the block"
7766        );
7767        // And it is the *source's* empty line, not a coarse fallback to the
7768        // block start: the offset the caret resolves to is the one Return made.
7769        let empty = span.end - 1;
7770        assert_eq!(
7771            m.rows[empty].end_src,
7772            src.find("beta\n\n").unwrap() + "beta\n".len(),
7773            "the empty row maps to the line the Return opened"
7774        );
7775
7776        // Nothing is invented where there is no empty line, and a second one is
7777        // a second row.
7778        assert_eq!(
7779            map("```\nalpha\nbeta\n```\n").code_blocks[0]
7780                .rows_span
7781                .len(),
7782            2,
7783            "a block that ends at its last code line keeps two rows"
7784        );
7785        assert_eq!(
7786            map("```\nalpha\n\n\n```\n").code_blocks[0].rows_span.len(),
7787            3,
7788            "two trailing empty lines are two rows"
7789        );
7790    }
7791
7792    #[test]
7793    fn a_directive_container_is_tinted_and_labeled_on_its_first_row() {
7794        // diaryx's `:::vis{.public .family}` visibility block, and any other
7795        // `:::name{.class}` fenced div — core is agnostic of `name`.
7796        let src = ":::vis{.public .family}\nhello\n\nworld\n:::\nafter\n";
7797        let m = map_directives(src);
7798
7799        let content_rows: Vec<usize> = (0..m.rows.len()).filter(|&i| m.rows[i].directive).collect();
7800        assert!(!content_rows.is_empty(), "some row is flagged directive");
7801
7802        let after_rows: Vec<usize> = (0..m.rows.len())
7803            .filter(|&i| !content_rows.contains(&i) && !m.rows[i].glyphs.is_empty())
7804            .collect();
7805        assert!(
7806            after_rows.iter().all(|&i| !m.rows[i].directive),
7807            "content outside the fence isn't tinted"
7808        );
7809
7810        let labels: Vec<&str> = content_rows
7811            .iter()
7812            .filter_map(|&i| m.rows[i].directive_label.as_deref())
7813            .collect();
7814        assert_eq!(
7815            labels,
7816            vec!["public family"],
7817            "only the first row carries the label"
7818        );
7819
7820        assert_eq!(
7821            rendered(&m)
7822                .lines()
7823                .filter(|l| !l.is_empty())
7824                .collect::<Vec<_>>(),
7825            vec!["hello", "world", "after"],
7826            "fence markers don't leak into the rendered text"
7827        );
7828    }
7829
7830    #[test]
7831    fn a_bare_word_directive_is_labeled_same_as_dot_classes() {
7832        // diaryx_core::visibility's own `:::vis{public family}` — no leading
7833        // dots — is what apps/web's directive serializer and the native
7834        // publish-time filter both actually write today, distinct from twig's
7835        // `.class` convention. Both must label the same way so every existing
7836        // diaryx `:::vis{...}` block reads, not just newly dot-authored ones.
7837        let src = ":::vis{public family}\nhello\n:::\n";
7838        let m = map_directives(src);
7839        let label = m.rows.iter().find_map(|r| r.directive_label.clone());
7840        assert_eq!(label.as_deref(), Some("public family"));
7841    }
7842
7843    #[test]
7844    fn a_text_directive_keeps_its_paragraph_visible() {
7845        // Regression: an inline `:name[label]{…}` used to make its paragraph
7846        // fail the "all children inline" test, so the whole line was walked as
7847        // a container of blocks and rendered as empty rows with NO caret stops —
7848        // the text vanished from the editor and the caret couldn't enter it.
7849        // diaryx's inline `:vis[…]` is exactly this shape.
7850        let src = "Text with :abbr[HTML]{title=\"HyperText\"} inline.\n";
7851        let m = map_directives(src);
7852        assert_eq!(rendered(&m).trim_end(), "Text with HTML inline.");
7853        // Every character of the line is a caret home, markup excluded — the
7854        // label reads as ordinary text, the way a link's does.
7855        let stops: usize = m
7856            .rows
7857            .iter()
7858            .map(|r| r.glyphs.iter().filter(|g| g.stop).count())
7859            .sum();
7860        assert_eq!(stops, "Text with HTML inline.".chars().count());
7861        // It is inline, so it is not the container form's tinted panel.
7862        assert!(m.rows.iter().all(|r| !r.directive));
7863    }
7864
7865    #[test]
7866    fn a_text_directives_label_maps_to_its_true_source_bytes() {
7867        // Regression (needs twig-doc >= 2.5.0): twig parses a `[label]` as a
7868        // detached slice, and until it rebased the enclosing scan's segments
7869        // onto it every node inside the label reported a span of `(0,0)`. Read
7870        // by anything that trusts a span that means "byte 0", so the label's
7871        // glyphs mapped to the START OF THE DOCUMENT — a click on the label put
7872        // the caret at the top of the file, its stops collided with the real
7873        // first line's, and an edit there landed on the wrong bytes entirely.
7874        //
7875        // The sibling test `a_text_directive_keeps_its_paragraph_visible` only
7876        // counts stops, which is exactly why this went unnoticed: the right
7877        // NUMBER of stops at completely wrong offsets.
7878        let src = "x :abbr[HTML]{title=\"y\"} z\n";
7879        let m = map_directives(src);
7880        let stops: Vec<(char, usize)> = m
7881            .rows
7882            .iter()
7883            .flat_map(|r| &r.glyphs)
7884            .filter(|g| g.stop)
7885            .map(|g| (g.ch, g.src))
7886            .collect();
7887        // `HTML` sits at 8..12. The name, brackets and `{…}` are hidden markup
7888        // the caret steps over, so the line's stops run 0, 1, 8..12, then 24.
7889        assert_eq!(
7890            stops,
7891            [
7892                ('x', 0),
7893                (' ', 1),
7894                ('H', 8),
7895                ('T', 9),
7896                ('M', 10),
7897                ('L', 11),
7898                (' ', 24),
7899                ('z', 25)
7900            ]
7901        );
7902    }
7903
7904    #[test]
7905    fn every_glyph_in_a_directive_label_points_at_its_source_byte() {
7906        // The `every_glyph_points_at_its_source_byte` invariant, extended over
7907        // directive labels now that their offsets are real. Nested markup is
7908        // included: its delimiters are hidden, so the visible glyphs must skip
7909        // them and still name their own bytes.
7910        let src = "x :abbr[a *b* c] y and :vis[family only] z\n";
7911        let m = map_directives(src);
7912        for g in m.rows.iter().flat_map(|r| &r.glyphs).filter(|g| g.stop) {
7913            let at = src[g.src..].chars().next();
7914            assert_eq!(
7915                at,
7916                Some(g.ch),
7917                "glyph {:?} claims byte {}, which is {at:?}",
7918                g.ch,
7919                g.src
7920            );
7921        }
7922        assert_eq!(rendered(&m).trim_end(), "x a b c y and family only z");
7923    }
7924
7925    #[test]
7926    fn a_directive_labels_nested_emphasis_keeps_both_its_style_and_its_offsets() {
7927        let src = "x :abbr[a *b* c] y\n";
7928        let m = map_directives(src);
7929        let b = m
7930            .rows
7931            .iter()
7932            .flat_map(|r| &r.glyphs)
7933            .find(|g| g.ch == 'b')
7934            .expect("the emphasised char");
7935        assert!(b.style.italic, "the label's *b* lost its emphasis");
7936        assert_eq!(b.src, 11, "the label's *b* lost its source byte");
7937    }
7938
7939    #[test]
7940    fn a_bare_colon_word_renders_as_the_prose_it_almost_always_is() {
7941        // Regression: twig matches a colon followed by any letter-led word, so
7942        // ordinary prose is full of "text directives" nobody meant to write.
7943        // With no `[label]` there are no children, and the arm recursed into
7944        // them — rendering *nothing*. The word vanished from the document with
7945        // no caret stop left behind, so it could not even be deleted.
7946        for src in ["a :word b\n", "note :see below\n", ":smile: hi\n"] {
7947            let m = map_directives(src);
7948            assert_eq!(
7949                rendered(&m).trim_end(),
7950                src.trim_end(),
7951                "prose was eaten: {src:?}"
7952            );
7953        }
7954    }
7955
7956    #[test]
7957    fn a_bare_colon_word_keeps_every_byte_a_caret_stop() {
7958        let src = "a :word b\n";
7959        let m = map_directives(src);
7960        // Nothing here is markup, so nothing is hidden: each byte maps to
7961        // itself and can be stood on, which is what makes the colon deletable.
7962        let stops: Vec<(char, usize)> = m
7963            .rows
7964            .iter()
7965            .flat_map(|r| &r.glyphs)
7966            .filter(|g| g.stop)
7967            .map(|g| (g.ch, g.src))
7968            .collect();
7969        assert_eq!(
7970            stops,
7971            "a :word b"
7972                .chars()
7973                .enumerate()
7974                .map(|(i, c)| (c, i))
7975                .collect::<Vec<_>>()
7976        );
7977    }
7978
7979    #[test]
7980    fn an_attribute_bearing_text_directive_draws_a_chip() {
7981        // `{…}` is deliberate in a way a bare colon is not — diaryx writes
7982        // `:vis{.family}` inline — so this one reads as an embed, on the same
7983        // `⧉ label` recipe the leaf form's placeholder row uses.
7984        // Both attribute conventions label it: twig's dot-prefixed classes and
7985        // the bare pandoc-style words diaryx also writes.
7986        for src in ["a :vis{.family} b\n", "a :vis{family} b\n"] {
7987            let m = map_directives(src);
7988            assert_eq!(rendered(&m).trim_end(), "a ⧉ vis family b", "{src:?}");
7989        }
7990        // A `key=value` attr is configuration, not a name, so it adds nothing.
7991        let m = map_directives("a :foo{title=\"x\"} b\n");
7992        assert_eq!(rendered(&m).trim_end(), "a ⧉ foo b");
7993    }
7994
7995    #[test]
7996    fn a_directive_chip_is_one_atomic_caret_stop_at_its_own_offset() {
7997        let src = "a :vis{.family} b\n";
7998        let m = map_directives(src);
7999        let stops: Vec<usize> = m
8000            .rows
8001            .iter()
8002            .flat_map(|r| &r.glyphs)
8003            .filter(|g| g.stop)
8004            .map(|g| g.src)
8005            .collect();
8006        // The chip contributes exactly one stop, at the directive's start (2),
8007        // so the caret steps over it whole instead of walking hidden markup a
8008        // byte at a time. `{.family}`'s bytes (3..15) are never stood on.
8009        assert_eq!(stops, [0, 1, 2, 15, 16]);
8010    }
8011
8012    #[test]
8013    fn a_paragraph_holding_only_a_chip_is_still_navigable() {
8014        // With no stop of its own the row would be unreachable — the caret
8015        // could never be put on the line to edit or delete the directive.
8016        let m = map_directives(":vis{.family}\n");
8017        assert!(
8018            m.row_is_navigable(0),
8019            "a chip-only paragraph has no caret home"
8020        );
8021        assert_eq!(
8022            m.offset_of_pos(0, 0),
8023            0,
8024            "its caret home isn't the directive's start"
8025        );
8026    }
8027
8028    #[test]
8029    fn a_ratio_or_a_clock_time_is_never_a_directive() {
8030        // twig requires a letter after the colon, so these stay prose — the
8031        // verbatim arm must not be reached for them at all.
8032        let src = "ratio 3:4 and 10:30\n";
8033        assert_eq!(
8034            rendered(&map_directives(src)).trim_end(),
8035            "ratio 3:4 and 10:30"
8036        );
8037    }
8038
8039    #[test]
8040    fn a_leaf_directive_is_a_placeholder_row_with_its_attrs_published() {
8041        // `::name{…}` is a standalone block with no body — an embed, a table of
8042        // contents. It used to emit no rows at all: invisible, no caret home,
8043        // vertical motion crossing a void. Now it draws the image recipe's
8044        // placeholder and publishes what the host app needs to paint the real
8045        // thing.
8046        let src = "before\n\n::embed{src=\"demo.html\" height=\"400\"}\n\nafter\n";
8047        let m = map_directives(src);
8048
8049        let row = m
8050            .rows
8051            .iter()
8052            .position(|r| r.leaf_directive.is_some())
8053            .expect("a placeholder row");
8054        assert_eq!(
8055            m.rows[row].glyphs.iter().map(|g| g.ch).collect::<String>(),
8056            "⧉ embed"
8057        );
8058        assert!(
8059            m.rows[row].glyphs.iter().any(|g| g.stop),
8060            "the caret can land on it"
8061        );
8062        assert!(
8063            m.rows[row].directive,
8064            "a frontend frames it like the container form"
8065        );
8066
8067        assert_eq!(m.directives.len(), 1);
8068        let info = &m.directives[0];
8069        assert_eq!(info.name, "embed");
8070        assert_eq!(info.rows_span, row..row + 1);
8071        assert_eq!(info.attr("src"), Some("demo.html"));
8072        assert_eq!(info.attr("height"), Some("400"));
8073        assert_eq!(info.attr("nope"), None);
8074        // The prose around it is untouched.
8075        assert!(rendered(&m).contains("before") && rendered(&m).contains("after"));
8076    }
8077
8078    #[test]
8079    fn a_leaf_directive_shows_its_label_and_honours_its_prefix() {
8080        // A `[label]` names the placeholder (the way an image's alt does), and a
8081        // quoted directive keeps the quote's gutter — it is a block like any
8082        // other, not a special case that escapes its container.
8083        let m = map_directives("::embed[Audience demo]{src=\"demo.html\"}\n");
8084        assert_eq!(rendered(&m).trim_end(), "⧉ Audience demo");
8085        assert_eq!(m.directives[0].label, "Audience demo");
8086
8087        let quoted = map_directives("> ::embed{src=\"x.html\"}\n");
8088        assert_eq!(rendered(&quoted).trim_end(), "│ ⧉ embed");
8089        assert_eq!(quoted.directives[0].name, "embed");
8090    }
8091
8092    #[test]
8093    fn a_container_directive_is_still_a_panel_not_a_placeholder() {
8094        // The three forms must not bleed into each other: only the leaf form is
8095        // a placeholder, and only the container form tints the blocks it wraps.
8096        let m = map_directives(":::note{.warning}\nBody\n:::\n");
8097        assert!(
8098            m.directives.is_empty(),
8099            "a container publishes no placeholder"
8100        );
8101        assert!(m.rows.iter().all(|r| r.leaf_directive.is_none()));
8102        assert_eq!(rendered(&m).trim_end(), "Body");
8103        assert!(
8104            m.rows
8105                .iter()
8106                .any(|r| r.directive && r.directive_label.as_deref() == Some("warning"))
8107        );
8108    }
8109
8110    /// A production-path build with both extensions on — the only way to put a
8111    /// promoted HTML element and a directive in one document, which is what the
8112    /// `container` kind made necessary to tell apart. Returns the whole `Doc`
8113    /// because [`VisualMap`] is not `Clone`; read `doc.vmap`.
8114    fn doc_built(src: &str) -> crate::Doc {
8115        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
8116        doc.build_visual(80);
8117        doc
8118    }
8119
8120    /// Every `container` node in `src`, parsed the way production does (both
8121    /// extensions on), paired with what [`container_is_directive`] makes of it.
8122    fn containers(src: &str) -> Vec<(String, bool, Option<DirectiveForm>)> {
8123        let mut ed = Editor::new_ext(
8124            src.as_bytes(),
8125            Format::Markdown,
8126            twig::MarkdownExtensions {
8127                directives: true,
8128                html_elements: true,
8129                ..Default::default()
8130            },
8131        )
8132        .unwrap();
8133        ed.nodes()
8134            .unwrap()
8135            .iter()
8136            .filter(|n| n.kind == Kind::Container)
8137            .map(|n| {
8138                (
8139                    n.name.clone().unwrap_or_default(),
8140                    container_is_directive(n),
8141                    n.directive_form,
8142                )
8143            })
8144            .collect()
8145    }
8146
8147    #[test]
8148    fn a_directive_and_an_html_element_are_told_apart_by_spelling_not_by_form() {
8149        // twig 2.8 folded `div`/`span`/`directive`/`element` into one `container`
8150        // kind. `directive_form` reads as though it separates them and does not:
8151        // a block-level `<div>` reports `Some(DirectiveForm::Container)` exactly
8152        // as a `:::note` does. Trusting it would draw directive chrome — a tinted
8153        // panel, a `.class` audience label — on every pasted Slack/Docs div.
8154        for (src, name, want) in [
8155            (":::note{.a}\nbody\n:::\n", "note", true),
8156            ("::embed{src=x}\n", "embed", true),
8157            ("a :vis[hi]{.b} b\n", "vis", true),
8158            ("<div class=\"x\">\nhi\n</div>\n", "div", false),
8159            ("<video src=\"v.mp4\" controls></video>\n", "video", false),
8160            ("<audio src=\"a.mp3\" controls></audio>\n", "audio", false),
8161            ("<figure>\n\nhi\n\n</figure>\n", "figure", false),
8162            // The `:` in an attribute must not read as a directive opener: the
8163            // `<` of the tag comes first, and first one wins.
8164            (
8165                "<video src=\"http://x.test/v.mp4\" controls></video>\n",
8166                "video",
8167                false,
8168            ),
8169            (
8170                "<source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\n",
8171                "source",
8172                false,
8173            ),
8174        ] {
8175            let found = containers(src);
8176            let hit = found.iter().find(|(n, ..)| n == name);
8177            let Some((_, is_directive, form)) = hit else {
8178                panic!("no `{name}` container in {src:?} — found {found:?}");
8179            };
8180            assert_eq!(*is_directive, want, "{name} in {src:?} (form was {form:?})");
8181        }
8182
8183        // And the reason this can't just read the field: for the one collision
8184        // that matters, the field says the same thing for both.
8185        let div = containers("<div class=\"x\">\nhi\n</div>\n");
8186        let note = containers(":::note{.a}\nbody\n:::\n");
8187        assert_eq!(
8188            div[0].2, note[0].2,
8189            "if these ever differ, `directive_form` became usable and this rule can go"
8190        );
8191    }
8192
8193    #[test]
8194    fn a_directive_nested_in_a_quote_or_list_is_still_a_directive() {
8195        // A container's span opens with its *block prefix*, not its own markup —
8196        // `> ::embed{…}` starts at the `>`. Reading only the first byte to tell a
8197        // directive from an element (both `container` since 2.8) therefore misses
8198        // every nested one, and the placeholder silently renders as nothing.
8199        for (src, ctx) in [
8200            ("> ::embed{src=\"x\"}\n", "quoted"),
8201            ("- ::embed{src=\"x\"}\n", "listed"),
8202            (">> ::embed{src=\"x\"}\n", "twice quoted"),
8203        ] {
8204            let m = map_directives(src);
8205            assert_eq!(m.directives.len(), 1, "{ctx} directive was lost");
8206            assert_eq!(m.directives[0].name, "embed", "{ctx}");
8207        }
8208    }
8209
8210    #[test]
8211    fn a_video_is_still_media_and_not_a_directive() {
8212        // The other side of the same coin: `<video>` is a `container` too, and
8213        // must reach `block_media` rather than the directive arms.
8214        let doc = doc_built("<video src=\"clip.mp4\" controls></video>\n");
8215        assert_eq!(doc.vmap.media.len(), 1, "the video is block media");
8216        assert!(
8217            doc.vmap.rows.iter().all(|r| !r.directive),
8218            "the video drew directive chrome"
8219        );
8220    }
8221
8222    #[test]
8223    fn a_directive_needs_the_extension_flag() {
8224        // `map` (twig's default extensions) leaves `directives` off — the fence
8225        // renders as literal paragraph text, same as any other unrecognized
8226        // punctuation, never corrupting or panicking.
8227        let src = ":::vis{.public}\nhello\n:::\n";
8228        let m = map(src);
8229        assert!(m.rows.iter().all(|r| !r.directive));
8230        assert!(rendered(&m).contains(":::vis{.public}"));
8231    }
8232
8233    #[test]
8234    fn a_footnote_reference_keeps_its_paragraph_visible() {
8235        // Regression: `footnote_reference` was in neither `is_inline_kind` nor
8236        // the inline walker, so a paragraph carrying one failed the "all children
8237        // inline" test, was walked as a container of blocks, and rendered as
8238        // empty rows with no caret stop anywhere — the whole line vanished.
8239        let src = "A claim[^1] and more.\n";
8240        let m = map(src);
8241        assert_eq!(rendered(&m).trim_end(), "A claim[1] and more.");
8242        // The `^` is spelling, not text: hidden the way a link's `](dest)` is.
8243        assert!(!rendered(&m).contains('^'));
8244    }
8245
8246    #[test]
8247    fn a_footnote_reference_is_raised_and_the_prose_around_it_is_not() {
8248        // What makes `[1]` read as a reference rather than as bracketed text.
8249        // The brackets ride with the label: the chip is one raised mark.
8250        let m = map("A claim[^1] and more.\n");
8251        assert_eq!(baselines_of(&m, '1'), vec![Baseline::Super]);
8252        assert_eq!(baselines_of(&m, '['), vec![Baseline::Super]);
8253        assert_eq!(baselines_of(&m, ']'), vec![Baseline::Super]);
8254        assert_eq!(baselines_of(&m, 'A'), vec![Baseline::Normal]);
8255    }
8256
8257    #[test]
8258    fn a_footnote_reference_keeps_the_link_role_it_had() {
8259        // The raised baseline is added to the role, not swapped for it: every
8260        // frontend already paints `Role::Link`, and a reference is one.
8261        let m = map("A claim[^1].\n");
8262        let label = m
8263            .rows
8264            .iter()
8265            .flat_map(|r| &r.glyphs)
8266            .find(|g| g.ch == '1')
8267            .unwrap();
8268        assert_eq!(label.style.role, Role::Link);
8269        assert_eq!(label.style.baseline, Baseline::Super);
8270    }
8271
8272    /// The [`Role`] of the first glyph spelling `ch` — how a test reads one
8273    /// run's styling off a map without caring which row it landed on.
8274    fn role_of(m: &VisualMap, ch: char) -> Role {
8275        m.rows
8276            .iter()
8277            .flat_map(|r| r.glyphs.iter())
8278            .find(|g| g.ch == ch)
8279            .unwrap_or_else(|| panic!("no glyph spelling {ch:?}"))
8280            .style
8281            .role
8282    }
8283
8284    #[test]
8285    fn a_markdown_highlight_is_a_mark_and_a_coloured_one_names_its_colour() {
8286        // twig 3.3's `highlight`/`highlight_colors`, which `parse_extensions`
8287        // turns on for every leaf document: `==text==` is a `mark` in Markdown
8288        // and not the literal `==` it used to be, and `==🔴 text==` is one
8289        // carrying a colour.
8290        //
8291        // `doc_built` rather than `map`, deliberately — the extensions are
8292        // leaf's choice, not twig's default, so a test that parsed bare
8293        // Markdown here would be testing a document leaf never builds.
8294        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
8295        assert_eq!(role_of(&doc.vmap, 'y'), Role::Mark(None));
8296        assert_eq!(
8297            role_of(&doc.vmap, 'r'),
8298            Role::Mark(Some(MarkColor::Red)),
8299            "the `data-color` twig stripped the emoji into"
8300        );
8301        assert_eq!(role_of(&doc.vmap, 'P'), Role::Body);
8302    }
8303
8304    #[test]
8305    fn the_emoji_that_named_a_highlight_is_markup_and_never_drawn() {
8306        // The colour is *spelling*: twig strips the emoji out of the mark's
8307        // content, so the reader sees the words and the wash, never the circle.
8308        // Drawing it would put a character in the rendered text that the author
8309        // wrote as syntax — the same mistake as drawing an emphasis's `*`.
8310        let doc = doc_built("Plain ==yes== and ==🔴 red== ok\n");
8311        let drawn: String = doc.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
8312        assert_eq!(drawn, "Plain yes and red ok");
8313    }
8314
8315    #[test]
8316    fn a_superscript_and_a_subscript_sit_off_the_baseline() {
8317        // Regression: both rendered flat, so the toolbar's superscript button
8318        // produced markup that looked exactly like the text around it.
8319        let m = map_djot("H~2~O and x^2^\n");
8320        assert_eq!(baselines_of(&m, '2'), vec![Baseline::Sub, Baseline::Super]);
8321        assert_eq!(baselines_of(&m, 'H'), vec![Baseline::Normal]);
8322        assert_eq!(baselines_of(&m, 'O'), vec![Baseline::Normal]);
8323    }
8324
8325    #[test]
8326    fn a_raised_glyph_keeps_the_style_it_was_raised_out_of() {
8327        // Why this is a `Baseline` and not a `Role`: raising a glyph says where
8328        // it sits, and must not cost it what it already was.
8329        let m = map_djot("# Heading x^2^\n");
8330        let two = m
8331            .rows
8332            .iter()
8333            .flat_map(|r| &r.glyphs)
8334            .find(|g| g.ch == '2')
8335            .unwrap();
8336        assert_eq!(two.style.baseline, Baseline::Super);
8337        assert_eq!(two.style.role, Role::Heading(1), "still heading text");
8338    }
8339
8340    #[test]
8341    fn a_footnote_references_brackets_are_decoration_and_only_its_label_is_a_stop() {
8342        let src = "see[^note] here\n";
8343        let m = map(src);
8344        // `[^note]` spans 3..10, its label `note` 5..9. The caret walks the
8345        // label; the brackets are drawn but never stood on, as a table's are,
8346        // and the `[^`/`]` bytes are stepped over like any hidden delimiter.
8347        let stops: Vec<usize> = m
8348            .rows
8349            .iter()
8350            .flat_map(|r| &r.glyphs)
8351            .filter(|g| g.stop)
8352            .map(|g| g.src)
8353            .collect();
8354        for off in 5..9 {
8355            assert!(
8356                stops.contains(&off),
8357                "label byte {off} isn't a caret stop: {stops:?}"
8358            );
8359        }
8360        for off in [3usize, 4, 9] {
8361            assert!(
8362                !stops.contains(&off),
8363                "delimiter byte {off} is a caret stop: {stops:?}"
8364            );
8365        }
8366    }
8367
8368    #[test]
8369    fn a_task_item_draws_its_box_where_the_bullet_would_be() {
8370        // Regression: the `[ ] ` is markup twig consumes — the item's paragraph
8371        // content starts past it — so a task item used to render as `• todo`,
8372        // identical to a plain bullet and with no way to see it was ticked.
8373        let m = map("- [ ] todo\n- [x] done\n- plain\n");
8374        assert_eq!(rendered(&m), "☐ todo\n☑ done\n• plain");
8375
8376        // The tick rides the item's first row, for a GUI that paints its own box.
8377        let ticks: Vec<Option<bool>> = m.rows.iter().map(|r| r.task).collect();
8378        assert_eq!(ticks, [Some(false), Some(true), None]);
8379    }
8380
8381    #[test]
8382    fn a_task_items_box_survives_a_wrap_and_marks_only_the_first_row() {
8383        let m = map_at(
8384            "- [x] a much longer task that has to wrap somewhere\n",
8385            Some(20),
8386        );
8387        assert!(m.rows.len() > 1, "the item should wrap: {:?}", rendered(&m));
8388        assert_eq!(m.rows[0].task, Some(true));
8389        assert!(
8390            m.rows[1..].iter().all(|r| r.task.is_none()),
8391            "only the first row"
8392        );
8393        // The continuation lines hang under the box, not under column zero.
8394        assert!(
8395            rendered(&m)
8396                .lines()
8397                .nth(1)
8398                .is_some_and(|l| l.starts_with("  "))
8399        );
8400    }
8401
8402    #[test]
8403    fn a_bracket_in_an_items_prose_is_not_a_checkbox() {
8404        // `task_checked` finds the box past the list marker; a plain item whose
8405        // text merely contains a bracket has none, and must keep its bullet.
8406        let m = map("- see [1] below\n");
8407        assert_eq!(rendered(&m), "• see [1] below");
8408        assert_eq!(m.rows[0].task, None);
8409    }
8410
8411    #[test]
8412    fn a_footnote_definition_renders_where_it_was_written() {
8413        // Regression: twig parses `[^1]: …` as a root *beside* `doc` — not a
8414        // child of it — so the walk from `doc` never reached one and every byte
8415        // of the note's body rendered as nothing at all.
8416        let src = "A claim[^1].\n\n[^1]: The note body.\n\nAfter.\n";
8417        let m = map(src);
8418        let text = rendered(&m);
8419        assert!(
8420            text.contains("The note body."),
8421            "the note body is invisible: {text:?}"
8422        );
8423        // In source order — between the paragraph that cites it and the one
8424        // after — not hoisted to the end, and marked to match its reference.
8425        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
8426        assert_eq!(lines, ["A claim[1].", "[1] The note body.", "After."]);
8427    }
8428
8429    #[test]
8430    fn a_footnote_definitions_body_maps_to_its_own_source_bytes() {
8431        let src = "x[^a].\n\n[^a]: body\n";
8432        let m = map(src);
8433        // `body` sits at 14..18. Its glyphs must map there — a marker that ate
8434        // the offsets would put the caret in the wrong place on every click.
8435        let body: Vec<(char, usize)> = m
8436            .rows
8437            .iter()
8438            .flat_map(|r| &r.glyphs)
8439            .filter(|g| g.stop && g.src >= 14)
8440            .map(|g| (g.ch, g.src))
8441            .collect();
8442        assert_eq!(body, [('b', 14), ('o', 15), ('d', 16), ('y', 17)]);
8443    }
8444
8445    #[test]
8446    fn an_empty_footnote_definition_still_shows_its_marker() {
8447        // The instant `[^1]: ` has been typed and nothing after it. `blocks`
8448        // renders no child, so without the explicit marker row the definition
8449        // wouldn't appear at all until something was typed into it.
8450        let src = "x[^1]\n\n[^1]:\n";
8451        let m = map(src);
8452        assert!(
8453            rendered(&m).contains("[1] "),
8454            "no marker row: {:?}",
8455            rendered(&m)
8456        );
8457    }
8458
8459    #[test]
8460    fn a_footnote_definition_wearing_a_long_label_indents_its_wrapped_body() {
8461        let src = "x[^src]\n\n[^src]: one two three four five six seven\n";
8462        let m = map_at(src, Some(24));
8463        let text = rendered(&m);
8464        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
8465        // Continuation lines hang under the marker, as a list item's do — the
8466        // indent is the marker's own width, not a fixed one.
8467        assert_eq!(lines[1].trim_end(), "[src] one two three four");
8468        assert!(
8469            lines[2].starts_with("      "),
8470            "body doesn't hang: {:?}",
8471            lines[2]
8472        );
8473        assert_eq!(lines[2].trim(), "five six seven");
8474    }
8475
8476    #[test]
8477    fn a_code_block_leaves_exactly_one_blank_row_below_it() {
8478        // The closing fence line used to be miscounted as a blank separator,
8479        // opening a phantom second gap under the block. One block boundary is
8480        // one blank row, code block or not.
8481        let src = "para\n\n```\ncode\n```\n\nafter\n";
8482        let m = map(src);
8483        let code_end = m.code_blocks[0].rows_span.end;
8484        let after = m
8485            .rows
8486            .iter()
8487            .position(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "after")
8488            .unwrap();
8489        assert_eq!(
8490            after - code_end,
8491            1,
8492            "exactly one row between code and 'after'"
8493        );
8494    }
8495
8496    #[test]
8497    fn a_fenced_block_publishes_its_language_on_its_code_block() {
8498        // The info string becomes the block's label; a bare fence and an indented
8499        // block carry none.
8500        assert_eq!(
8501            map("```rust\nlet x = 1;\n```\n").code_blocks[0]
8502                .lang
8503                .as_deref(),
8504            Some("rust")
8505        );
8506        assert_eq!(map("```\nplain\n```\n").code_blocks[0].lang, None);
8507        assert_eq!(map("    indented\n").code_blocks[0].lang, None);
8508    }
8509
8510    fn lang_of(src: &str) -> Option<String> {
8511        map(src).code_blocks[0].lang.clone()
8512    }
8513
8514    #[test]
8515    fn a_fence_in_a_quote_has_its_language() {
8516        // The block's span starts at the line, `> ` and all; the fence is past
8517        // the quote marker, and so is its info string.
8518        let src = "> ```rust\n> let x = 1;\n> ```\n";
8519        assert_eq!(lang_of(src).as_deref(), Some("rust"));
8520        let info = code_info_span(src, 0).unwrap();
8521        assert_eq!(&src[info], "rust", "the info string's exact bytes");
8522        assert_eq!(
8523            lang_of("> > ~~~ py\n> > x\n> > ~~~\n").as_deref(),
8524            Some("py")
8525        );
8526    }
8527
8528    #[test]
8529    fn a_fence_in_a_list_item_has_its_language() {
8530        // On the item's own line, past its marker…
8531        assert_eq!(
8532            lang_of("- ```rust\n  let x = 1;\n  ```\n").as_deref(),
8533            Some("rust")
8534        );
8535        assert_eq!(
8536            lang_of("10. ```rust\n    let x = 1;\n    ```\n").as_deref(),
8537            Some("rust")
8538        );
8539        // …and on a line of its own inside the item, where the indent is the
8540        // item's content column and not the fence's.
8541        assert_eq!(
8542            lang_of("10. a\n\n    ```rust\n    let x = 1;\n    ```\n").as_deref(),
8543            Some("rust")
8544        );
8545        assert_eq!(
8546            lang_of("- a\n  - b\n\n    ```rust\n    x\n    ```\n").as_deref(),
8547            Some("rust")
8548        );
8549        // In a list in a quote.
8550        assert_eq!(
8551            lang_of("> - a\n>\n>   ```rust\n>   x\n>   ```\n").as_deref(),
8552            Some("rust")
8553        );
8554    }
8555
8556    #[test]
8557    fn an_indented_block_in_a_list_item_still_has_no_language() {
8558        // Four spaces past the item's content column is an indented code
8559        // block, whatever its text looks like — the allowance is measured from
8560        // the item, not dropped.
8561        let src = "- a\n\n      ```rust\n";
8562        assert_eq!(map(src).code_blocks.len(), 1);
8563        assert_eq!(lang_of(src), None);
8564        assert_eq!(lang_of("- a\n\n      indented\n"), None);
8565    }
8566
8567    /// The token every glyph spelling `ch` carries, in row order — how a test
8568    /// reads a block's highlighting off the map.
8569    fn tokens_of(m: &VisualMap, ch: char) -> Vec<Option<Token>> {
8570        m.rows
8571            .iter()
8572            .flat_map(|r| r.glyphs.iter())
8573            .filter(|g| g.ch == ch)
8574            .map(|g| g.style.token)
8575            .collect()
8576    }
8577
8578    #[cfg(feature = "syntax")]
8579    #[test]
8580    fn a_fenced_block_in_a_known_language_carries_tokens() {
8581        // `let` is a keyword, the string literal a string, and the plain
8582        // identifier `x` nothing at all — it draws in the code colour. Every
8583        // glyph is still `Role::Code`: a token is beside the role, not instead.
8584        let m = map("```rust\nlet x = \"s\";\n```\n");
8585        assert_eq!(tokens_of(&m, 'l'), vec![Some(Token::Keyword)]);
8586        assert_eq!(tokens_of(&m, 'x'), vec![None]);
8587        assert_eq!(tokens_of(&m, '"'), vec![Some(Token::String); 2]);
8588        assert!(
8589            m.rows
8590                .iter()
8591                .filter(|r| r.code)
8592                .flat_map(|r| r.glyphs.iter())
8593                .all(|g| g.style.role == Role::Code),
8594            "a token replaced the code role"
8595        );
8596    }
8597
8598    #[cfg(feature = "syntax")]
8599    #[test]
8600    fn a_token_changes_nothing_about_where_a_glyph_is() {
8601        // The same block with and without a language it can be highlighted in
8602        // lays out identically: same rows, same offsets, same stops. Only the
8603        // token differs, so the caret walks a highlighted block as it walked an
8604        // unhighlighted one.
8605        let hl = map("```rust\nlet x = 1; // c\nfn f() {}\n```\n");
8606        let plain = map("```text\nlet x = 1; // c\nfn f() {}\n```\n");
8607        assert_eq!(hl.rows.len(), plain.rows.len());
8608        for (a, b) in hl.rows.iter().zip(&plain.rows) {
8609            assert_eq!(a.end_src, b.end_src);
8610            assert_eq!(a.glyphs.len(), b.glyphs.len());
8611            for (ga, gb) in a.glyphs.iter().zip(&b.glyphs) {
8612                assert_eq!((ga.ch, ga.src, ga.stop), (gb.ch, gb.src, gb.stop));
8613                assert_eq!(ga.style.token(None), gb.style);
8614            }
8615        }
8616        assert!(tokens_of(&hl, 'l').iter().any(Option::is_some));
8617        assert!(tokens_of(&plain, 'l').iter().all(Option::is_none));
8618    }
8619
8620    #[test]
8621    fn a_block_with_no_language_to_highlight_in_carries_no_tokens() {
8622        // A bare fence, an indented block, a fence in a language no grammar
8623        // covers, and inline code all draw as plain code — and so does a
8624        // `rust` fence when the `syntax` feature is off.
8625        for src in [
8626            "```\nlet x = 1;\n```\n",
8627            "    let x = 1;\n",
8628            "```no-such-language\nlet x = 1;\n```\n",
8629            "a `let x` b\n",
8630        ] {
8631            assert!(
8632                tokens_of(&map(src), 'l').iter().all(Option::is_none),
8633                "{src:?} was highlighted"
8634            );
8635        }
8636        #[cfg(not(feature = "syntax"))]
8637        assert!(
8638            tokens_of(&map("```rust\nlet x = 1;\n```\n"), 'l')
8639                .iter()
8640                .all(Option::is_none)
8641        );
8642    }
8643
8644    #[test]
8645    fn inline_code_is_not_a_code_block() {
8646        // A `code` span inside prose is styled by role, not boxed: it's part of a
8647        // normal paragraph row, so it names no `code_blocks` entry.
8648        let m = map("a `snippet` b\n");
8649        assert!(m.code_blocks.is_empty(), "inline code wrongly boxed");
8650        assert!(
8651            m.rows.iter().all(|r| !r.code),
8652            "inline code flagged a code row"
8653        );
8654    }
8655
8656    #[test]
8657    fn caret_steps_over_hidden_delimiters() {
8658        // "a **bold** c": bytes 8,9 are the closing ** — no glyph. Moving right
8659        // from 'd' (src 7) lands on the space before 'c' (src 10), not inside **.
8660        let m = map("a **bold** c\n");
8661        let (r, c) = m.pos_of_offset(7);
8662        assert_eq!(m.offset_of_pos(r, c + 1), 10);
8663    }
8664
8665    // ── the structural view of a table ───────────────────────────────────────
8666
8667    #[test]
8668    fn a_table_is_published_structurally_beside_its_picture() {
8669        let m = map(TABLE);
8670        let t = &m.tables[0];
8671        let cell = |r: usize, c: usize| -> String {
8672            t.grid[r].cells[c].glyphs.iter().map(|g| g.ch).collect()
8673        };
8674        assert_eq!(t.grid.len(), 3, "head + two body rows");
8675        assert_eq!(
8676            (cell(0, 0), cell(0, 1), cell(1, 0), cell(2, 1)),
8677            ("Name".into(), "Qty".into(), "Pear".into(), "12".into())
8678        );
8679        assert_eq!(
8680            t.grid.iter().map(|r| r.head).collect::<Vec<_>>(),
8681            [true, false, false]
8682        );
8683        // The alignment the delimiter row spelled, carried per cell — the only
8684        // place it survives, since the parser consumes that row.
8685        assert!(matches!(t.grid[1].cells[0].align, Alignment::Left));
8686        assert!(matches!(t.grid[1].cells[1].align, Alignment::Right));
8687    }
8688
8689    #[test]
8690    fn a_block_media_is_published_structurally_beside_its_placeholder() {
8691        let m = map("intro\n\n![a cat](img/cat.png)\n\nend\n");
8692        assert_eq!(m.media.len(), 1, "one block image");
8693        let img = &m.media[0];
8694        assert_eq!(img.destination, "img/cat.png");
8695        assert_eq!(img.alt, "a cat");
8696        // The placeholder row named by `rows_span` carries the label a plain
8697        // surface paints and a capable frontend replaces.
8698        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
8699        assert_eq!(
8700            img.rows_span.end - img.rows_span.start,
8701            1,
8702            "one placeholder row"
8703        );
8704        assert_eq!(row_text(img.rows_span.start), "🖼 a cat");
8705        // The row carries the mark `media_spans` derives the side-table from.
8706        assert!(m.rows[img.rows_span.start].media.is_some());
8707    }
8708
8709    #[test]
8710    fn an_image_without_alt_labels_itself_with_its_filename() {
8711        let m = map("![](photos/beach.jpg)\n");
8712        let row = &m.rows[m.media[0].rows_span.start];
8713        assert_eq!(
8714            row.glyphs.iter().map(|g| g.ch).collect::<String>(),
8715            "🖼 beach.jpg"
8716        );
8717        assert_eq!(m.media[0].alt, "");
8718    }
8719
8720    #[test]
8721    fn an_empty_cells_home_is_read_from_either_shape_of_span() {
8722        // A whole-row span: the cell's pipes are the `col`-th and next.
8723        let row = "|  |  |";
8724        assert_eq!(empty_cell_offset(row, 10, 0), 12);
8725        assert_eq!(empty_cell_offset(row, 10, 1), 15);
8726        // A cell's own span, opening pipe to closing pipe exclusive: the same
8727        // homes, each read from its own span.
8728        assert_eq!(empty_cell_offset("|  ", 10, 0), 12);
8729        assert_eq!(empty_cell_offset("|  ", 13, 1), 15);
8730        // Nothing to stand in: just inside the pipe, never past the span.
8731        assert_eq!(empty_cell_offset("|", 10, 0), 11);
8732        assert_eq!(empty_cell_offset("", 10, 1), 10);
8733    }
8734
8735    #[test]
8736    fn a_hidden_marks_content_end_is_a_caret_home_but_not_a_glyph_stop() {
8737        // `a **bold** b`: the `d` is at 7, the content ends at 8, the closing
8738        // `**` draws nothing, and the space after it is at 10. Two homes at one
8739        // spot on screen: 8 (inside the bold) and 10 (past it).
8740        let m = map("a **bold** b\n");
8741        assert!(
8742            !m.stops.contains(&8),
8743            "8 has no glyph, so it is no glyph stop"
8744        );
8745        assert_eq!(m.mark_ends, vec![8]);
8746        assert!(m.is_stop(8), "but the caret may rest there");
8747        assert_eq!(m.snap_to_stop(8), 8, "and is left there when placed there");
8748        // Left/Right take both homes; the character-pairing walk takes one.
8749        assert_eq!(m.caret_stop_after(7), Some(8));
8750        assert_eq!(m.caret_stop_after(8), Some(10));
8751        assert_eq!(m.caret_stop_before(10), Some(8));
8752        assert_eq!(m.caret_stop_before(8), Some(7));
8753        assert_eq!(m.stop_after(7), Some(10));
8754        assert_eq!(m.stop_before(10), Some(7));
8755        // Drawn where the next glyph is: after the `d`, not on it.
8756        assert_eq!(m.pos_of_offset(8), m.pos_of_offset(10));
8757    }
8758
8759    #[test]
8760    fn every_hidden_inline_mark_gives_its_content_end_a_home() {
8761        // One end per mark, whatever it is spelled with; nested marks closing
8762        // together share the outer's end and the inner's alike.
8763        assert_eq!(
8764            map("*em* `code` [link](u) ~~del~~\n").mark_ends,
8765            vec![3, 10, 17, 27]
8766        );
8767        assert_eq!(map("***both***\n").mark_ends, vec![7]);
8768        // A mark that closes at its row's end coincides with the row's own end
8769        // stop — one offset, in both tables.
8770        let m = map("**bold**\n");
8771        assert_eq!(m.mark_ends, vec![6]);
8772        assert!(m.stops.contains(&6));
8773        // Revealed, the delimiter is glyphs of its own and the end is an
8774        // ordinary glyph stop: nothing to add.
8775        let mut ed = Editor::new_str("a **bold** b\n", Format::Markdown).unwrap();
8776        let src = "a **bold** b\n";
8777        let revealed = build(
8778            &ed.nodes().unwrap(),
8779            src,
8780            Some(80),
8781            false,
8782            &Surface::default(),
8783            Some(Reveal::full(0..src.len())),
8784        );
8785        assert!(revealed.mark_ends.is_empty());
8786        assert!(revealed.stops.contains(&8));
8787    }
8788
8789    #[test]
8790    fn a_marks_content_end_is_a_home_inside_a_table_cell() {
8791        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
8792        let m = map(src);
8793        let end = src.find("bold").unwrap() + 4; // 32, before the closing `**`
8794        assert_eq!(m.mark_ends, vec![end]);
8795        assert_eq!(m.snap_to_stop(end), end);
8796        // Drawn after the `d`, in this cell — where the cell's own end stop is.
8797        assert_eq!(m.pos_of_offset(end), m.pos_of_offset(end + 2));
8798    }
8799
8800    #[test]
8801    fn a_block_media_gives_the_caret_a_home_before_and_after_it() {
8802        // `![x](y)` on its own line: the caret can rest in front of the image
8803        // (its start) and just past it (the row end), and nowhere inside the
8804        // markup — the same coarse mapping a thematic break uses.
8805        let src = "![x](y.png)\n";
8806        let m = map(src);
8807        let img = &m.rows[m.media[0].rows_span.start];
8808        let start = 0; // the image opens the document
8809        let end = "![x](y.png)".len();
8810        // Every placeholder glyph maps to the image start and is a stop there.
8811        assert!(img.glyphs.iter().all(|g| g.src == start && g.stop));
8812        assert_eq!(img.end_src, end, "the row ends past the image");
8813        assert_eq!(m.stops.first(), Some(&start));
8814        assert!(m.stops.contains(&end), "a stop sits after the image");
8815        // Nothing inside the markup is a stop.
8816        assert!(!m.stops.iter().any(|&s| s > start && s < end));
8817    }
8818
8819    #[test]
8820    fn an_inline_image_amid_text_is_not_a_block_media() {
8821        // An image sharing its line with prose isn't block-level: it stays in the
8822        // inline path (rendered as its alt text), and publishes no MediaInfo.
8823        let m = map("see ![a cat](cat.png) here\n");
8824        assert!(m.media.is_empty(), "not a block image");
8825        assert!(
8826            rendered(&m).contains("a cat"),
8827            "alt text still renders inline"
8828        );
8829    }
8830
8831    /// The block images `Doc` publishes for `src`, driven through the real
8832    /// production build (`build_visual` → `build_cached`) with `html_elements`
8833    /// on — the path a `<picture>` actually travels. Not the raw `build` the
8834    /// other tests use: the editor's flat whole-arena snapshot tangles the links
8835    /// of inline-promoted HTML (phantom roots, dangling `parent`s), which only
8836    /// the per-block subtree walk `build_cached` does untangles.
8837    fn doc_media(src: &str) -> Vec<MediaInfo> {
8838        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
8839        doc.build_visual(80);
8840        doc.vmap.media.clone()
8841    }
8842
8843    #[test]
8844    fn a_video_block_is_media_with_its_src_poster_and_kind() {
8845        // The load-bearing assumption of video support: twig has no `video` node
8846        // kind, so `html_elements` promotion must land a `<video>` as a generic
8847        // `element` whose tag name and attributes survive onto `FlatNode` — the
8848        // same treatment `<picture>` gets. If that ever stops holding, this is
8849        // the test that says so.
8850        let m = doc_media("<video src=\"clip.mp4\" poster=\"still.png\" controls>\n</video>\n");
8851        assert_eq!(m.len(), 1, "the video is one block media");
8852        assert_eq!(m[0].kind, MediaKind::Video);
8853        assert_eq!(m[0].destination, "clip.mp4");
8854        assert_eq!(m[0].poster, "still.png");
8855    }
8856
8857    #[test]
8858    fn a_single_line_video_is_a_block_too() {
8859        // The spelling everyone actually writes. It used to parse as a paragraph
8860        // of raw inline HTML — CommonMark opens a block on a complete tag only
8861        // when the line ends there, and its fixed tag list predates `<video>` —
8862        // so the tags never reached core as an element at all. twig 2.5.1 widened
8863        // that list under `html_elements`; this is the test that would catch the
8864        // pin sliding back.
8865        let m = doc_media("<video src=\"clip.mp4\" controls></video>\n");
8866        assert_eq!(m.len(), 1, "single-line <video> is a block");
8867        assert_eq!(m[0].kind, MediaKind::Video);
8868        assert_eq!(m[0].destination, "clip.mp4");
8869    }
8870
8871    #[test]
8872    fn a_single_line_picture_is_a_block_with_its_alternatives() {
8873        // `<picture>` had the identical gap and it went unnoticed because the
8874        // conventional spelling breaks the lines. Same twig fix covers it.
8875        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\">\
8876                   <img src=\"l.svg\" alt=\"banner\"></picture>\n";
8877        let m = doc_media(src);
8878        assert_eq!(m.len(), 1);
8879        assert_eq!(m[0].kind, MediaKind::Image);
8880        assert_eq!(m[0].destination, "l.svg");
8881        assert_eq!(m[0].resolve(ColorScheme::Dark), "d.svg");
8882    }
8883
8884    #[test]
8885    fn an_audio_block_is_media_with_no_poster() {
8886        let m = doc_media("<audio src=\"take.mp3\" controls>\n</audio>\n");
8887        assert_eq!(m.len(), 1);
8888        assert_eq!(m[0].kind, MediaKind::Audio);
8889        assert_eq!(m[0].destination, "take.mp3");
8890        assert!(m[0].poster.is_empty(), "audio has no poster frame");
8891    }
8892
8893    #[test]
8894    fn a_videos_source_children_are_its_candidates_typed_by_mime() {
8895        // A `<video>` with no `src` of its own — the common shape, since it's how
8896        // you offer more than one codec. The candidates come from `<source src>`
8897        // (not `srcset`, which is `<picture>`'s spelling) and carry their MIME.
8898        let src = "<video controls>\n\
8899                   <source src=\"a.webm\" type=\"video/webm\">\n\
8900                   <source src=\"a.mp4\" type=\"video/mp4\">\n\
8901                   fallback\n\
8902                   </video>\n";
8903        let m = doc_media(src);
8904        assert_eq!(m.len(), 1);
8905        assert!(
8906            m[0].destination.is_empty(),
8907            "no src attribute on the element"
8908        );
8909        assert_eq!(m[0].sources.len(), 2);
8910        assert_eq!(m[0].sources[0].srcset, "a.webm");
8911        assert_eq!(m[0].sources[0].mime, "video/webm");
8912        assert_eq!(m[0].sources[1].srcset, "a.mp4");
8913        // With an empty destination, `resolve` falls through to the first
8914        // candidate rather than handing the frontend nothing to load.
8915        assert_eq!(m[0].resolve(ColorScheme::Light), "a.webm");
8916    }
8917
8918    #[test]
8919    fn a_video_placeholder_row_carries_its_own_sigil_and_mark() {
8920        // The placeholder contract images already hold, now for a video: the row
8921        // renders as a labelled stand-in a plain surface can paint as-is, and
8922        // carries the mark a capable frontend replaces it from.
8923        let src = "<video src=\"clip.mp4\" controls>\n</video>\n";
8924        let mut doc = crate::Doc::from_source(src.to_string(), Format::Markdown).unwrap();
8925        doc.build_visual(80);
8926        let row = &doc.vmap.rows[doc.vmap.media[0].rows_span.start];
8927        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
8928        assert!(
8929            text.starts_with('🎬'),
8930            "video sigil, not the image one: {text:?}"
8931        );
8932        assert!(row.media.is_some(), "the mark rides the placeholder row");
8933    }
8934
8935    #[test]
8936    fn a_picture_block_carries_its_source_alternatives() {
8937        // A `<picture>` with a dark-mode `<source>`: one block image, whose
8938        // fallback destination is the `<img>` and whose `sources` carry the
8939        // `<source>`'s media + srcset for a theme-aware frontend to pick.
8940        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"banner\"></picture>\n";
8941        let images = doc_media(src);
8942        assert_eq!(images.len(), 1, "the picture is one block image");
8943        let img = &images[0];
8944        assert_eq!(img.destination, "light.svg", "fallback is the <img>");
8945        assert_eq!(img.alt, "banner");
8946        assert_eq!(
8947            img.sources,
8948            vec![MediaSource {
8949                media: "(prefers-color-scheme: dark)".into(),
8950                srcset: "dark.svg".into(),
8951                mime: String::new(),
8952            }],
8953        );
8954    }
8955
8956    #[test]
8957    fn a_picture_inside_a_heading_is_still_a_block_media_with_sources() {
8958        // fig.md's shape: the banner is an `<h1>` wrapping the `<picture>`.
8959        let src = "<h1><picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"d.svg\"><img src=\"l.svg\" alt=\"fig\"></picture></h1>\n";
8960        let images = doc_media(src);
8961        assert_eq!(images.len(), 1, "heading-wrapped picture is a block image");
8962        assert_eq!(images[0].destination, "l.svg");
8963        assert_eq!(images[0].sources.len(), 1);
8964        assert_eq!(images[0].sources[0].srcset, "d.svg");
8965    }
8966
8967    #[test]
8968    fn a_plain_image_has_no_media_sources() {
8969        // A bare Markdown image carries an empty `sources` — nothing to pick from.
8970        let images = doc_media("![alt](p.png)\n");
8971        assert_eq!(images.len(), 1);
8972        assert!(
8973            images[0].sources.is_empty(),
8974            "no <picture>, no alternatives"
8975        );
8976    }
8977
8978    #[test]
8979    fn resolve_picks_the_source_matching_the_scheme() {
8980        let src = "<picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"dark.svg\"><img src=\"light.svg\" alt=\"b\"></picture>\n";
8981        let images = doc_media(src);
8982        let img = &images[0];
8983        // Dark theme takes the dark source; light falls through to the <img>.
8984        assert_eq!(img.resolve(ColorScheme::Dark), "dark.svg");
8985        assert_eq!(img.resolve(ColorScheme::Light), "light.svg");
8986    }
8987
8988    #[test]
8989    fn resolve_falls_back_for_a_plain_image_and_unknown_media() {
8990        // A plain image ignores the scheme.
8991        let plain = doc_media("![a](p.png)\n");
8992        assert_eq!(plain[0].resolve(ColorScheme::Dark), "p.png");
8993
8994        // A <source> with an unrecognized media query is skipped; a light source
8995        // is taken under a light theme.
8996        let m = doc_media(
8997            "<picture><source media=\"print\" srcset=\"p.svg\"><source media=\"(prefers-color-scheme: light)\" srcset=\"l.svg\"><img src=\"f.svg\" alt=\"x\"></picture>\n",
8998        );
8999        assert_eq!(m[0].resolve(ColorScheme::Light), "l.svg");
9000        assert_eq!(
9001            m[0].resolve(ColorScheme::Dark),
9002            "f.svg",
9003            "no dark source → <img>"
9004        );
9005    }
9006
9007    #[test]
9008    fn resolve_reads_the_first_srcset_url_ignoring_descriptors() {
9009        // A comma/descriptor srcset resolves to its first URL.
9010        assert_eq!(first_srcset_url("a.png 1x, b.png 2x"), Some("a.png"));
9011        assert_eq!(first_srcset_url("  solo.svg  "), Some("solo.svg"));
9012        assert_eq!(first_srcset_url(""), None);
9013        // An empty (unconditional) media always matches.
9014        assert!(media_matches("", ColorScheme::Light));
9015        assert!(media_matches(
9016            "(prefers-color-scheme:dark)",
9017            ColorScheme::Dark
9018        ));
9019        assert!(!media_matches(
9020            "(prefers-color-scheme: dark)",
9021            ColorScheme::Light
9022        ));
9023    }
9024
9025    #[test]
9026    fn a_block_media_carries_its_list_prefix() {
9027        // An image that is a list item's body opens past the bullet, like every
9028        // other block does.
9029        let m = map("- ![alt](p.png)\n");
9030        let row = &m.rows[m.media[0].rows_span.start];
9031        let text: String = row.glyphs.iter().map(|g| g.ch).collect();
9032        assert!(
9033            text.starts_with("• "),
9034            "the list marker prefixes the image row: {text:?}"
9035        );
9036        assert!(text.contains("🖼 alt"));
9037    }
9038
9039    #[test]
9040    fn the_structural_table_spans_exactly_its_drawn_rows() {
9041        // A frontend drawing its own grid skips `rows_span` and renders from
9042        // `grid`. If the span were short the leftover border rows would be
9043        // painted as text under the real table; if long it would eat a
9044        // neighbouring paragraph. Both are silent, so pin it to the picture.
9045        let m = map(&format!("before\n\n{TABLE}\nafter\n"));
9046        let t = &m.tables[0];
9047        let row_text = |r: usize| -> String { m.rows[r].glyphs.iter().map(|g| g.ch).collect() };
9048        assert!(
9049            row_text(t.rows_span.start).starts_with('┌'),
9050            "opens on the top border"
9051        );
9052        assert!(
9053            row_text(t.rows_span.end - 1).starts_with('└'),
9054            "closes on the bottom border"
9055        );
9056        assert!(
9057            !row_text(t.rows_span.start - 1).contains('┌'),
9058            "the row before the span is not the table's"
9059        );
9060        assert_eq!(
9061            row_text(t.rows_span.end),
9062            "",
9063            "the span ends before the gap row"
9064        );
9065    }
9066
9067    #[test]
9068    fn a_nested_tables_structure_carries_the_block_prefix() {
9069        // The picture puts the quote's gutter on every row of the grid. A
9070        // frontend drawing its own table has to draw that too and start past it,
9071        // so the prefix has to travel with the structure — without it a quoted
9072        // table renders flush at the margin and leaves the quote it's in.
9073        let m = map("> | a | b |\n> |---|---|\n> | c | d |\n");
9074        let t = &m.tables[0];
9075        let prefix: String = t.prefix.iter().map(|g| g.ch).collect();
9076        assert_eq!(prefix, "│ ", "the quote's gutter should ride the structure");
9077        // And it matches what the picture actually drew.
9078        let drawn: String = m.rows[t.rows_span.start]
9079            .glyphs
9080            .iter()
9081            .map(|g| g.ch)
9082            .collect();
9083        assert!(
9084            drawn.starts_with(&prefix),
9085            "picture and structure disagree: {drawn:?}"
9086        );
9087    }
9088
9089    #[test]
9090    fn a_top_level_table_carries_no_prefix() {
9091        assert!(map(TABLE).tables[0].prefix.is_empty());
9092    }
9093
9094    #[test]
9095    fn structural_cells_are_unwrapped_even_when_the_picture_wraps_them() {
9096        // The picture wraps a cell to its column; a frontend laying the grid out
9097        // in pixels needs the text as the document spells it, before that
9098        // decision. Narrow enough that the drawn cell must break.
9099        let src = "| Name |\n|------|\n| alpha beta gamma |\n";
9100        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
9101        let m = build_t(&ed.nodes().unwrap(), src, Some(12));
9102        let drawn = rendered(&m);
9103        let cell: String = m.tables[0].grid[1].cells[0]
9104            .glyphs
9105            .iter()
9106            .map(|g| g.ch)
9107            .collect();
9108        assert_eq!(
9109            cell, "alpha beta gamma",
9110            "structure must not carry the wrap"
9111        );
9112        assert!(
9113            drawn.lines().count() > 5,
9114            "the picture should have wrapped, else this proves nothing:\n{drawn}"
9115        );
9116    }
9117
9118    // ── display columns ──────────────────────────────────────────────────────
9119
9120    #[test]
9121    fn a_table_column_is_as_wide_as_its_cells_are_drawn() {
9122        // A column sized by counting characters is drawn narrower than the text
9123        // it has to hold — `你好` is two characters in four cells — and the cell
9124        // spills over the border it is supposed to sit inside, taking the whole
9125        // grid out of square with it. Squareness is the property: every row of a
9126        // grid is drawn to the same column, whatever its cells are spelled with.
9127        for src in [
9128            "| A | B |\n|---|---|\n| 你好 | y |\n",
9129            "| A | B |\n|---|---|\n| a👨‍👩‍👧b | y |\n",
9130            "| A | 漢字 |\n|---|---|\n| x | y |\n",
9131        ] {
9132            let m = map(src);
9133            let widths: Vec<usize> = m.rows.iter().map(|r| r.width()).collect();
9134            assert!(
9135                widths.windows(2).all(|w| w[0] == w[1]),
9136                "ragged grid {widths:?} for {src:?}:\n{}",
9137                rendered(&m)
9138            );
9139        }
9140    }
9141
9142    #[test]
9143    fn a_cell_wrapped_narrow_never_breaks_inside_a_character() {
9144        // A column too narrow for its cell hard-breaks the text, and every line
9145        // of it is given an end stop just past its last glyph. Broken into runs
9146        // of four glyphs, the first line of this cell ends between `👨‍👩` and the
9147        // joiner holding `👧` on — so its end stop lands inside a character,
9148        // where a click or Down can reach it and the next Backspace takes the
9149        // cluster apart from the middle.
9150        let src = "| A |\n|---|\n| 👨‍👩‍👧👨‍👩‍👧 |\n";
9151        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
9152        let m = build_t(&ed.nodes().unwrap(), src, Some(8));
9153        let boundaries: Vec<usize> = src
9154            .grapheme_indices(true)
9155            .map(|(i, _)| i)
9156            .chain(std::iter::once(src.len()))
9157            .collect();
9158        for off in (0..=src.len()).filter(|&o| m.is_stop(o)) {
9159            assert!(
9160                boundaries.contains(&off),
9161                "stop at {off} is inside a character:\n{}",
9162                rendered(&m)
9163            );
9164        }
9165    }
9166
9167    #[test]
9168    fn a_wrapped_cell_keeps_every_line_inside_its_column() {
9169        // The width is a promise in a table, where a glyph past the column lands
9170        // on the border or in the next cell — and it is a promise about cells,
9171        // which is not what a count of glyphs measures.
9172        let src = "| A |\n|---|\n| 你好世界漢字 |\n";
9173        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
9174        let m = build_t(&ed.nodes().unwrap(), src, Some(14));
9175        for r in &m.rows {
9176            assert_eq!(r.width(), 14, "{:?} is not drawn to the grid", rendered(&m));
9177        }
9178    }
9179
9180    #[test]
9181    fn a_hard_break_falls_between_clusters_and_measures_in_cells() {
9182        let glyphs = |s: &str| {
9183            let mut out = Vec::new();
9184            push_text(&mut out, s, 0, Style::default());
9185            out
9186        };
9187        let piece = |p: &[Glyph]| p.iter().map(|g| g.ch).collect::<String>();
9188
9189        // Six cells of CJK broken at four: two characters, then one — never
9190        // between the two cells of `好`.
9191        let w = glyphs("你好世");
9192        let pieces: Vec<String> = hard_break(&w, 4).iter().map(|p| piece(p)).collect();
9193        assert_eq!(pieces, ["你好", "世"]);
9194
9195        // A character wider than the column has nowhere legal to break, so it
9196        // keeps its cells rather than being cut in half.
9197        let w = glyphs("你好");
9198        let pieces: Vec<String> = hard_break(&w, 1).iter().map(|p| piece(p)).collect();
9199        assert_eq!(pieces, ["你", "好"]);
9200
9201        // An empty word yields no pieces at all — a double space stays a space.
9202        assert!(hard_break(&[], 4).is_empty());
9203    }
9204
9205    #[test]
9206    fn an_empty_list_item_still_gets_a_bulleted_row_with_a_caret_home() {
9207        // Pressing Enter at the end of a list item opens a new, empty item —
9208        // a childless `list_item`. Without a row of its own the new bullet
9209        // wouldn't appear until something was typed into it (the caret would be
9210        // stranded on an offset no row draws). It now renders as one prefixed
9211        // row whose end is a caret stop, so the bullet shows and the caret lands
9212        // just past the marker.
9213        let m = map("- item\n- \n");
9214        assert_eq!(m.num_rows(), 2, "the empty second item needs its own row");
9215        assert_eq!(
9216            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
9217            "• ",
9218            "the empty item draws just its bullet",
9219        );
9220        // Its end is the caret home (past the `- ` marker), and it's a real stop.
9221        assert!(
9222            m.is_stop(m.rows[1].end_src),
9223            "the empty item's caret home is not a stop"
9224        );
9225        assert_eq!(
9226            m.pos_of_offset(m.rows[1].end_src),
9227            (1, 2),
9228            "caret sits after '• '"
9229        );
9230    }
9231
9232    #[test]
9233    fn a_notes_row_range_stops_at_the_note_even_when_it_ends_in_a_link() {
9234        // The peek bug: a note whose body ends in a link has its last byte
9235        // inside the hidden destination, so mapping `end - 1` through
9236        // `pos_of_offset` snapped *forward* — past its own row, past the drawn
9237        // gap, and onto the next note's row. The popover then drew both notes.
9238        let src = "A[^1] B[^2].\n\n[^1]: bare text\n\n[^2]: [title](https://example.com/x)\n\n[^3]: last\n";
9239        let m = map(src);
9240        let body = src.find("[title]").unwrap();
9241        let end = src.find("\n\n[^3]").unwrap();
9242
9243        let (first, last) = m.row_range_for(body..end);
9244        assert_eq!(
9245            first, last,
9246            "a one-block note is one row, not a span onto the next"
9247        );
9248
9249        // The old arithmetic, kept here as the thing that must stay wrong: it
9250        // is what this method exists instead of.
9251        assert_ne!(
9252            m.pos_of_offset(end - 1).0,
9253            last,
9254            "the forward snap still leaves the note's row — that is the whole point",
9255        );
9256
9257        // A note ending in *visible* text was never broken, and still isn't:
9258        // both readings agree there, which is why the original test missed it.
9259        let plain = src.find("bare text").unwrap();
9260        let plain_end = src.find("\n\n[^2]").unwrap();
9261        let (pf, pl) = m.row_range_for(plain..plain_end);
9262        assert_eq!(pf, pl);
9263        assert_eq!(m.pos_of_offset(plain_end - 1).0, pl);
9264    }
9265
9266    #[test]
9267    fn a_row_range_covers_every_row_of_a_block_that_spans_several() {
9268        // The range is a span, not a point: a quote of two paragraphs covers its
9269        // gap row and both of its text rows, so a peek draws the whole thing.
9270        let src = "> one\n>\n> two\n\nafter\n";
9271        let m = map(src);
9272        let (first, last) = m.row_range_for(0..src.find("\n\nafter").unwrap());
9273        assert_eq!((first, last), (0, 2));
9274
9275        // And a range with no visible byte at all still covers the row it opened
9276        // on, rather than collapsing to nothing.
9277        let (f, l) = m.row_range_for(0..1);
9278        assert_eq!((f, l), (0, 0));
9279    }
9280
9281    #[test]
9282    fn an_empty_block_quote_still_gets_a_gutter_row_with_a_caret_home() {
9283        // The peer of the empty list item, and the case that made an empty line
9284        // in a quote draw as plain body text: a childless `block_quote` — a bare
9285        // `> `, which is what the toolbar's Quote button leaves on a blank line —
9286        // has no inner block to carry the gutter, so the whole quote used to
9287        // render as *nothing*. It didn't merely lose its bar; the row went away
9288        // and the caret had no home on it.
9289        let m = map("a\n\n> \n\nb\n");
9290        assert_eq!(
9291            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
9292            "│ ",
9293            "the empty quote draws just its gutter",
9294        );
9295        assert!(
9296            m.rows[2]
9297                .glyphs
9298                .iter()
9299                .all(|g| g.style.role == Role::QuoteGutter)
9300        );
9301        assert!(
9302            !m.rows[2].decoration,
9303            "it is a line text can go on, not a drawn gap"
9304        );
9305        assert!(
9306            m.is_stop(m.rows[2].end_src),
9307            "the empty quote's caret home is not a stop"
9308        );
9309        assert_eq!(
9310            m.pos_of_offset(m.rows[2].end_src),
9311            (2, 2),
9312            "caret sits after '│ '"
9313        );
9314
9315        // And a document that is *only* an empty quote still renders a row — it
9316        // used to render none at all, leaving the caret nowhere to stand.
9317        let m = map("> \n");
9318        assert_eq!(m.num_rows(), 1);
9319        assert_eq!(
9320            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
9321            "│ "
9322        );
9323    }
9324
9325    #[test]
9326    fn a_quotes_own_trailing_marker_lines_stay_inside_the_quote() {
9327        // Enter at the end of `> a` writes `> a\n>\n> \n`. Those last two lines
9328        // hold no block — a quote's `content_span` stops at its last child — so
9329        // the children walk never reaches them, and they used to fall through to
9330        // the document-level trailing pass, which knows no prefix: the gutter
9331        // stopped and the writer's new line drew as plain prose. Fixable only
9332        // since twig 3.2.0, where the quote's *span* covers its own marker lines
9333        // (`0..3` before, `0..8` now) and there is finally a node saying they
9334        // are the quote's.
9335        let m = map("> a\n>\n> \n");
9336        assert_eq!(m.num_rows(), 3, "one row per line the quote spells");
9337        for (i, row) in m.rows.iter().enumerate() {
9338            let text = row.glyphs.iter().map(|g| g.ch).collect::<String>();
9339            assert!(text.starts_with("│ "), "row {i} lost the gutter: {text:?}");
9340            assert!(
9341                !row.decoration,
9342                "row {i} is a line to type on, not a drawn gap"
9343            );
9344            assert!(m.is_stop(row.end_src), "row {i} has no caret home");
9345        }
9346        assert_eq!(
9347            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
9348            "│ a"
9349        );
9350        // Distinct offsets, so ↑/↓ between them moves the caret rather than
9351        // landing twice on the same byte.
9352        assert!(m.rows[0].end_src < m.rows[1].end_src);
9353        assert!(m.rows[1].end_src < m.rows[2].end_src);
9354
9355        // A blank line *after* the quote is not the quote's: it is spelled with
9356        // no marker, so it stays an ordinary boundary and the gutter ends.
9357        let m = map("> a\n\nb\n");
9358        assert_eq!(m.num_rows(), 3);
9359        assert_eq!(
9360            m.rows[2].glyphs.iter().map(|g| g.ch).collect::<String>(),
9361            "b"
9362        );
9363        assert!(
9364            !m.rows[1]
9365                .glyphs
9366                .iter()
9367                .any(|g| g.style.role == Role::QuoteGutter)
9368        );
9369
9370        // Nesting is the case this could get wrong, and the depth has to come
9371        // from which quote's span the line falls in rather than from the row
9372        // above it. A trailing `>` under `> > a` matches only the OUTER quote,
9373        // so it wears one gutter; spell it `> >` and it wears two.
9374        let m = map("> > a\n>\n");
9375        assert_eq!(
9376            m.rows[0].glyphs.iter().map(|g| g.ch).collect::<String>(),
9377            "│ │ a"
9378        );
9379        assert_eq!(
9380            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
9381            "│ "
9382        );
9383        let m = map("> > a\n> >\n");
9384        assert_eq!(
9385            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
9386            "│ │ "
9387        );
9388
9389        // And a marker line BETWEEN two quoted paragraphs is untouched: that is
9390        // the boundary `emit_separators_before` spells, and it stays a drawn gap
9391        // rather than becoming a line to type on.
9392        let m = map("> a\n>\n> b\n");
9393        assert_eq!(m.num_rows(), 3);
9394        assert!(
9395            m.rows[1].decoration,
9396            "the gap between two quoted blocks is still a gap"
9397        );
9398    }
9399
9400    #[test]
9401    fn an_empty_ordered_item_gets_its_number_and_a_caret_home() {
9402        let m = map("1. item\n2. \n");
9403        assert_eq!(m.num_rows(), 2);
9404        assert_eq!(
9405            m.rows[1].glyphs.iter().map(|g| g.ch).collect::<String>(),
9406            "2. "
9407        );
9408        assert!(m.is_stop(m.rows[1].end_src));
9409        assert_eq!(
9410            m.pos_of_offset(m.rows[1].end_src),
9411            (1, 3),
9412            "caret sits after '2. '"
9413        );
9414    }
9415
9416    #[test]
9417    fn an_empty_headings_caret_home_is_past_its_hidden_marker() {
9418        // The toolbar's H1 on a blank line writes `# ` and nothing else. The row
9419        // it renders is empty (the marker is hidden), so its end *is* its only
9420        // caret stop — and it has to be the offset past the `# `, where typing
9421        // continues the heading. Anchored at the block's start instead, the caret
9422        // drew in front of the hashes and the first character typed there landed
9423        // before them (`x# `), which isn't a heading at all.
9424        let m = map("# \n");
9425        assert_eq!(m.num_rows(), 1);
9426        assert!(m.rows[0].glyphs.is_empty(), "the `# ` marker is hidden");
9427        assert_eq!(m.rows[0].end_src, 2, "the caret home is past the marker");
9428        assert!(m.is_stop(2), "the empty heading's caret home is not a stop");
9429    }
9430
9431    #[test]
9432    fn a_headings_rows_carry_its_level_even_with_nothing_typed_in_it() {
9433        // The row-level fact a proportional frontend sizes a whole line by. An
9434        // empty heading has no glyph to read a `Role::Heading` off, so a renderer
9435        // scanning glyphs drew `# ` (and its caret) at body height until the
9436        // first character landed.
9437        let m = map("# \n");
9438        assert_eq!(
9439            m.rows[0].heading,
9440            Some(1),
9441            "the empty heading knows its level"
9442        );
9443
9444        // Every row of one that wraps, not just the first — and nothing else.
9445        let m = map_at(
9446            "## a heading long enough to wrap over two rows\n\nbody\n",
9447            Some(20),
9448        );
9449        let heads: Vec<Option<u8>> = m.rows.iter().map(|r| r.heading).collect();
9450        assert!(
9451            heads.iter().filter(|h| **h == Some(2)).count() >= 2,
9452            "got {heads:?}"
9453        );
9454        assert_eq!(
9455            m.rows.last().and_then(|r| r.heading),
9456            None,
9457            "the paragraph under it is not a heading",
9458        );
9459    }
9460
9461    #[test]
9462    fn an_empty_heading_leaves_the_rows_under_it_at_their_own_offsets() {
9463        // The row's end is also what the *next* row's separator is measured from,
9464        // so an empty heading that under-reported it shifted every offset below —
9465        // and the blank line under the heading then claimed the same offset as the
9466        // heading's own end. `pos_of_offset` resolves such a tie downstream (a
9467        // soft wrap belongs to the row below), so the caret at the end of the
9468        // heading was drawn two rows lower, on the blank line.
9469        // `text\n\n# \n\n`: the heading's content opens at 8, and the two rows
9470        // under it end at 9 and 10 — the blank line and the document's end.
9471        let m = map("text\n\n# \n\n");
9472        let end = m.rows.last().expect("a trailing blank row").end_src;
9473        assert_eq!(end, 10, "the trailing rows must end at their real offsets");
9474        // The heading's caret home is its own row's, not one shared with a row
9475        // below — the tie that drew the caret two rows down.
9476        assert_eq!(m.pos_of_offset(8), (2, 0), "the empty heading's own row");
9477        assert!(
9478            m.rows[3..].iter().all(|r| r.end_src > 8),
9479            "rows below own later offsets"
9480        );
9481    }
9482
9483    // ── block boundaries ─────────────────────────────────────────────────────
9484
9485    /// Every drawn boundary in `src`, in order, as `(above, below)`.
9486    fn boundaries(m: &VisualMap) -> Vec<(BlockClass, BlockClass)> {
9487        m.rows
9488            .iter()
9489            .filter_map(|r| r.boundary)
9490            .map(|b| (b.above, b.below))
9491            .collect()
9492    }
9493
9494    #[test]
9495    fn a_boundary_says_which_blocks_it_divides() {
9496        use BlockClass::*;
9497        let m = map("one\n\ntwo\n\n# Head\n\ntail\n\n> quoted\n\n```\ncode\n```\n\n");
9498        assert_eq!(
9499            boundaries(&m),
9500            vec![
9501                (Paragraph, Paragraph),
9502                (Paragraph, Heading),
9503                (Heading, Paragraph),
9504                (Paragraph, Quote),
9505                (Quote, Code),
9506                // The blank line the document trails off with is a boundary too
9507                // — it closes the last block above the empty paragraph the caret
9508                // rests on. See `emit_trailing_blank_lines`.
9509                (Code, Paragraph),
9510            ],
9511            "each gap names the pair it falls between, in document order"
9512        );
9513    }
9514
9515    #[test]
9516    fn a_closing_fence_at_the_end_of_the_document_opens_no_phantom_row() {
9517        // The code block's last row ends at its last line of code; the closing
9518        // fence under it has no row. Counted from the row, the fence's line read
9519        // as a trailing blank line and opened an empty paragraph whose offset
9520        // was inside the fence — typing on it wrote into the backticks.
9521        let m = map("para\n\n```\ncode\n```\n");
9522        let texts: Vec<String> = m
9523            .rows
9524            .iter()
9525            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9526            .collect();
9527        assert_eq!(texts, vec!["para", "", "code"], "a row under the fence");
9528        assert!(
9529            m.rows.last().is_some_and(|r| r.code),
9530            "the last row is the code"
9531        );
9532        // One more newline is the real empty paragraph, past the fence.
9533        let m = map("para\n\n```\ncode\n```\n\n");
9534        let last = m.rows.last().expect("a trailing row");
9535        assert_eq!(last.end_src, 20, "the trailing row stands past the fence");
9536        assert!(!last.decoration, "the trailing row is somewhere to type");
9537        // A setext underline is the same shape: markup under the last row.
9538        let m = map("Head\n====\n");
9539        assert_eq!(
9540            m.rows.len(),
9541            1,
9542            "a row under the underline: {:?}",
9543            m.rows.len()
9544        );
9545    }
9546
9547    /// Each row as whether it is drawn-only and where it ends — the shape of
9548    /// the blank lines around a block, which is what its text can't show.
9549    fn row_shape(m: &VisualMap) -> Vec<(bool, usize)> {
9550        m.rows.iter().map(|r| (r.decoration, r.end_src)).collect()
9551    }
9552
9553    #[test]
9554    fn the_lines_above_the_first_block_draw_as_the_lines_under_the_last_do() {
9555        // No row was drawn above the first block, so an empty paragraph opened
9556        // there drew nothing. As at the document's end, one blank line is only
9557        // the gap, and every line above that gap is somewhere to type.
9558        assert_eq!(row_shape(&map("\nb\n")), [(false, 2)]);
9559        let m = map("\n\nb\n");
9560        assert_eq!(row_shape(&m), [(false, 0), (true, 1), (false, 3)]);
9561        assert_eq!(m.content_start, 0, "the caret can reach the empty line");
9562        assert_eq!(m.pos_of_offset(0), (0, 0));
9563        assert_eq!(map("b\n").content_start, 0);
9564        assert_eq!(
9565            row_shape(&map("\n\n\n# H\n")),
9566            [(false, 0), (false, 1), (true, 2), (false, 6)]
9567        );
9568
9569        // Past frontmatter, the line under it is the frontmatter's.
9570        let fm = "---\nt: x\n---\n";
9571        let m = map(&format!("{fm}\nb\n"));
9572        assert_eq!(row_shape(&m), [(false, 15)]);
9573        assert_eq!(m.content_start, 14);
9574        let m = map(&format!("{fm}\n\nb\n"));
9575        assert_eq!(row_shape(&m), [(false, 13), (true, 14), (false, 16)]);
9576        assert_eq!(m.content_start, 13);
9577
9578        // Preserve flow draws every line, but the frontmatter's.
9579        let preserve = |src: &str| {
9580            let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
9581            build(
9582                &ed.nodes().unwrap(),
9583                src,
9584                Some(80),
9585                true,
9586                &Surface::default(),
9587                None,
9588            )
9589        };
9590        assert_eq!(row_shape(&preserve("\nb\n")), [(false, 0), (false, 2)]);
9591        assert_eq!(row_shape(&preserve(&format!("{fm}\nb\n"))), [(false, 15)]);
9592        assert_eq!(
9593            row_shape(&preserve(&format!("{fm}\n\nb\n"))),
9594            [(false, 14), (false, 16)]
9595        );
9596
9597        // Past a comment, counted from the line after it.
9598        assert_eq!(row_shape(&map("<!-- c -->\n\nb\n")), [(false, 13)]);
9599        assert_eq!(
9600            row_shape(&map("<!-- c -->\n\n\nb\n")),
9601            [(false, 11), (true, 12), (false, 14)]
9602        );
9603    }
9604
9605    #[test]
9606    fn the_lines_under_a_rule_are_counted_from_the_rule() {
9607        // A rule's row ends at the caret's home past the newline under it, and
9608        // the counts of the blank lines below used to start from there too, so
9609        // every gap under a rule came up a line short: the empty paragraph
9610        // Enter opens beneath a rule drew as two gaps and no line, and the
9611        // caret put on it was drawn on the next block. They count from the
9612        // rule itself, as under any other block's last line.
9613        let src = "a\n\n---\n\n\n\nb\n";
9614        let m = map(src);
9615        assert_eq!(
9616            row_shape(&m),
9617            [
9618                (false, 1),
9619                (true, 2),
9620                (false, 7), // the rule, its home past the newline under it
9621                (true, 7),
9622                (false, 8), // the empty paragraph
9623                (true, 9),
9624                (false, 11),
9625            ]
9626        );
9627        assert_eq!(m.pos_of_offset(8), (4, 0), "the caret on the empty line");
9628        // The one blank line under a rule is still the one gap, not two.
9629        assert_eq!(
9630            row_shape(&map("a\n\n---\n\nb\n")),
9631            [(false, 1), (true, 2), (false, 7), (true, 7), (false, 9)]
9632        );
9633
9634        // Closing the document, the line under the gap is somewhere to type.
9635        let m = map("a\n\n---\n\n");
9636        assert_eq!(
9637            row_shape(&m),
9638            [(false, 1), (true, 2), (false, 7), (true, 7), (false, 8)]
9639        );
9640        assert_eq!(m.pos_of_offset(8), (4, 0));
9641        // And a lone newline after the rule is only the rule's own.
9642        assert_eq!(
9643            row_shape(&map("a\n\n---\n")),
9644            [(false, 1), (true, 2), (false, 7)]
9645        );
9646
9647        // A quote's own trailing lines under a rule: each a row, the first too.
9648        let m = map("> ---\n>\n> ");
9649        assert_eq!(row_shape(&m), [(false, 6), (false, 7), (false, 10)]);
9650    }
9651
9652    #[test]
9653    fn the_home_past_a_djot_rule_is_the_line_under_it() {
9654        // djot's span takes in the newline that ends the rule, and the home
9655        // past the rule was measured from that end — one newline further on,
9656        // across the blank line, to the next block's first character. A caret
9657        // left after the rule was drawn on that block.
9658        let m = map_djot("a\n\n* * *\n\nb\n");
9659        assert_eq!(
9660            row_shape(&m),
9661            [(false, 1), (true, 2), (false, 9), (true, 9), (false, 11)]
9662        );
9663        assert_eq!(m.pos_of_offset(9).0, 2, "beside the rule, not on `b`");
9664        let m = map_djot("a\n\n* * *\n\n\n\nb\n");
9665        assert_eq!(m.pos_of_offset(10), (4, 0), "the caret on the empty line");
9666    }
9667
9668    // ── hidden blocks ────────────────────────────────────────────────────────
9669
9670    /// The row texts of `m`, one string per row.
9671    fn row_texts(m: &VisualMap) -> Vec<String> {
9672        m.rows
9673            .iter()
9674            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9675            .collect()
9676    }
9677
9678    #[test]
9679    fn a_div_s_closing_tag_is_not_a_blank_row() {
9680        // The `</div>` sits on a line of its own under the div's last child and
9681        // draws nothing. Counting the separator from the child's end read that
9682        // line as a blank line between the div and the block below — a
9683        // navigable empty row the author never opened — and at the end of the
9684        // file, as an empty trailing paragraph.
9685        let m = map("above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n");
9686        assert_eq!(row_texts(&m), ["above", "", "hello", "", "below"]);
9687        assert!(!m.is_stop(36), "the `</div>` line is not a caret home");
9688        assert_eq!(
9689            m.stop_after(34),
9690            Some(44),
9691            "from `hello` the next stop is `below`"
9692        );
9693
9694        let m = map("above\n\n<div class=\"center\">\n\nhello\n\n</div>\n");
9695        assert_eq!(row_texts(&m), ["above", "", "hello"], "no trailing rows");
9696    }
9697
9698    #[test]
9699    fn a_comment_between_two_blocks_is_stepped_over_not_drawn_as_a_gap() {
9700        // `<!-- exec -->` is a top-level block that draws no rows. The blocks
9701        // either side of it meet across the one boundary a paragraph and a code
9702        // block always meet across — not that boundary *plus* one blank row per
9703        // line of the comment, which is what counting the separator from the
9704        // paragraph's end used to spell.
9705        let m = map("para one\n\n<!-- exec -->\n```\ncode\n```\n\nafter\n");
9706        assert_eq!(row_texts(&m), ["para one", "", "code", "", "after"]);
9707        assert_eq!(
9708            boundaries(&m),
9709            vec![
9710                (BlockClass::Paragraph, BlockClass::Code),
9711                (BlockClass::Code, BlockClass::Paragraph),
9712            ],
9713            "the boundary names the drawn blocks either side, not the comment"
9714        );
9715        // The gap stands past the comment, so the caret's row lookup never
9716        // resolves inside it.
9717        assert_eq!(
9718            m.rows[1].end_src, 23,
9719            "the gap row ends at the comment's end"
9720        );
9721    }
9722
9723    #[test]
9724    fn a_comment_opening_the_document_draws_no_leading_gap() {
9725        let m = map("<!-- lead -->\n\npara\n");
9726        assert_eq!(row_texts(&m), ["para"]);
9727        assert_eq!(m.content_start, 0, "the comment is still the first block");
9728    }
9729
9730    #[test]
9731    fn a_comment_closing_the_document_is_not_trailing_blank_lines() {
9732        // Its lines are not blank lines the author opened with Enter, so no
9733        // gap-plus-empty-paragraph is fabricated under the last drawn block.
9734        let m = map("para\n\n<!-- trail -->\n");
9735        assert_eq!(row_texts(&m), ["para"]);
9736        // Enter at the end of the document still opens the empty paragraph the
9737        // caret rests on: the newlines *after* the comment count as they would
9738        // after any block.
9739        let m = map("para\n\n<!-- trail -->\n\n");
9740        assert_eq!(row_texts(&m), ["para", "", ""]);
9741    }
9742
9743    #[test]
9744    fn a_comment_in_a_list_item_leaves_the_bullet_to_what_follows_it() {
9745        // The first *drawn* child wears the item's marker; a hidden first child
9746        // would otherwise take it and leave the text without one.
9747        let m = map("- <!-- note -->\n\n  text\n- two\n");
9748        let texts = row_texts(&m);
9749        assert!(
9750            texts.iter().any(|t| t == "• text"),
9751            "the text wears the bullet: {texts:?}"
9752        );
9753        assert!(
9754            !texts.iter().any(|t| t == "• "),
9755            "no empty bullet row for the comment: {texts:?}"
9756        );
9757    }
9758
9759    #[test]
9760    fn the_cached_build_does_not_spell_the_document_out_as_blank_rows_after_a_comment() {
9761        // The bug as seen: a 200-line document with one comment in it rendered
9762        // ~200 blank rows after the comment, one per source line, because the
9763        // comment's per-block builder handed back a `last_off` of 0. Parity with
9764        // `build` alone would not catch a *shared* wrong answer, so the count is
9765        // pinned outright.
9766        let body = (0..200)
9767            .map(|i| format!("line {i}"))
9768            .collect::<Vec<_>>()
9769            .join("\n\n");
9770        let src = format!("intro\n\n<!-- exec -->\n{body}\n");
9771        let mut ed = Editor::new_str(&src, Format::Markdown).unwrap();
9772        let mut cache = BlockCache::default();
9773        let (plain, cached) = render_both(&mut ed, &src, Some(80), &mut cache);
9774        assert_maps_eq(&plain, &cached, "comment then 200 paragraphs");
9775        // intro, then 200 × (gap, paragraph): 401 rows and not a row more.
9776        assert_eq!(cached.rows.len(), 401);
9777    }
9778
9779    #[test]
9780    fn a_link_reference_definition_is_stepped_over_like_a_comment() {
9781        // `[a]: /a` is a root beside `doc` with no rows of its own. Merged into
9782        // the walk it is a hidden block: the blocks either side meet across one
9783        // boundary, and its line is not a blank row.
9784        let m = map("see [a]\n\n[a]: /a\n\nafter\n");
9785        assert_eq!(row_texts(&m), ["see a", "", "after"]);
9786        assert_eq!(
9787            boundaries(&m),
9788            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
9789        );
9790    }
9791
9792    #[test]
9793    fn link_reference_definitions_closing_the_document_are_not_trailing_blank_lines() {
9794        // The README shape: prose, then a `[links]` block nobody reads. Its
9795        // lines used to be counted as blank ones, an empty paragraph per
9796        // definition under the last real block.
9797        let m = map("see [a] and [b]\n\n<!-- links -->\n[a]: /a\n[b]: /b \"bee\"\n");
9798        assert_eq!(row_texts(&m), ["see a and b"]);
9799    }
9800
9801    #[test]
9802    fn a_definition_glued_under_a_paragraph_stays_inside_it() {
9803        // `[a]: /a` at the front of a paragraph's lines is stripped from the
9804        // paragraph's text, but the paragraph's span still starts on its line.
9805        // Both blocks start at the same offset; the definition, sorted first,
9806        // is stepped over, and the paragraph draws as it always did — one gap
9807        // above it, none inside.
9808        let m = map("intro\n\n[a]: /a\ntext [a]\n");
9809        assert_eq!(row_texts(&m), ["intro", "", "text a"]);
9810    }
9811
9812    #[test]
9813    fn a_definition_with_no_span_is_left_out_of_the_walk() {
9814        // twig before 3.3.3 reported `0..0` for every link reference
9815        // definition. One of those has nowhere to be merged: sorted first by
9816        // its zero start it would open the document with a phantom block, and
9817        // the walk would step back to offset 0. It is simply not a block. A
9818        // footnote definition is always placed; it has a body to draw.
9819        assert!(!is_placed_definition(&Kind::Reference, &(0..0)));
9820        assert!(is_placed_definition(&Kind::Reference, &(7..14)));
9821        assert!(is_placed_definition(&Kind::Footnote, &(0..0)));
9822        assert!(!is_placed_definition(&Kind::Str, &(7..14)));
9823    }
9824
9825    #[test]
9826    fn the_trailing_gap_closes_the_last_block() {
9827        // Two Enters at the end of a document: a drawn gap, then the navigable
9828        // empty paragraph. Only the gap is labelled, so a frontend that shrinks
9829        // boundaries shrinks the spacer and leaves the row being typed on alone.
9830        let m = map("# Head\n\n\n");
9831        assert_eq!(
9832            boundaries(&m),
9833            vec![(BlockClass::Heading, BlockClass::Paragraph)]
9834        );
9835    }
9836
9837    #[test]
9838    fn only_the_drawn_gap_rows_carry_a_boundary() {
9839        let m = map("one\n\ntwo\n");
9840        for row in &m.rows {
9841            assert_eq!(
9842                row.boundary.is_some(),
9843                row.decoration,
9844                "a boundary is exactly a drawn gap row: {:?}",
9845                row.glyphs.iter().map(|g| g.ch).collect::<String>()
9846            );
9847        }
9848    }
9849
9850    #[test]
9851    fn preserve_flow_labels_no_boundary() {
9852        // Every blank line is a caret home there — somewhere text can go, not a
9853        // gap between blocks — so nothing is drawn-only and nothing is labelled.
9854        // A frontend keying its spacing off `boundary` can't shrink a row the
9855        // author is about to type on.
9856        let m = map_preserve("one\n\ntwo\n\n# Head\n", Some(80));
9857        assert!(boundaries(&m).is_empty());
9858    }
9859
9860    #[test]
9861    fn a_list_draws_no_boundary_between_its_items() {
9862        // Tight or loose, core puts no gap row between two items of one list —
9863        // so an item↔item boundary is a shape no frontend will ever be handed,
9864        // and spacing one is spacing something that isn't there.
9865        for src in ["- one\n- two\n", "- one\n\n- two\n"] {
9866            let m = map(src);
9867            assert!(
9868                boundaries(&m).is_empty(),
9869                "no gap row inside the list of {src:?}"
9870            );
9871        }
9872        // Leaving the list is an ordinary boundary, and the list is named as
9873        // what sits above it.
9874        let m = map("- one\n- two\n\npara\n");
9875        assert_eq!(
9876            boundaries(&m),
9877            vec![(BlockClass::List, BlockClass::Paragraph)]
9878        );
9879    }
9880
9881    #[test]
9882    fn a_nested_boundary_names_the_blocks_inside_the_container() {
9883        // Two paragraphs inside a blockquote are divided by a Paragraph↔Paragraph
9884        // boundary — the quote is the container they're both in, not what the gap
9885        // separates.
9886        let m = map("> one\n>\n> two\n");
9887        assert_eq!(
9888            boundaries(&m),
9889            vec![(BlockClass::Paragraph, BlockClass::Paragraph)]
9890        );
9891    }
9892
9893    #[test]
9894    fn a_directive_container_draws_one_boundary_like_every_other_block() {
9895        // A container's rows stop at its last *child*, so without anchoring
9896        // `last_off` past the closing `:::` the separator logic counted the fence
9897        // line as a blank row of its own and drew the gap twice — one authored
9898        // blank line, two boundaries, and a frontend spacing each of them put
9899        // double margin under every fenced div. The code-block arm anchors past
9900        // its ``` for exactly this reason; compare the two here.
9901        let fenced = map_directives(":::note\nin\n:::\n\ntwo\n");
9902        assert_eq!(
9903            boundaries(&fenced),
9904            vec![(BlockClass::Directive, BlockClass::Paragraph)],
9905            "one authored gap, one boundary row"
9906        );
9907        let code = map("```\nc\n```\n\ntwo\n");
9908        assert_eq!(
9909            boundaries(&code).len(),
9910            boundaries(&fenced).len(),
9911            "a fenced div spaces like a fenced code block"
9912        );
9913        // Nesting closes several fences at once; still one gap.
9914        let nested = map_directives(":::a\n:::b\nin\n:::\n:::\n\ntwo\n");
9915        assert_eq!(
9916            boundaries(&nested),
9917            vec![(BlockClass::Directive, BlockClass::Paragraph)]
9918        );
9919    }
9920
9921    #[test]
9922    fn a_block_media_names_itself_in_the_boundaries_either_side() {
9923        use BlockClass::*;
9924        // A block image is never a node of its own — `media_only` promotes the
9925        // *paragraph* wrapping it — so classifying the node the walk stands on
9926        // called the picture `Paragraph` and left `BlockClass::Media` unreachable:
9927        // a frontend could not give a photo more air than a line of prose.
9928        // `label_media_boundaries` reads it back off the finished rows instead.
9929        let m = map("one\n\n![alt](p.png)\n\ntwo\n");
9930        assert_eq!(boundaries(&m), vec![(Paragraph, Media), (Media, Paragraph)]);
9931        // At the edges of the document too: the leading gap has no boundary of
9932        // its own, and the trailing one is `emit_trailing_blank_lines`'.
9933        let edges = map("![a](p.png)\n\nmid\n\n![b](q.png)\n");
9934        assert_eq!(
9935            boundaries(&edges),
9936            vec![(Media, Paragraph), (Paragraph, Media)]
9937        );
9938        // One gap spelled with several rows — the row closing the block above and
9939        // the row opening the one below, with the author's spare blank line
9940        // navigable between them — carries the same pair on every drawn row.
9941        let roomy = map("one\n\n\n\n![alt](p.png)\n");
9942        assert_eq!(
9943            boundaries(&roomy),
9944            vec![(Paragraph, Media), (Paragraph, Media)]
9945        );
9946    }
9947
9948    #[test]
9949    fn a_block_video_is_media_at_its_boundaries_not_a_directive_panel() {
9950        // Worse than the image case before `label_media_boundaries`: a `<video>`
9951        // arrives as twig's generic `container`, which classifies `Directive` —
9952        // the one class a frontend reads as "draw a tinted panel here". A movie
9953        // got the chrome of a fenced div.
9954        let mut doc = crate::Doc::from_source(
9955            "one\n\n<video src=\"v.mp4\"></video>\n\ntwo\n".to_string(),
9956            Format::Markdown,
9957        )
9958        .unwrap();
9959        doc.build_visual(80);
9960        assert_eq!(
9961            boundaries(&doc.vmap),
9962            vec![
9963                (BlockClass::Paragraph, BlockClass::Media),
9964                (BlockClass::Media, BlockClass::Paragraph),
9965            ]
9966        );
9967    }
9968
9969    #[test]
9970    fn the_incremental_walk_labels_boundaries_like_the_full_one() {
9971        // `assert_maps_eq` compares boundaries too, so this pins the two doors
9972        // into `BlockClass::from_node_kind` — a `FlatNode`'s kind on the full
9973        // build, a query match's on the cached one — against a document with one
9974        // of every boundary in it.
9975        let src = "one\n\n# Head\n\ntwo\n\n- a\n- b\n\n> q\n\n```\nc\n```\n\npara\n";
9976        let mut ed = Editor::new_str(src, Format::Markdown).unwrap();
9977        let mut cache = BlockCache::default();
9978        let (full, cached) = render_both(&mut ed, src, Some(80), &mut cache);
9979        assert_maps_eq(&full, &cached, "boundary labelling");
9980        assert!(
9981            !boundaries(&full).is_empty(),
9982            "the fixture has boundaries to compare"
9983        );
9984    }
9985
9986    #[test]
9987    fn every_caret_stop_opens_a_cluster_of_its_row() {
9988        // The two ways of finding a cluster have to agree. `push_text` marks the
9989        // stops by segmenting one run of text; the column mapping segments the
9990        // whole row, decoration and all. A stop that came out as the *middle* of
9991        // some row-level cluster would be a caret with no column of its own —
9992        // drawn at the column of whatever swallowed it.
9993        let src = "# 標題\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` 你好\n\n\
9994                   - 項目 one\n- e\u{0301}dge\n\n> 引用 text\n\n\
9995                   | A | 值 |\n|---|---|\n| 你好 | 👩‍🚀 |\n";
9996        let m = map(src);
9997        for (r, row) in m.rows.iter().enumerate() {
9998            let openers: Vec<usize> = clusters(&row.glyphs).iter().map(|c| c.glyph).collect();
9999            for (i, g) in row.glyphs.iter().enumerate() {
10000                assert!(
10001                    !g.stop || openers.contains(&i),
10002                    "row {r}: the stop at glyph {i} ({:?}) is inside a cluster, \
10003                     so it is drawn at another glyph's column",
10004                    g.ch
10005                );
10006            }
10007        }
10008    }
10009
10010    // ── the presentation vocabulary ─────────────────────────────────────────
10011
10012    /// A block's own attributes, in the three formats that spell one on the
10013    /// block itself: HTML's tag, djot's `{…}` line, and — the odd one — a
10014    /// Markdown `<div>` around it, which is where twig has to put a Markdown
10015    /// block's attributes because the format has nowhere else.
10016    #[test]
10017    fn a_block_carries_its_alignment_on_every_row_it_draws() {
10018        // HTML, on the paragraph. `lead` is somebody else's class and is
10019        // neither read nor in the way.
10020        let html = map_leaf("<p class=\"lead center\">hi</p>\n", Format::Html);
10021        assert_eq!(line_facts(&html), vec![(Some(Align::Center), None)]);
10022
10023        // djot's attribute line, on the block.
10024        let dj = map_leaf("{.right}\nhi\n", Format::Djot);
10025        assert_eq!(line_facts(&dj), vec![(Some(Align::Right), None)]);
10026
10027        // A heading carries it too, and on every row a wrapped one draws.
10028        let h = map_leaf("{.center}\n# a heading\n", Format::Djot);
10029        assert_eq!(line_facts(&h), vec![(Some(Align::Center), None)]);
10030        assert_eq!(h.rows[0].heading, Some(1));
10031
10032        // Both keys at once, and the line spacing is read the same way.
10033        let both = map_leaf("{.justify data-line-height=\"1.5\"}\nhi\n", Format::Djot);
10034        assert_eq!(
10035            line_facts(&both),
10036            vec![(
10037                Some(Align::Justify),
10038                Some(LineHeight::Step(LineSpacing::OneHalf))
10039            )]
10040        );
10041
10042        // An unknown token is somebody else's and the block draws at the
10043        // theme's alignment; a ratio outside the menu's three is the author's
10044        // own and draws at exactly what they wrote.
10045        let other = map_leaf("{.lead data-line-height=\"1.3\"}\nhi\n", Format::Djot);
10046        assert_eq!(line_facts(&other), vec![(None, LineHeight::ratio(1.3))]);
10047
10048        // A value the grammar does not cover is neither: carried by the
10049        // document, drawn at the theme's spacing, and read as nothing at all.
10050        let em = map_leaf("{data-line-height=\"1.3em\"}\nhi\n", Format::Djot);
10051        assert_eq!(line_facts(&em), vec![(None, None)]);
10052    }
10053
10054    /// `<div class="center">` around three paragraphs centres all three, which
10055    /// is what the author of that HTML meant — and around one is the sole-child
10056    /// shape twig's `set_block_attrs` writes in Markdown.
10057    #[test]
10058    fn a_div_lends_its_alignment_to_every_block_inside_it() {
10059        let m = map_leaf(
10060            "<div class=\"center\" data-line-height=\"2\">\n\none\n\ntwo\n\n</div>\n",
10061            Format::Markdown,
10062        );
10063        assert_eq!(
10064            line_facts(&m),
10065            vec![
10066                (
10067                    Some(Align::Center),
10068                    Some(LineHeight::Step(LineSpacing::Double))
10069                ),
10070                (
10071                    Some(Align::Center),
10072                    Some(LineHeight::Step(LineSpacing::Double))
10073                ),
10074            ]
10075        );
10076
10077        // The nearer node wins, and the block after the div is untouched — the
10078        // context is restored, not left running.
10079        let nested = map_leaf(
10080            "<div class=\"center\">\n\n<div class=\"right\">\n\ninner\n\n</div>\n\nouter\n\n</div>\n\nafter\n",
10081            Format::Markdown,
10082        );
10083        assert_eq!(
10084            line_facts(&nested),
10085            vec![
10086                (Some(Align::Right), None),
10087                (Some(Align::Center), None),
10088                (None, None),
10089            ]
10090        );
10091    }
10092
10093    /// Size, face and colour are the run's, and the block's when the whole
10094    /// block is meant — read at both levels with the nearer winning.
10095    #[test]
10096    fn a_span_s_size_beats_its_block_s_and_its_face_falls_through() {
10097        // `<div data-font>` over `<p data-size>` over `<span data-size>`: the
10098        // span wins on size, the block is still what says the face.
10099        // The span is not first on its line: a `<span …>` opening one is an
10100        // HTML *block* to CommonMark, which is a fact about Markdown and not
10101        // about this.
10102        let m = map_leaf(
10103            "<div data-font=\"serif\">\n\nc <span data-size=\"small\">a</span> b\n\n</div>\n",
10104            Format::Markdown,
10105        );
10106        let a = style_of(&m, 'a');
10107        assert_eq!(a.size, Some(FontSize::Step(SizeStep::Small)));
10108        assert_eq!(a.font, Some(FaceRef::Generic(FontFamily::Serif)));
10109        // The text outside the span keeps the div's face and no size at all.
10110        let b = style_of(&m, 'b');
10111        assert_eq!(b.size, None);
10112        assert_eq!(b.font, Some(FaceRef::Generic(FontFamily::Serif)));
10113
10114        // djot spells the same span anonymously and it reads identically.
10115        let dj = map_leaf(
10116            "{data-size=\"large\"}\nx [y]{data-size=\"xx-large\" data-color=\"blue\"} z\n",
10117            Format::Djot,
10118        );
10119        assert_eq!(
10120            style_of(&dj, 'x').size,
10121            Some(FontSize::Step(SizeStep::Large))
10122        );
10123        assert_eq!(
10124            style_of(&dj, 'y').size,
10125            Some(FontSize::Step(SizeStep::XxLarge))
10126        );
10127        assert_eq!(
10128            style_of(&dj, 'y').color,
10129            Some(TextColor::Named(MarkColor::Blue))
10130        );
10131        // The block's size is still the block's outside the span.
10132        assert_eq!(
10133            style_of(&dj, 'z').size,
10134            Some(FontSize::Step(SizeStep::Large))
10135        );
10136        assert_eq!(style_of(&dj, 'z').color, None);
10137    }
10138
10139    /// The exact half of the vocabulary reaches a glyph and a row by the same
10140    /// doors the names do — the fold has one rule, not one per form. A named
10141    /// family is the one that cannot ride the glyph as itself: the walker
10142    /// interns it and the glyph carries the id.
10143    #[test]
10144    fn an_exact_size_face_and_colour_reach_the_glyph_and_the_row() {
10145        let m = map_leaf(
10146            "<div data-line-height=\"1.3\">\n\nc <span data-size=\"14pt\" \
10147             data-color=\"#c03030\" data-font=\"Garamond\">a</span> b\n\n</div>\n",
10148            Format::Markdown,
10149        );
10150        let a = style_of(&m, 'a');
10151        assert_eq!(a.size, FontSize::points(14.0));
10152        assert_eq!(
10153            a.color,
10154            Some(TextColor::Rgb {
10155                r: 0xc0,
10156                g: 0x30,
10157                b: 0x30
10158            })
10159        );
10160        assert_eq!(a.font, Some(FaceRef::Named(FaceId::of("Garamond"))));
10161        assert_eq!(m.face_name(FaceId::of("Garamond")), Some("Garamond"));
10162        // The div's ratio is the row's, on every row the block draws.
10163        assert_eq!(line_facts(&m), vec![(None, LineHeight::ratio(1.3))]);
10164        // And the text outside the span has none of the span's three.
10165        let b = style_of(&m, 'b');
10166        assert_eq!((b.size, b.font, b.color), (None, None, None));
10167
10168        // One name, one entry, however many spans wear it — the table is what
10169        // keeps a `Style` `Copy` and it should not grow per run.
10170        let twice = map_leaf(
10171            "x <span data-font=\"Garamond\">a</span> y <span data-font=\"Garamond\">b</span>\n",
10172            Format::Markdown,
10173        );
10174        assert_eq!(twice.faces().len(), 1);
10175        assert_eq!(
10176            style_of(&twice, 'a').font,
10177            style_of(&twice, 'b').font,
10178            "one family, one id"
10179        );
10180
10181        // A generic needs no entry at all: it names itself.
10182        let generic = map_leaf(
10183            "<div data-font=\"serif\">\n\nhi\n\n</div>\n",
10184            Format::Markdown,
10185        );
10186        assert_eq!(
10187            style_of(&generic, 'h').font,
10188            Some(FaceRef::Generic(FontFamily::Serif))
10189        );
10190        assert!(generic.faces().is_empty());
10191    }
10192
10193    /// The one key two nodes share. `data-color` on a `mark` is the highlight's
10194    /// *background* and reaches a glyph through [`Role::Mark`]; the same key on
10195    /// an attributed span is the text's foreground. Same vocabulary, same enum,
10196    /// no collision — and a mark inside a coloured span wears both.
10197    #[test]
10198    fn a_mark_keeps_its_highlight_colour_and_a_span_colours_the_text() {
10199        let m = map_leaf("a ==\u{1f534} red== b\n", Format::Markdown);
10200        let r = style_of(&m, 'r');
10201        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)));
10202        assert_eq!(r.color, None, "a highlight is not a text colour");
10203
10204        let both = map_leaf(
10205            "<span data-color=\"blue\">a ==\u{1f534} red== b</span>\n",
10206            Format::Markdown,
10207        );
10208        let r = style_of(&both, 'r');
10209        assert_eq!(r.role, Role::Mark(Some(MarkColor::Red)), "the highlight");
10210        assert_eq!(
10211            r.color,
10212            Some(TextColor::Named(MarkColor::Blue)),
10213            "the letters"
10214        );
10215    }
10216
10217    /// A page break is the `::page-break` leaf directive, and djot spells the
10218    /// same document as an empty `::: page-break` fence whose name comes back
10219    /// as a class, HTML as a `<page-break>` element and AsciiDoc as `<<<`. All
10220    /// four draw the placeholder row every leaf directive gets and carry the
10221    /// same [`DirectiveMark`], because a frontend that opens a page at one
10222    /// must not be able to tell which format the file is in.
10223    #[test]
10224    fn a_page_break_reads_the_same_in_every_format() {
10225        for (fmt, src) in [
10226            (Format::Markdown, "a\n\n::page-break\n\nb\n"),
10227            (Format::Djot, "a\n\n::: page-break\n:::\n\nb\n"),
10228            (
10229                Format::Html,
10230                "<p>a</p>\n\n<page-break></page-break>\n\n<p>b</p>\n",
10231            ),
10232            (Format::Asciidoc, "a\n\n<<<\n\nb\n"),
10233        ] {
10234            let m = map_leaf(src, fmt);
10235            let marks: Vec<&DirectiveMark> = m
10236                .rows
10237                .iter()
10238                .filter_map(|r| r.leaf_directive.as_ref())
10239                .collect();
10240            assert_eq!(marks.len(), 1, "{fmt:?} draws one placeholder");
10241            assert_eq!(marks[0].name, "page-break", "{fmt:?}");
10242            assert!(marks[0].attrs.is_empty(), "{fmt:?}: {:?}", marks[0].attrs);
10243            assert!(
10244                m.rows
10245                    .iter()
10246                    .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>()
10247                        == "\u{29c9} page-break"),
10248                "{fmt:?} draws the label, got {:?}",
10249                m.rows
10250                    .iter()
10251                    .map(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>())
10252                    .collect::<Vec<_>>()
10253            );
10254        }
10255
10256        // A Markdown `:::note` with nothing in it is *not* this: its name is
10257        // its own, and nothing about it says "a block with no body" the way
10258        // djot's spelling of a leaf directive does.
10259        let empty_fence = map_leaf("::: note\n:::\n", Format::Markdown);
10260        assert!(
10261            empty_fence.rows.iter().all(|r| r.leaf_directive.is_none()),
10262            "a named empty fence keeps the reading it has"
10263        );
10264    }
10265
10266    /// A djot fence carrying more than its name keeps the rest as an attribute
10267    /// rather than folding it into the name: the *first* class token is the
10268    /// name, because that is where `insert_directive` puts it.
10269    #[test]
10270    fn a_djot_fence_s_first_class_is_the_directive_s_name_and_the_rest_is_attributes() {
10271        let m = map_leaf("{.page-break .wide}\n:::\n:::\n", Format::Djot);
10272        let mark = m
10273            .rows
10274            .iter()
10275            .find_map(|r| r.leaf_directive.as_ref())
10276            .expect("a placeholder");
10277        assert_eq!(mark.name, "page-break");
10278        assert_eq!(
10279            mark.attrs,
10280            vec![("class".to_string(), Some("wide".to_string()))]
10281        );
10282    }
10283
10284    // ── math ─────────────────────────────────────────────────────────────────
10285
10286    /// [`map_leaf`] on a chosen surface and reveal — the whole of what a math
10287    /// rendering turns on.
10288    fn map_math(src: &str, format: Format, surface: &Surface, reveal: Option<Reveal>) -> VisualMap {
10289        let mut ed =
10290            Editor::new_ext(src.as_bytes(), format, crate::doc::parse_extensions()).unwrap();
10291        build(&ed.nodes().unwrap(), src, Some(80), false, surface, reveal)
10292    }
10293
10294    fn pictures() -> Surface {
10295        Surface {
10296            inline_pictures: true,
10297            ..Default::default()
10298        }
10299    }
10300
10301    #[test]
10302    fn markdown_reads_math_and_a_dollar_before_whitespace_stays_prose() {
10303        // The `math` extension is on for every leaf document; twig's own rule
10304        // keeps a price out of it.
10305        let m = map_leaf("Say $E = mc^2$ for $5 and $6.\n", Format::Markdown);
10306        assert_eq!(row_texts(&m), vec!["Say E = mc^2 for $5 and $6."]);
10307        let e = m.rows[0].glyphs.iter().find(|g| g.ch == 'E').unwrap();
10308        assert_eq!(
10309            e.style.role,
10310            Role::Code,
10311            "the formula's TeX, in the code style"
10312        );
10313        assert_eq!(e.src, 5, "at its own byte, past the `$`");
10314        let five = m.rows[0].glyphs.iter().find(|g| g.ch == '5').unwrap();
10315        assert_eq!(five.style.role, Role::Body);
10316        assert!(m.math.is_empty(), "no picture stands in on a plain surface");
10317    }
10318
10319    #[test]
10320    fn a_plain_surface_draws_inline_math_as_code_with_the_delimiters_hidden() {
10321        // The verbatim treatment, in both languages — what `inline_math` always
10322        // rendered as — with the caret's home at the content's end.
10323        for (src, fmt) in [
10324            ("a $x+y$ b\n", Format::Markdown),
10325            ("a $`x+y` b\n", Format::Djot),
10326        ] {
10327            let m = map_leaf(src, fmt);
10328            assert_eq!(row_texts(&m), vec!["a x+y b"], "{src:?}");
10329            let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
10330            assert_eq!(x.style.role, Role::Code);
10331            assert!(!m.mark_ends.is_empty(), "the content end is a caret home");
10332        }
10333    }
10334
10335    #[test]
10336    fn display_math_in_a_line_of_prose_puts_its_text_at_the_text_s_own_offset() {
10337        // `display_math` had no arm and fell to the default one, which pushed
10338        // the text at the *node's* start: three bytes short in djot, past `$$`
10339        // and the backtick.
10340        let m = map_leaf("Before $$`x`$$ after\n", Format::Djot);
10341        let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
10342        assert_eq!(x.src, "Before $$`".len());
10343        assert_eq!(x.style.role, Role::Code);
10344        let m = map_leaf("Before $$x$$ after\n", Format::Markdown);
10345        let x = m.rows[0].glyphs.iter().find(|g| g.ch == 'x').unwrap();
10346        assert_eq!(x.src, "Before $$".len());
10347    }
10348
10349    #[test]
10350    fn a_surface_that_paints_in_a_line_gets_one_atom_per_inline_formula() {
10351        let src = "Say $E = mc^2$ and $a$.\n";
10352        let m = map_math(src, Format::Markdown, &pictures(), None);
10353        assert_eq!(row_texts(&m), vec!["Say ∑ and ∑."]);
10354        assert_eq!(m.math.len(), 2);
10355        let first = &m.math[0];
10356        assert_eq!(first.tex, "E = mc^2");
10357        assert!(!first.display);
10358        assert_eq!(first.row, 0);
10359        assert_eq!(first.rows_span, 0..1);
10360        assert_eq!(first.glyph, Some(4));
10361        assert_eq!(first.src, 4, "the formula's start, where a click lands");
10362        let atom = &m.rows[0].glyphs[4];
10363        assert_eq!(atom.ch, MATH_ATOM);
10364        assert_eq!(atom.style.role, Role::Math);
10365        assert!(atom.stop);
10366        assert_eq!(atom.src, 4);
10367        // The caret has a stop on the atom and the next glyph's past it, and
10368        // nothing inside the markup.
10369        assert_eq!(m.stop_after(4), Some("Say $E = mc^2$".len()));
10370        assert!(m.mark_ends.is_empty(), "no home inside the hidden markup");
10371        // The row carries the marks the side-table is derived from.
10372        assert_eq!(m.rows[0].math.len(), 2);
10373        assert_eq!(m.rows[0].math[1].glyph, Some(m.math[1].glyph.unwrap()));
10374        assert_eq!(m.math[1].tex, "a");
10375    }
10376
10377    #[test]
10378    fn a_display_formula_written_inline_is_an_atom_in_display_style() {
10379        let m = map_math("Before $$x$$ after\n", Format::Markdown, &pictures(), None);
10380        assert_eq!(row_texts(&m), vec!["Before ∑ after"]);
10381        assert_eq!(m.math.len(), 1);
10382        assert!(m.math[0].display);
10383        assert_eq!(m.math[0].tex, "x");
10384    }
10385
10386    #[test]
10387    fn an_atom_follows_its_glyph_across_a_wrap() {
10388        // Fifteen words, then a formula that wraps onto the second row: the
10389        // mark is drained onto the row the glyph landed on, at its index there.
10390        let src = format!("{}$x$ end\n", "word ".repeat(15));
10391        let mut ed = Editor::new_ext(
10392            src.as_bytes(),
10393            Format::Markdown,
10394            crate::doc::parse_extensions(),
10395        )
10396        .unwrap();
10397        let m = build(
10398            &ed.nodes().unwrap(),
10399            &src,
10400            Some(40),
10401            false,
10402            &pictures(),
10403            None,
10404        );
10405        assert!(m.rows.len() >= 2);
10406        assert_eq!(m.math.len(), 1);
10407        let info = &m.math[0];
10408        let g = &m.rows[info.row].glyphs[info.glyph.unwrap()];
10409        assert_eq!(g.ch, MATH_ATOM);
10410        assert_eq!(g.src, src.find("$x$").unwrap());
10411        assert!(m.rows[..info.row].iter().all(|r| r.math.is_empty()));
10412    }
10413
10414    #[test]
10415    fn an_atom_in_a_table_cell_rides_the_cell_s_row() {
10416        let m = map_math(
10417            "| a | b |\n|---|---|\n| $x$ | c |\n",
10418            Format::Markdown,
10419            &pictures(),
10420            None,
10421        );
10422        assert_eq!(m.math.len(), 1);
10423        let info = &m.math[0];
10424        assert_eq!(m.rows[info.row].glyphs[info.glyph.unwrap()].ch, MATH_ATOM);
10425    }
10426
10427    #[test]
10428    fn a_display_formula_on_its_own_lines_is_a_block_placeholder_on_every_surface() {
10429        for (src, fmt) in [
10430            (
10431                "intro\n\n$$\n\\int_0^1 x\\,dx\n$$\n\nend\n",
10432                Format::Markdown,
10433            ),
10434            ("intro\n\n$$`\\int_0^1 x\\,dx`\n\nend\n", Format::Djot),
10435        ] {
10436            for surface in [Surface::default(), pictures()] {
10437                let m = map_math(src, fmt, &surface, None);
10438                assert_eq!(
10439                    row_texts(&m),
10440                    vec!["intro", "", "∑ \\int_0^1 x\\,dx", "", "end"],
10441                    "{src:?}"
10442                );
10443                assert_eq!(m.math.len(), 1);
10444                let info = &m.math[0];
10445                assert!(info.display);
10446                assert_eq!(info.glyph, None, "a block, not an atom");
10447                assert_eq!(info.rows_span, 2..3);
10448                assert_eq!(info.tex.trim(), "\\int_0^1 x\\,dx");
10449                let start = src.find("$$").unwrap();
10450                let end = start + src[start..].find("\n\nend").unwrap();
10451                assert_eq!(info.src, start);
10452                // Every label glyph at the formula's start, a stop there and
10453                // one past the block, nothing inside — a picture's two homes.
10454                let row = &m.rows[2];
10455                assert!(
10456                    row.glyphs
10457                        .iter()
10458                        .all(|g| g.src == start && g.style.role == Role::Math)
10459                );
10460                assert_eq!(row.end_src, end);
10461                assert_eq!(m.stop_after(start), Some(end));
10462                assert_eq!(m.stop_before(end), Some(start));
10463                // The gaps either side are labelled as a formula's.
10464                assert_eq!(m.rows[1].boundary.map(|b| b.below), Some(BlockClass::Math));
10465                assert_eq!(m.rows[3].boundary.map(|b| b.above), Some(BlockClass::Math));
10466            }
10467        }
10468    }
10469
10470    #[test]
10471    fn a_display_block_reserves_the_rows_the_frontend_measured() {
10472        let src = "$$\nx\n$$\n\nend\n";
10473        let surface = Surface {
10474            math_rows: HashMap::from([("\nx\n".to_string(), 4)]),
10475            ..Default::default()
10476        };
10477        let m = map_math(src, Format::Markdown, &surface, None);
10478        assert_eq!(m.math[0].rows_span, 0..4);
10479        assert_eq!(row_texts(&m)[..5], ["∑ x", "", "", "", ""]);
10480        // The fillers are decoration: drawn, no caret, anchored past the block.
10481        for r in &m.rows[1..4] {
10482            assert!(r.decoration);
10483            assert_eq!(r.end_src, 7);
10484        }
10485        assert_eq!(m.stop_after(0), Some(7));
10486        // A height keyed by TeX that does not match reserves nothing.
10487        let surface = Surface {
10488            math_rows: HashMap::from([("x".to_string(), 4)]),
10489            ..Default::default()
10490        };
10491        let m = map_math(src, Format::Markdown, &surface, None);
10492        assert_eq!(m.math[0].rows_span, 0..1);
10493    }
10494
10495    #[test]
10496    fn a_paragraph_with_prose_beside_a_display_formula_is_not_a_block() {
10497        let m = map_math("see\n$$\nx\n$$\n", Format::Markdown, &pictures(), None);
10498        assert!(
10499            m.math.iter().all(|i| i.glyph.is_some()),
10500            "an atom, not a placeholder"
10501        );
10502        let m = map_math(
10503            "$$\nx\n$$\n$$\ny\n$$\n",
10504            Format::Markdown,
10505            &pictures(),
10506            None,
10507        );
10508        assert_eq!(m.math.len(), 2);
10509        assert!(
10510            m.math.iter().all(|i| i.glyph.is_some()),
10511            "two formulas is prose with math in it"
10512        );
10513    }
10514
10515    #[test]
10516    fn a_formula_on_the_reveal_line_is_its_tex_in_every_mode() {
10517        let src = "Say $E = mc^2$ here.\n";
10518        // The hidden modes' reveal: only the formula shows its markup.
10519        let m = map_math(
10520            src,
10521            Format::Markdown,
10522            &pictures(),
10523            Some(Reveal::math(0..src.len() - 1)),
10524        );
10525        assert_eq!(row_texts(&m), vec!["Say $E = mc^2$ here."]);
10526        assert!(
10527            m.math.is_empty(),
10528            "nothing stands in for a revealed formula"
10529        );
10530        let dollar = m.rows[0].glyphs.iter().find(|g| g.ch == '$').unwrap();
10531        assert_eq!(dollar.style.role, Role::Delimiter);
10532        let e = m.rows[0].glyphs.iter().find(|g| g.ch == 'E').unwrap();
10533        assert_eq!(e.style.role, Role::Code);
10534        // Full's reveal draws the same, and an emphasis beside it reveals too
10535        // where the hidden modes' does not.
10536        let src = "*a* $x$\n";
10537        let hidden = map_math(
10538            src,
10539            Format::Markdown,
10540            &pictures(),
10541            Some(Reveal::math(0..src.len() - 1)),
10542        );
10543        assert_eq!(row_texts(&hidden), vec!["a $x$"]);
10544        let full = map_math(
10545            src,
10546            Format::Markdown,
10547            &pictures(),
10548            Some(Reveal::full(0..src.len() - 1)),
10549        );
10550        assert_eq!(row_texts(&full), vec!["*a* $x$"]);
10551        // A reveal line that does not meet the formula leaves the atom.
10552        let other = map_math(
10553            "$x$\n\ntext\n",
10554            Format::Markdown,
10555            &pictures(),
10556            Some(Reveal::math(5..9)),
10557        );
10558        assert_eq!(row_texts(&other)[0], "∑");
10559    }
10560
10561    #[test]
10562    fn a_display_block_on_the_reveal_line_is_its_source_lines_in_the_code_style() {
10563        let src = "intro\n\n$$\n\\int_0^1 x\n$$\n\nend\n";
10564        // Any line of the block reveals the whole of it: here the middle one.
10565        let mid = src.find("\\int").unwrap();
10566        let line = mid..mid + "\\int_0^1 x".len();
10567        let m = map_math(src, Format::Markdown, &pictures(), Some(Reveal::math(line)));
10568        assert_eq!(
10569            row_texts(&m),
10570            vec!["intro", "", "$$", "\\int_0^1 x", "$$", "", "end"]
10571        );
10572        assert!(m.math.is_empty());
10573        let fence = m.rows[2].glyphs.iter().find(|g| g.ch == '$').unwrap();
10574        assert_eq!(fence.style.role, Role::Delimiter);
10575        assert_eq!(fence.src, 7);
10576        let x = m.rows[3].glyphs.iter().find(|g| g.ch == 'x').unwrap();
10577        assert_eq!(x.style.role, Role::Code);
10578        assert_eq!(x.src, src.find("x\n$$").unwrap());
10579        // Every byte of the source is reachable: a stop on each fence and each
10580        // character between.
10581        assert!(m.is_stop(7));
10582        assert!(m.is_stop(mid));
10583        // The closing fence's line too, and the same for djot.
10584        let close = src.rfind("$$").unwrap();
10585        let m = map_math(
10586            src,
10587            Format::Markdown,
10588            &pictures(),
10589            Some(Reveal::math(close..close + 2)),
10590        );
10591        assert_eq!(row_texts(&m)[2], "$$");
10592        let src = "$$`\n\\int\n`\n";
10593        let m = map_math(src, Format::Djot, &pictures(), Some(Reveal::math(4..8)));
10594        assert_eq!(row_texts(&m), vec!["$$`", "\\int", "`"]);
10595    }
10596
10597    #[test]
10598    fn a_block_that_holds_a_formula_says_so_to_the_cache() {
10599        let src = "plain\n\nwith $x$ in it\n\n$$\ny\n$$\n";
10600        let mut ed = Editor::new_ext(
10601            src.as_bytes(),
10602            Format::Markdown,
10603            crate::doc::parse_extensions(),
10604        )
10605        .unwrap();
10606        let mut cache = BlockCache::default();
10607        let top = top_blocks(&mut ed);
10608        let _ = build_cached(
10609            &top,
10610            src,
10611            None,
10612            false,
10613            &pictures(),
10614            None,
10615            &mut cache,
10616            |id| ed.subtree(NodeId(id)).unwrap_or_default(),
10617        );
10618        assert!(!cache.math_meets(&(0..5)), "the plain paragraph");
10619        assert!(cache.math_meets(&(7..21)), "the one with an atom");
10620        assert!(
10621            cache.math_meets(&(26..27)),
10622            "the middle line of the display block"
10623        );
10624        // A hit carries the answer without a walk: build again from the cache.
10625        let _ = build_cached(
10626            &top,
10627            src,
10628            None,
10629            false,
10630            &pictures(),
10631            None,
10632            &mut cache,
10633            |_| Vec::new(),
10634        );
10635        assert!(cache.math_meets(&(7..21)));
10636        assert!(!cache.math_meets(&(0..5)));
10637    }
10638
10639    #[test]
10640    fn incremental_builds_agree_with_the_reference_on_math() {
10641        for src in [
10642            "a $x$ b\n\n$$\ny\n$$\n\nc\n",
10643            "one\n\ntwo $\\frac{a}{b}$ three\n",
10644            "$$\n\\int\n$$\n",
10645        ] {
10646            for surface in [Surface::default(), pictures()] {
10647                let mut ed = Editor::new_ext(
10648                    src.as_bytes(),
10649                    Format::Markdown,
10650                    crate::doc::parse_extensions(),
10651                )
10652                .unwrap();
10653                let all = ed.nodes().unwrap();
10654                let plain = build(&all, src, Some(80), false, &surface, None);
10655                let mut cache = BlockCache::default();
10656                let top = top_blocks(&mut ed);
10657                let cached = build_cached(
10658                    &top,
10659                    src,
10660                    Some(80),
10661                    false,
10662                    &surface,
10663                    None,
10664                    &mut cache,
10665                    |id| ed.subtree(NodeId(id)).unwrap_or_default(),
10666                );
10667                assert_eq!(row_texts(&plain), row_texts(&cached), "{src:?}");
10668                assert_eq!(plain.math, cached.math, "{src:?}");
10669                assert_eq!(plain.stops, cached.stops, "{src:?}");
10670            }
10671        }
10672    }
10673}