edamame 0.1.6

A Terminal Markdown editor that stays rendered while you edit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use std::ops::Range;

use pulldown_cmark::HeadingLevel;

use super::segment_break;

// ─── Source positions ─────────────────────────────────────────────────────────

/// Where a leaf block's content sits in the source, relative to its top-level block's first line.
///
/// Block-relative rather than absolute so `RenderCache`, which keys on `Block` by value, still
/// hits for a block that moved: two identical blocks hash identically wherever they sit.
/// Recorded by the parser from pulldown-cmark's own offsets, in the one block parse; see
/// `docs/dev/plans/row-provenance.md` §1.
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct SrcLines {
    /// Block-relative index of the leaf's first source line.
    pub first: u32,
    /// Per source line of the leaf, the char column where its content starts: past container
    /// prefixes (`> `, list indent), its own marker, and any stripped code indent.
    ///
    /// `None` for a line that is all chrome (a fence, a setext underline, a table's delimiter
    /// row, a metadata delimiter), and for a line that only continues an atomic inline begun on
    /// an earlier line (the tail of a multi-line code span, math span, or inline HTML), which
    /// renders on the row of the line it began on and has no content start of its own.  The
    /// exception is a `$$` formula that renders as a ` math ` block: each of its body lines is a
    /// row, and has the column its formula line starts at
    /// (`parser::post_pass::with_formula_cols`); an `ImageBlock` promoted from one keeps them.
    ///
    /// Columns are `u32`, not `u16`: a column is bounded by line length, not by terminal
    /// width, and the document is untrusted.  A wider one saturates at `u32::MAX`.
    cols: Cols,
}

/// [`SrcLines`]' columns, stored compactly.  Nearly every leaf starts its content at one column
/// on every line but at most two chrome lines (a fence pair, a setext underline, a table's
/// delimiter row), which [`Cols::Uniform`] holds without a heap allocation, and which hashes in
/// a few words on every render-cache lookup.  Only [`SrcLines::new`] builds one, always in the
/// canonical form, so the derived `Eq` and `Hash` compare content.
#[derive(Clone, PartialEq, Eq, Hash)]
enum Cols {
    /// `len` lines, all at `col` but the (at most two, ascending) `chrome` lines, which are
    /// `None`; an unused `chrome` slot is [`Cols::NO_LINE`].  `col` is 0 when no line has one.
    Uniform {
        col: u32,
        len: u32,
        chrome: [u32; 2],
    },
    /// Any other shape, one entry per line.
    Varied(Box<[Option<u32>]>),
}

impl Cols {
    const NO_LINE: u32 = u32::MAX;
}

impl Default for Cols {
    fn default() -> Self {
        Cols::Uniform {
            col: 0,
            len: 0,
            chrome: [Cols::NO_LINE; 2],
        }
    }
}

impl SrcLines {
    /// A leaf starting on block-relative line `first`, with `cols[k]` the content column of its
    /// `k`th line (see the field docs).
    pub fn new(first: u32, cols: &[Option<u32>]) -> Self {
        let mut col = None;
        let mut chrome = [Cols::NO_LINE; 2];
        let mut n_chrome = 0;
        let mut uniform = true;
        for (k, c) in cols.iter().enumerate() {
            match *c {
                None if n_chrome < 2 => {
                    chrome[n_chrome] = to_u32(k);
                    n_chrome += 1;
                }
                Some(c) if col.is_none_or(|col| col == c) => col = Some(c),
                _ => {
                    uniform = false;
                    break;
                }
            }
        }
        let cols = if uniform {
            Cols::Uniform {
                col: col.unwrap_or(0),
                len: to_u32(cols.len()),
                chrome,
            }
        } else {
            Cols::Varied(cols.into())
        };
        Self { first, cols }
    }

    /// How many source lines the leaf covers.
    pub fn len(&self) -> usize {
        match &self.cols {
            Cols::Uniform { len, .. } => *len as usize,
            Cols::Varied(cols) => cols.len(),
        }
    }

