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