Skip to main content

specfold_core/markdown/
body.rs

1//! Reads the parts of a Markdown body specfold cares about: `[[references]]`, heading anchors,
2//! and paths that cite spec files directly. Fenced code blocks and inline code are skipped, so
3//! examples in documentation never count as references.
4
5use regex::Regex;
6use serde::{Deserialize, Serialize};
7use std::sync::OnceLock;
8
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10pub struct Link {
11    pub text: String,
12    pub line: usize,
13}
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16pub struct Anchor {
17    pub name: String,
18    pub heading: String,
19    pub line: usize,
20}
21
22#[derive(Debug, Default, Clone, Serialize, Deserialize)]
23pub struct Body {
24    pub links: Vec<Link>,
25    pub anchors: Vec<Anchor>,
26    /// Paths into a spec directory written as plain text, e.g. `services/x/.spec/plan/…md`.
27    pub path_cites: Vec<Link>,
28    pub first_heading: Option<String>,
29    pub lines: usize,
30}
31
32/// `[[target]]` and `[[target|label]]`; group 1 is the target.
33pub fn wiki_re() -> &'static Regex {
34    static R: OnceLock<Regex> = OnceLock::new();
35    R.get_or_init(|| Regex::new(r"\[\[([^\[\]\n|]+)(?:\|[^\[\]\n]*)?\]\]").unwrap())
36}
37
38fn anchor_re() -> &'static Regex {
39    static R: OnceLock<Regex> = OnceLock::new();
40    R.get_or_init(|| Regex::new(r"\{#([A-Za-z0-9][A-Za-z0-9_.-]*)\}\s*$").unwrap())
41}
42
43fn inline_code_re() -> &'static Regex {
44    static R: OnceLock<Regex> = OnceLock::new();
45    R.get_or_init(|| Regex::new(r"`+[^`]*`+").unwrap())
46}
47
48/// Builds the regex that finds plain-text paths into `<spec_dir>/` ending in `.md`.
49pub fn path_cite_re(spec_dir: &str) -> Regex {
50    let dir = regex::escape(spec_dir);
51    Regex::new(&format!(r"(?:[A-Za-z0-9_.@-]+/)*{dir}/[A-Za-z0-9_./@-]+\.md")).unwrap()
52}
53
54/// `first_line` is the 1-based line number of the body's first line in the file.
55pub fn scan(body: &str, first_line: usize, path_re: &Regex) -> Body {
56    let mut out = Body::default();
57    let mut fence: Option<String> = None;
58    for (i, raw_line) in body.lines().enumerate() {
59        let line_no = first_line + i;
60        out.lines += 1;
61        let trimmed = raw_line.trim_start();
62        if let Some(f) = &fence {
63            if trimmed.starts_with(f.as_str())
64                && trimmed.trim_start_matches(f.chars().next().unwrap()).trim().is_empty()
65            {
66                fence = None;
67            }
68            continue;
69        }
70        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
71            let ch = trimmed.chars().next().unwrap();
72            let n = trimmed.chars().take_while(|c| *c == ch).count();
73            fence = Some(std::iter::repeat_n(ch, n).collect());
74            continue;
75        }
76        let line = inline_code_re().replace_all(raw_line, "");
77        if let Some(rest) = trimmed.strip_prefix('#') {
78            let level_rest = rest.trim_start_matches('#');
79            if level_rest.starts_with(' ') || level_rest.is_empty() {
80                let heading_text = level_rest.trim();
81                let heading_clean = anchor_re().replace(heading_text, "").trim().to_string();
82                if out.first_heading.is_none() && !heading_clean.is_empty() {
83                    out.first_heading = Some(heading_clean.clone());
84                }
85                if let Some(c) = anchor_re().captures(heading_text) {
86                    out.anchors.push(Anchor { name: c[1].to_string(), heading: heading_clean, line: line_no });
87                }
88            }
89        }
90        for c in wiki_re().captures_iter(&line) {
91            out.links.push(Link { text: c[1].trim().to_string(), line: line_no });
92        }
93        for m in path_re.find_iter(&line) {
94            out.path_cites.push(Link { text: m.as_str().to_string(), line: line_no });
95        }
96    }
97    out
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    #[test]
105    fn finds_links_anchors_and_cites() {
106        let body = "# Checkout\n\nSee [[adr:shop/20260101000000]] and [[sot:shop/cart#CO-1|the rule]].\n\n## Totals {#CO-1}\n\n```\n[[not:a/link]]\n```\nInline `[[not:a/link]]` too.\nOld path services/shop/.spec/plan/x.plan.md here.\n";
107        let b = scan(body, 5, &path_cite_re(".spec"));
108        assert_eq!(b.links.len(), 2);
109        assert_eq!(b.links[0].line, 7);
110        assert_eq!(b.links[1].text, "sot:shop/cart#CO-1");
111        assert_eq!(b.anchors[0].name, "CO-1");
112        assert_eq!(b.anchors[0].heading, "Totals");
113        assert_eq!(b.first_heading.as_deref(), Some("Checkout"));
114        assert_eq!(b.path_cites[0].text, "services/shop/.spec/plan/x.plan.md");
115    }
116}