    /// Whether the leaf covers no line at all (a promotion's placeholder).
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The content column of the leaf's `k`th line; `None` for a chrome line or past the end.
    pub fn col(&self, k: usize) -> Option<u32> {
        match &self.cols {
            Cols::Uniform { col, len, chrome } => {
                let k = u32::try_from(k).ok().filter(|&k| k < *len)?;
                (!chrome.contains(&k)).then_some(*col)
            }
            Cols::Varied(cols) => cols.get(k).copied().flatten(),
        }
    }

    /// Every line's content column, in order.
    pub fn cols(&self) -> impl ExactSizeIterator<Item = Option<u32>> + '_ {
        (0..self.len()).map(|k| self.col(k))
    }

    /// The block-relative source lines this leaf covers.
    pub fn span(&self) -> Range<u32> {
        self.first..self.first.saturating_add(to_u32(self.len()))
    }
}

/// Reads as the per-line list it stands for, whichever form stores it.
impl std::fmt::Debug for SrcLines {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SrcLines")
            .field("first", &self.first)
            .field("content_col", &self.cols().collect::<Vec<_>>())
            .finish()
    }
}

/// Narrow a line, column or cell count to the `u32` positions use, saturating at `u32::MAX`
/// (see [`SrcLines`]).
pub(crate) fn to_u32(n: usize) -> u32 {
    u32::try_from(n).unwrap_or(u32::MAX)
}

/// Block-relative source lines a container (`BlockQuote`, `List`, `FootnoteDefinition`) or a
/// [`ListItem`] covers, end exclusive.  The renderer reads the gaps between its children's spans
/// as the source's blank lines.
pub type LineSpan = Range<u32>;

// ─── Block-level nodes ────────────────────────────────────────────────────────

// `CodeBlock` / `BlockQuote` are Markdown terminology, not stuttering.
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Block {
    Heading {
        level: HeadingLevel,
        inlines: Vec<Inline>,
        src: SrcLines,
    },
    Paragraph {
        inlines: Vec<Inline>,
        src: SrcLines,
    },
    CodeBlock {
        language: Option<String>,
        content: String,
        fenced: bool,
        src: SrcLines,
    },
    BlockQuote {
        blocks: Vec<Block>,
        span: LineSpan,
        /// Lines of `span` no child covers that aren't bare `>` lines: link reference
        /// definitions, which render nothing.  Usually empty.
        hidden: Vec<u32>,
    },
    List {
        ordered: bool,
        start: Option<u64>,
        items: Vec<ListItem>,
        span: LineSpan,
    },
    /// `src.col(0)` is the column of the rule's first `-`/`*`/`_`.
    HorizontalRule {
        src: SrcLines,
    },
    Table {
        /// Column count (from the GFM table alignment row).
        col_count: usize,
        headers: Vec<Vec<Inline>>,
        rows: Vec<Vec<Vec<Inline>>>,
        /// Column widths from a trailing `<!-- tui-columns: [..] -->` comment (stripped from the
        /// AST by the parser). Outer `None` = no comment; inner `None` (`_` in the comment) =
        /// auto-size that column.
        user_widths: Option<Vec<Option<usize>>>,
        src: SrcLines,
    },
    /// Raw HTML, rendered as a plain fenced block.
    Html(String, SrcLines),
    /// An HTML comment promoted out of `Block::Html` by the parser post-pass. Stores the full
    /// source including delimiters (same convention as `Html`, so comment helpers accept either).
    /// Renders zero lines; its bytes are still covered by the `SourceMap`.
    HtmlComment(String, SrcLines),
    /// A paragraph whose sole content is an image, promoted so the renderer can reserve a
    /// multi-row region for the graphics overlay. Mixed paragraphs keep `Inline::Image`
    /// placeholders since graphics can't sit mid-wrap.  `src` is the replaced block's.
    ImageBlock {
        alt: String,
        url: String,
        src: SrcLines,
    },
    /// YAML (`---`) or TOML (`+++`) frontmatter, recognized only where CommonMark's metadata
    /// extension accepts one. `content` is the raw text between the delimiter lines, never
    /// re-flowed; the delimiters are reproduced from `kind` (see `docs/dev/frontmatter.md`).
    MetadataBlock {
        kind: MetadataKind,
        content: String,
        src: SrcLines,
    },
    /// A footnote definition, rendered in place at its source position with the raw `label` as
    /// marker so the rendered number never diverges from the source. Renumbering is the
    /// `RenumberFootnotes` action's job, not the renderer's.
    FootnoteDefinition {
        label: String,
        blocks: Vec<Block>,
        span: LineSpan,
        /// Lines between two children that no child covers and that aren't blank: link
        /// reference definitions, which render nothing.  Usually empty.
        hidden: Vec<u32>,
    },
}

