Skip to main content

specfold_core/model/markdown/
blocks.rs

1//! CommonMark block syntax every Markdown reader here shares: code fences and ATX headings.
2
3/// C135: where fenced code starts and ends, the CommonMark way: a fence opens with three or
4/// more backticks or tildes and closes only with the same character, at least as many, and
5/// nothing else on the line.
6#[derive(Debug, Clone, Default)]
7pub struct Fence(Option<(char, usize)>);
8
9impl Fence {
10    /// Feeds one line; true when it opens or closes a fence.
11    pub fn step(&mut self, line: &str) -> bool {
12        let t = line.trim_start();
13        let run = |ch: char| t.chars().take_while(|c| *c == ch).count();
14        match self.0 {
15            Some((ch, n)) => {
16                let m = run(ch);
17                if m >= n && t[m * ch.len_utf8()..].trim().is_empty() {
18                    self.0 = None;
19                    return true;
20                }
21                false
22            }
23            None => {
24                for ch in ['`', '~'] {
25                    let n = run(ch);
26                    // A backtick fence's info string cannot hold a backtick.
27                    if n >= 3 && !(ch == '`' && t[n..].contains('`')) {
28                        self.0 = Some((ch, n));
29                        return true;
30                    }
31                }
32                false
33            }
34        }
35    }
36
37    /// Whether the lines fed so far leave a fence open.
38    pub fn inside(&self) -> bool {
39        self.0.is_some()
40    }
41}
42
43/// C238: an ATX heading the CommonMark way: at most three spaces of indent (four make code),
44/// one to six `#`, then a space, a tab or the end of the line. Gives the level and the text,
45/// without a closing run of `#`.
46pub fn atx(line: &str) -> Option<(usize, &str)> {
47    let indent = line.len() - line.trim_start_matches(' ').len();
48    if indent > 3 {
49        return None;
50    }
51    let t = &line[indent..];
52    let n = t.chars().take_while(|c| *c == '#').count();
53    let rest = &t[n..];
54    if !(1..=6).contains(&n) || !(rest.is_empty() || rest.starts_with([' ', '\t'])) {
55        return None;
56    }
57    // C240: an optional closing run of `#` (after a space, or the whole text) is not text.
58    let text = rest.trim();
59    let open = text.trim_end_matches('#');
60    let text = if open.is_empty() || open.ends_with([' ', '\t']) { open.trim_end() } else { text };
61    Some((n, text))
62}