skimmd 0.2.0

Skim Markdown at agent speed. Outline any Markdown file, then extract any slice.
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
//! Heading extraction and TOC row computation.
//!
//! See spec §5 (heading extraction) and §6 (TOC row computation). Every row has
//! exactly five fields in this order: `line`, `level`, `end`, `chars`, `title`.
//!
//! Two distinct right-hand boundaries are computed per heading:
//! * `chars` stops at the **next heading of any level** (the heading's own body).
//! * `end` stops before the **next heading of equal or shallower level** (subtree).

use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd};

use crate::lines::LineMap;

/// One TOC row. Field order is load-bearing (matches the Markdown emitter).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Row {
    pub line: usize,
    pub level: u8,
    pub end: usize,
    pub chars: usize,
    pub title: String,
}

/// A heading as extracted from the document.
#[derive(Debug)]
struct Heading {
    first_line: usize,
    last_line: usize,
    level: u8,
    title: String,
}

/// The exact parser options (spec §4.1 + §5.1). `ENABLE_SMART_PUNCTUATION` is
/// deliberately **off** (it would rewrite quotes/dashes and diverge titles).
/// (Not `const`: this `bitflags!` version's `BitOr` is non-const.)
fn parser_opts() -> Options {
    Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
        | Options::ENABLE_HEADING_ATTRIBUTES
        | Options::ENABLE_STRIKETHROUGH
        | Options::ENABLE_FOOTNOTES
}

/// Build the TOC rows for `lm`: a leading `preamble` row (if any) followed by one
/// row per heading, in document order.
#[must_use]
pub fn build_toc(lm: &LineMap) -> Vec<Row> {
    let text = lm.text();
    let n = lm.n();
    let headings = extract_headings(text, lm);
    let k = headings.len();

    let mut rows = Vec::with_capacity(k + 1);

    // Preamble row (§6.1): emitted iff N > 0 and line 1 is not a heading.
    if n > 0 && (k == 0 || headings[0].first_line > 1) {
        let p = if k > 0 { headings[0].first_line - 1 } else { n };
        rows.push(Row {
            line: 1,
            level: 0,
            end: p,
            chars: lm.chars(1, p),
            title: "preamble".into(),
        });
    }

    // subtree_end(i) via a stack (§6.2): pop while top.level >= cur.level.
    let mut ends = vec![n; k];
    let mut stack: Vec<usize> = Vec::new();
    for j in 0..k {
        while let Some(&i) = stack.last() {
            if headings[i].level >= headings[j].level {
                ends[i] = headings[j].first_line - 1;
                stack.pop();
            } else {
                break;
            }
        }
        stack.push(j);
    }
    // indices still on the stack keep `ends[i] = n` (their initial value).

    for (i, h) in headings.iter().enumerate() {
        let body_a = h.last_line + 1;
        let body_b = if i + 1 < k {
            headings[i + 1].first_line - 1
        } else {
            n
        };
        rows.push(Row {
            line: h.first_line,
            level: h.level,
            end: ends[i],
            chars: lm.chars(body_a, body_b),
            title: h.title.clone(),
        });
    }

    rows
}

/// Keep rows whose section text matches any candidate in a `|`-separated `needle`
/// (OR semantics). `|` is a literal separator, not regex; each candidate and the
/// section text are lowercased and whitespace-normalized (every run of whitespace,
/// incl. newlines, collapses to one space) before a plain `str::contains`. Empty
/// candidates (e.g. from `a||b`) are ignored; a value with none left matches every
/// row. A row's block is its heading line(s) plus its own body: `line` up to the
/// line before the next row's heading, or EOF (subsections excluded).
#[must_use]
pub fn filter_rows(lm: &LineMap, rows: &[Row], needle: &str) -> Vec<Row> {
    let needles = split_needles(needle);
    if needles.is_empty() {
        return rows.to_vec(); // no candidates: match every row
    }
    let n = lm.n();
    rows.iter()
        .enumerate()
        .filter_map(|(i, r)| {
            let block_end = rows.get(i + 1).map_or(n, |next| next.line - 1);
            let hay = normalize_ws(&lm.span(r.line, block_end).to_lowercase());
            needles.iter().any(|nd| hay.contains(nd)).then(|| r.clone())
        })
        .collect()
}