impl Block {
    /// A leaf's [`SrcLines`]; `None` for a container.
    pub fn src(&self) -> Option<&SrcLines> {
        match self {
            Block::Heading { src, .. }
            | Block::Paragraph { src, .. }
            | Block::CodeBlock { src, .. }
            | Block::HorizontalRule { src }
            | Block::Table { src, .. }
            | Block::Html(_, src)
            | Block::HtmlComment(_, src)
            | Block::ImageBlock { src, .. }
            | Block::MetadataBlock { src, .. } => Some(src),
            Block::BlockQuote { .. } | Block::List { .. } | Block::FootnoteDefinition { .. } => {
                None
            }
        }
    }

    /// Whether this is a setext heading: its source lines end in an underline, where an ATX
    /// heading is one line.
    pub fn is_setext_heading(&self) -> bool {
        matches!(self, Block::Heading { src, .. } if src.len() >= 2)
    }

    /// The block-relative source lines this block covers, leaf or container.
    pub fn span(&self) -> LineSpan {
        match self {
            Block::BlockQuote { span, .. }
            | Block::List { span, .. }
            | Block::FootnoteDefinition { span, .. } => span.clone(),
            leaf => leaf.src().map(SrcLines::span).unwrap_or_default(),
        }
    }

    /// The list items holding block-relative `line`, outermost first; `None` when a quote or a
    /// footnote holds it, as its lines carry a prefix (`>`, the label) a list's don't.
    pub fn items_holding(&self, line: u32) -> Option<Vec<&ListItem>> {
        let mut items = Vec::new();
        let mut blocks = std::slice::from_ref(self);
        while let Some(holder) = blocks.iter().find(|b| b.span().contains(&line)) {
            match holder {
                Block::List { items: list, .. } => {
                    let Some(item) = list.iter().find(|i| i.span.contains(&line)) else {
                        break;
                    };
                    items.push(item);
                    blocks = &item.blocks;
                }
                Block::BlockQuote { .. } | Block::FootnoteDefinition { .. } => return None,
                _ => break,
            }
        }
        Some(items)
    }
}

/// Which delimiter style opened a [`Block::MetadataBlock`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MetadataKind {
    Yaml,
    Toml,
}

impl MetadataKind {
    pub fn delimiter(self) -> &'static str {
        match self {
            MetadataKind::Yaml => "---",
            MetadataKind::Toml => "+++",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ListItem {
    pub blocks: Vec<Block>,
    /// `Some(true)` = checked, `Some(false)` = unchecked, `None` = not a task item.
    pub task: Option<bool>,
    /// From the marker's line through the item's last content line: never the blank lines
    /// after it, which pulldown-cmark's item range absorbs.  A loose list's spacing is the gap
    /// between one item's span and the next's.
    pub span: LineSpan,
    /// Lines between two of `blocks` that no block covers and that aren't blank: link
    /// reference definitions, which render nothing.  Usually empty.
    pub hidden: Vec<u32>,
}

// ─── Inline nodes ─────────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Inline {
    Text(String),
    Bold(Vec<Inline>),
    Italic(Vec<Inline>),
    Strikethrough(Vec<Inline>),
    Code(String),
    Link {
        text: Vec<Inline>,
        url: String,
        title: Option<String>,
    },
    Image {
        alt: String,
        url: String,
    },
    Highlight(Vec<Inline>),
    /// Mid-paragraph HTML comment, stored with delimiters; renders as zero spans.
    HtmlComment(String),
    /// Any other inline HTML (a tag such as `<span>`), kept as its source and rendered exactly
    /// like [`Text`](Self::Text).  Distinct only so a heading slug can drop it, as GitHub's
    /// does: `# a <b>x</b>` is `#a-x`, while an escaped `\<b>` stays text and keeps its `b`.
    Html(String),
    /// A footnote reference (`[^label]`). Always has a definition: pulldown-cmark leaves an
    /// undefined `[^x]` as literal text. See `docs/dev/footnotes.md` for marker rendering.
    FootnoteReference {
        label: String,
    },
    /// `$...$` inline or `$$...$$` display math, raw LaTeX source.
    /// Rendered as source-equivalent text in phase 1 (inline beautification
    /// is phase 2); a paragraph holding exactly one `display: true` Math is
    /// promoted to a `Block::ImageBlock` by the post-pass.
    Math {
        source: String,
        display: bool,
    },
    SoftBreak,
    HardBreak,
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

/// `inlines_to_plain` with hard breaks collapsed to spaces, for single-row uses.
pub fn heading_plain_text(inlines: &[Inline]) -> String {
    inlines_to_plain(inlines).replace('\n', " ")
}

/// Flatten inlines to a plain text string (no styling).  A soft break is a space, or nothing
/// between two CJK glyphs ([`segment_break::vanishes`]), as a flow renders it between the same
/// text (the renderer frames an image's alt text in a placeholder, this doesn't).  The parser
/// builds an image's alt text here too, so `![日本⏎語](x)`'s is `日本語`.
pub fn inlines_to_plain(inlines: &[Inline]) -> String {
    let mut out = String::new();
    let mut soft_breaks = Vec::new();
    push_plain(inlines, false, &mut out, &mut soft_breaks);
    // Last first, so each earlier break's byte offset still holds.  A break next to another
    // sits next to its space, so its fate doesn't hang on the other's.
    for at in soft_breaks.into_iter().rev() {
        let before = out[..at].chars().next_back();
        let after = out[at + 1..].chars().next();
        if before
            .zip(after)
            .is_some_and(|(b, a)| segment_break::vanishes(b, a))
        {
            out.remove(at);
        }
    }
    out
}

/// The text GitHub slugs a heading from: [`inlines_to_plain`] less what isn't the heading's
/// text content (image alt text, inline HTML tags), and with a soft break as the newline it
/// is rather than a space, so it drops out of the slug instead of becoming a `-` (a setext
/// `Foo` / `bar` heading is `#foobar`).
pub fn heading_slug_text(inlines: &[Inline]) -> String {
    let mut out = String::new();
    push_plain(inlines, true, &mut out, &mut Vec::new());
    out
}

/// Push `inlines`' text onto `out`, and the byte offset of each soft break's space onto
/// `soft_breaks` (`for_slug` pushes a newline instead, and no offset).
fn push_plain(inlines: &[Inline], for_slug: bool, out: &mut String, soft_breaks: &mut Vec<usize>) {
    for inline in inlines {
        match inline {
            Inline::Text(t) => out.push_str(t),
            Inline::Html(h) if !for_slug => out.push_str(h),
            Inline::Html(_) => {}
            Inline::Bold(inner)
            | Inline::Italic(inner)
            | Inline::Strikethrough(inner)
            | Inline::Highlight(inner) => push_plain(inner, for_slug, out, soft_breaks),
            Inline::Code(c) => out.push_str(c),
            Inline::Link { text, .. } => push_plain(text, for_slug, out, soft_breaks),
            Inline::Image { alt, .. } if !for_slug => out.push_str(alt),
            Inline::Image { .. } => {}
            Inline::HtmlComment(_) => {}
            // Footnote markers are chrome, not prose: keep them out of heading slugs.
            Inline::FootnoteReference { .. } => {}
            // Math renders as its source in phase 1 (delimiters included,
            // width-equivalent to the source text).
            Inline::Math { source, display } => {
                let delim = if *display { "$$" } else { "$" };
                out.push_str(delim);
                out.push_str(source);
                out.push_str(delim);
            }
            Inline::SoftBreak if for_slug => out.push('\n'),
            Inline::SoftBreak => {
                soft_breaks.push(out.len());
                out.push(' ');
            }
            Inline::HardBreak => out.push('\n'),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The slug text leaves out what GitHub's heading text content doesn't hold, and keeps a
    /// line break a newline; the display text keeps all of it.
    #[test]
    fn heading_slug_text_drops_alt_text_and_markup() {
        let inlines = [
            Inline::Text("a ".into()),
            Inline::Image {
                alt: "alt".into(),
                url: "x.png".into(),
            },
            Inline::Html("<b>".into()),
            Inline::Bold(vec![Inline::Text("b".into())]),
            Inline::Html("</b>".into()),
            Inline::SoftBreak,
            Inline::Text("c".into()),
        ];
        assert_eq!(inlines_to_plain(&inlines), "a alt<b>b</b> c");
        assert_eq!(heading_slug_text(&inlines), "a b\nc");
    }

    /// A soft break is a space in plain text, or nothing between two CJK glyphs (issue #79), as a
    /// reflowed paragraph renders it; a slug's is a newline either way.
    #[test]
    fn plain_text_drops_a_soft_break_between_cjk_glyphs() {
        let inlines = [
            Inline::Text("日本".into()),
            Inline::SoftBreak,
            Inline::Italic(vec![Inline::Text("語".into())]),
            Inline::SoftBreak,
            Inline::Text("abc".into()),
        ];
        assert_eq!(inlines_to_plain(&inlines), "日本語 abc");
        assert_eq!(heading_slug_text(&inlines), "日本\n語\nabc");
        let two = [
            Inline::Text("日".into()),
            Inline::SoftBreak,
            Inline::HtmlComment("<!-- c -->".into()),
            Inline::SoftBreak,
            Inline::Text("本".into()),
        ];
        assert_eq!(
            inlines_to_plain(&two),
            "日  本",
            "a break beside a break stays"
        );
    }

    /// Every line of each shape, read back through the accessors.
    fn round_trip(cols: &[Option<u32>]) -> SrcLines {
        let src = SrcLines::new(3, cols);
        assert_eq!(src.len(), cols.len());
        assert_eq!(src.cols().collect::<Vec<_>>(), cols);
        assert_eq!(src.col(cols.len()), None, "past the end");
        assert_eq!(src.span(), 3..3 + cols.len() as u32);
        src
    }

    #[test]
    fn common_shapes_store_uniformly() {
        for cols in [
            &[][..],
            &[Some(2)],
            &[Some(0), Some(0), Some(0)],
            &[Some(0), None],                   // setext heading
            &[None, Some(4), Some(4), None],    // fenced code
            &[Some(2), None, Some(2), Some(2)], // table
            &[None],                            // an empty ATX heading
            &[None, None],                      // an empty fence
        ] {
            let src = round_trip(cols);
            assert!(matches!(src.cols, Cols::Uniform { .. }), "{cols:?}");
        }
    }

    #[test]
    fn other_shapes_store_every_line() {
        for cols in [
            &[Some(2), Some(1)][..],
            &[None, None, None],
            &[Some(0), None, None, Some(0), None],
            &[Some(2), Some(70_000)],
        ] {
            let src = round_trip(cols);
            assert!(matches!(src.cols, Cols::Varied(_)), "{cols:?}");
        }
    }

    /// Equal content is an equal value, whichever way it was built, so the render cache's
    /// `Block` keys still compare by content.
    #[test]
    fn equal_columns_build_equal_values() {
        let a = SrcLines::new(0, &[None, Some(1), None]);
        let b = SrcLines::new(0, &a.cols().collect::<Vec<_>>());
        assert_eq!(a, b);
        assert_ne!(a, SrcLines::new(0, &[None, Some(2), None]));
        assert_ne!(a, SrcLines::new(0, &[Some(1), None, None]));
        assert_eq!(SrcLines::new(0, &[]), SrcLines::default());
    }

    /// AST snapshots read the per-line list, not the storage form.
    #[test]
    fn debug_shows_the_per_line_columns() {
        assert_eq!(
            format!("{:?}", SrcLines::new(1, &[None, Some(2)])),
            "SrcLines { first: 1, content_col: [None, Some(2)] }"
        );
    }
}