/// Walk the offset iterator and collect headings in document order (§5.2).
fn extract_headings(text: &str, lm: &LineMap) -> Vec<Heading> {
    let mut headings = Vec::new();
    // While inside a heading: (first_line, last_line, level, title buffer).
    let mut cur: Option<(usize, usize, u8, String)> = None;

    for (ev, range) in Parser::new_ext(text, parser_opts()).into_offset_iter() {
        match ev {
            Event::Start(Tag::Heading { level, .. }) => {
                let first = lm.line_of(range.start);
                let last = lm.line_of(range.end.saturating_sub(1));
                cur = Some((first, last, level_to_u8(level), String::new()));
            }
            Event::End(TagEnd::Heading(_)) => {
                if let Some((first, last, level, buf)) = cur.take() {
                    headings.push(Heading {
                        first_line: first,
                        last_line: last,
                        level,
                        title: normalize_ws(&buf),
                    });
                }
            }
            ev if cur.is_some() => {
                let title = &mut cur.as_mut().expect("checked cur.is_some()").3;
                match ev {
                    // Keep: visible text, code (no backticks), math.
                    Event::Text(s)
                    | Event::Code(s)
                    | Event::InlineMath(s)
                    | Event::DisplayMath(s) => title.push_str(&s),
                    // Soft/hard breaks collapse to a single space.
                    Event::SoftBreak | Event::HardBreak => title.push(' '),
                    // Inline tags (Emphasis/Strong/Strikethrough/Link/Image):
                    // boundaries add nothing; their inner Text is kept above.
                    // Html/InlineHtml/FootnoteReference: dropped.
                    _ => {}
                }
            }
            // Block-level events outside a heading (paragraphs, metadata blocks,
            // code, lists, blockquotes, …): ignored.
            _ => {}
        }
    }

    headings
}

/// `HeadingLevel` → 1..=6. (Explicit match; the enum's repr is not relied on.)
fn level_to_u8(level: HeadingLevel) -> u8 {
    match level {
        HeadingLevel::H1 => 1,
        HeadingLevel::H2 => 2,
        HeadingLevel::H3 => 3,
        HeadingLevel::H4 => 4,
        HeadingLevel::H5 => 5,
        HeadingLevel::H6 => 6,
    }
}

/// Collapse every run of whitespace (spaces, tabs, newlines, `\r`) to a single space
/// and trim the ends. Used for heading titles (§5.2 step 5) and for the `-f` filter
/// (normalizing the keyword and section text before matching).
#[must_use]
fn normalize_ws(s: &str) -> String {
    s.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Split a `-f` value on `|` into normalized candidate substrings. `|` is a
/// literal separator (no regex). Each candidate is lowercased and
/// whitespace-normalized (see `normalize_ws`); empty ones (e.g. from `a||b`)
/// are dropped. An all-empty value yields an empty `Vec`; the caller treats
/// that as "match every row".
#[must_use]
fn split_needles(needle: &str) -> Vec<String> {
    needle
        .split('|')
        .map(|p| normalize_ws(&p.to_lowercase()))
        .filter(|p| !p.is_empty())
        .collect()
}

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

    fn toc_of(s: &str) -> Vec<Row> {
        build_toc(&LineMap::new(s.to_string()))
    }

    fn rows_summary(rows: &[Row]) -> Vec<(usize, u8, usize, usize, &str)> {
        rows.iter()
            .map(|r| (r.line, r.level, r.end, r.chars, r.title.as_str()))
            .collect()
    }

    #[test]
    fn setext_trap_is_avoided() {
        // §12.4: front matter must not become a Setext "title: Foo" heading.
        let rows = toc_of("---\ntitle: Foo\n---\n\n# Real\n");
        let s = rows_summary(&rows);
        assert_eq!(
            s,
            vec![
                (1, 0, 4, 20, "preamble"), // lines 1-4
                (5, 1, 5, 0, "Real"),
            ],
            "no row titled 'title: Foo'"
        );
    }

    #[test]
    fn heading_attribute_is_stripped() {
        // §12.6: `## Foo {#foo .x}` -> title `Foo`.
        let rows = toc_of("## Foo {#foo .x}\nbody\n");
        assert_eq!(rows[0].title, "Foo");
        assert_eq!(rows[0].line, 1);
        assert_eq!(rows[0].level, 2);
    }

    #[test]
    fn blockquote_and_list_headings_count() {
        // §12.5: `> ## Quoted` and `- ## Listed` are headings (level = # count).
        let rows = toc_of("> ## Quoted\n- ## Listed\n");
        let s = rows_summary(&rows);
        assert_eq!(s[0], (1, 2, 1, 0, "Quoted"));
        assert_eq!(s[1], (2, 2, 2, 0, "Listed"));
    }

    #[test]
    fn fenced_heading_is_not_a_heading() {
        // §12.5: `# Fenced` inside a ``` fence is not a heading.
        let rows = toc_of("```text\n# Fenced\n```\n");
        assert_eq!(rows.len(), 1, "only the preamble row: {rows:?}");
        assert_eq!(rows[0].level, 0);
        assert_eq!(rows[0].title, "preamble");
    }

    #[test]
    fn setext_multiline_title() {
        // §12.7: `Alpha\nBeta\n=====` -> line 1, level 1, title `Alpha Beta`,
        // body starts at line 4.
        let rows = toc_of("Alpha\nBeta\n=====\n");
        let r = &rows[0];
        assert_eq!(r.line, 1);
        assert_eq!(r.level, 1);
        assert_eq!(r.title, "Alpha Beta");
        // heading spans lines 1-3 (content 1-2 + underline 3), body at 4..N=3? none
        assert_eq!(r.end, 3);
        assert_eq!(r.chars, 0);
    }

    #[test]
    fn setext_multiline_with_leading_blank() {
        // §12.7 variant: `\nAlpha\nBeta\n=====` -> preamble row (1-1) + heading row.
        let rows = toc_of("\nAlpha\nBeta\n=====\n");
        let s = rows_summary(&rows);
        assert_eq!(s[0], (1, 0, 1, 1, "preamble")); // line 1 is a blank line
        assert_eq!(s[1], (2, 1, 4, 0, "Alpha Beta"));
    }

    #[test]
    fn empty_atx_heading_has_empty_title() {
        let rows = toc_of("#\nbody\n");
        assert_eq!(rows[0].title, "");
        assert_eq!(rows[0].level, 1);
    }

    #[test]
    fn trailing_atx_hashes_stripped() {
        // `## Foo ##` -> title `Foo`.
        let rows = toc_of("## Foo ##\n");
        assert_eq!(rows[0].title, "Foo");
    }

    #[test]
    fn inline_markup_in_title() {
        // Spaces between inline elements are Text events and are kept; tag
        // boundaries contribute nothing. Link text kept, URL dropped.
        let rows = toc_of("## a *b* `c` ~~d~~ [e](http://x)\n");
        assert_eq!(rows[0].title, "a b c d e");
    }

    #[test]
    fn multiple_h1s_are_separate_subtrees() {
        let rows = toc_of("# A\nbody a\n# B\nbody b\n");
        // A: line 1, ends before B (line 3). B: line 3, ends at N=4.
        assert_eq!(rows[0].end, 2);
        assert_eq!(rows[1].end, 4);
    }

    #[test]
    fn html_h2_is_not_a_heading() {
        let rows = toc_of("<h2>Not a heading</h2>\n");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].title, "preamble");
    }

    #[test]
    fn no_headings_is_one_preamble_row() {
        let rows = toc_of("just text\nmore text\n");
        assert_eq!(rows.len(), 1);
        assert_eq!(
            rows[0],
            Row {
                line: 1,
                level: 0,
                end: 2,
                chars: 20,
                title: "preamble".into(),
            }
        );
    }

    #[test]
    fn empty_file_has_no_rows() {
        assert!(toc_of("").is_empty());
    }

    // --- filter_rows (the -f/--filter filter) --------------------------------

    #[test]
    fn filter_matches_title_and_body_case_insensitively() {
        let lm = LineMap::new("# Alpha\nalpha body\n## Beta\nonly beta\n".to_string());
        let rows = build_toc(&lm);
        // "beta" is in the Beta heading and body; "ALPHA" (case-insens.) in Alpha.
        assert_eq!(filter_rows(&lm, &rows, "beta")[0].title, "Beta");
        assert_eq!(filter_rows(&lm, &rows, "ALPHA").len(), 1);
        assert_eq!(filter_rows(&lm, &rows, "ALPHA")[0].title, "Alpha");
        // body-only match: "alpha" is in Alpha's body, not just its heading.
        assert_eq!(filter_rows(&lm, &rows, "body")[0].title, "Alpha");
        // no match -> empty, no panic.
        assert!(filter_rows(&lm, &rows, "zzz").is_empty());
    }

    #[test]
    fn filter_excludes_subsections() {
        // "deep" is only in the H3's body; the H2's own body must not match it,
        // but the H3 row must.
        let lm = LineMap::new("## Parent\nshallow\n### Child\ndeep text\n".to_string());
        let rows = build_toc(&lm);
        let got = filter_rows(&lm, &rows, "deep");
        assert_eq!(got.len(), 1, "only the leaf section matches: {got:?}");
        assert_eq!(got[0].title, "Child");
    }

    #[test]
    fn filter_normalizes_whitespace_including_newlines() {
        // "foo" ends line 2, "bar" starts line 3: the keyword may span the break.
        // Runs of any whitespace (space/tab/newline) collapse on both sides.
        let lm = LineMap::new("## Sec\nends with foo\nbar starts here\n".to_string());
        let rows = build_toc(&lm);
        assert_eq!(filter_rows(&lm, &rows, "foo bar").len(), 1, "single space");
        assert_eq!(filter_rows(&lm, &rows, "foo  bar").len(), 1, "double space");
        assert_eq!(filter_rows(&lm, &rows, "foo\tbar").len(), 1, "tab");
        assert_eq!(
            filter_rows(&lm, &rows, "foo\nbar").len(),
            1,
            "newline in keyword"
        );
        assert!(
            filter_rows(&lm, &rows, "foo baz").is_empty(),
            "no such phrase"
        );
    }

    #[test]
    fn filter_matches_any_of_multiple_needles() {
        let lm = LineMap::new(
            "# Alpha\nalpha body\n## Beta\nonly beta\n## Gamma\ngamma text\n".to_string(),
        );
        let rows = build_toc(&lm);
        // OR semantics: "alpha" or "gamma" -> Alpha + Gamma, not Beta.
        let got = filter_rows(&lm, &rows, "alpha|gamma");
        assert_eq!(got.len(), 2, "two of three rows: {got:?}");
        let titles: Vec<&str> = got.iter().map(|r| r.title.as_str()).collect();
        assert_eq!(titles, vec!["Alpha", "Gamma"]);
        // Each candidate is case- and whitespace-insensitive; `|` is literal.
        assert_eq!(filter_rows(&lm, &rows, "ALPHA | BETA").len(), 2);
        // Leading/trailing/consecutive pipes are ignored.
        assert_eq!(filter_rows(&lm, &rows, "||alpha|beta||").len(), 2);
        assert_eq!(filter_rows(&lm, &rows, "|alpha|").len(), 1);
        // Empty candidates (a||b, a| |b) are ignored -> same as a|b.
        assert_eq!(filter_rows(&lm, &rows, "alpha||beta").len(), 2);
        assert_eq!(filter_rows(&lm, &rows, "alpha| |beta").len(), 2);
        // No candidate left (only pipes / only whitespace) -> matches every row.
        assert_eq!(
            filter_rows(&lm, &rows, "|||").len(),
            3,
            "pipes-only matches all"
        );
        assert_eq!(
            filter_rows(&lm, &rows, "   ").len(),
            3,
            "whitespace-only matches all"
        );
        // None of the candidates present -> no rows.
        assert!(filter_rows(&lm, &rows, "foo|bar").is_empty());
    }

    // --- §12.8 structural invariants (private access, no public helper needed) -

    /// Edge-case corpus beyond the golden fixture (CRLF, setext, multi-H1, empty…).
    fn corpus() -> &'static [&'static str] {
        &[
            "",
            "# H\n",
            "plain\n",
            "---\ntitle: x\n---\n\n# Real\n",
            "Alpha\nBeta\n=====\n",
            "a\r\nb\r\nc\r\n",
            "# A\n# B\n",
            "> ## Q\n- ## L\n",
            "## x {#id}\nbody\n",
            "#\n",
            "no trailing newline",
            "# T\n\nbody\n",
        ]
    }

    /// §12.8 accounting invariant: preamble + each heading's own lines + each
    /// heading row's body chars must tile the whole file.
    #[test]
    fn accounting_invariant_holds() {
        for (i, text) in corpus().iter().enumerate() {
            let lm = LineMap::new(text.to_string());
            let headings = extract_headings(lm.text(), &lm);
            let rows = build_toc(&lm);
            let n = lm.n();
            let p = headings.first().map_or(n, |h| h.first_line - 1);
            let mut sum = lm.chars(1, p); // 0 when the preamble is suppressed
            for h in &headings {
                sum += lm.chars(h.first_line, h.last_line); // heading's own lines
            }
            for r in rows.iter().filter(|r| r.level > 0) {
                sum += r.chars; // each heading row's body
            }
            assert_eq!(sum, lm.text().chars().count(), "corpus[{i}]: {text:?}");
        }
    }

    #[test]
    fn last_row_end_equals_n() {
        for (i, text) in corpus().iter().enumerate() {
            let lm = LineMap::new(text.to_string());
            let rows = build_toc(&lm);
            let n = lm.n();
            if n == 0 {
                assert!(rows.is_empty(), "corpus[{i}]");
            } else {
                assert_eq!(rows.last().map(|r| r.end), Some(n), "corpus[{i}]: {text:?}");
            }
        }
    }

    #[test]
    fn preamble_row_consistency() {
        for text in ["intro line\n# Head\n", "# Head\n", ""] {
            let lm = LineMap::new(text.to_string());
            let rows = build_toc(&lm);
            if lm.n() == 0 {
                continue;
            }
            let first = &rows[0];
            assert_eq!(first.line, 1);
            if rows.len() > 1 {
                assert_eq!(first.level, 0);
                assert_eq!(first.title, "preamble");
                assert_eq!(first.end, rows[1].line - 1);
            } else {
                assert!(first.level > 0 && first.line == 1, "{text:?}");
            }
        }
    }
}