Skip to main content

specfold_core/export/
links.rs

1//! Every `[[reference]]` in a body with its byte span and what it resolves to, using the same
2//! resolution as rule L1 (ids, aliases, paths, anchors and remotes).
3
4use crate::config::Config;
5use crate::corpus::Corpus;
6use crate::corpus::graph::{Graph, Resolution};
7use crate::model::RefText;
8use crate::model::markdown::body::{is_wiki_link, wiki_re};
9use crate::workspace::remotes::{self, Remote};
10use serde::Serialize;
11
12/// One reference as written: `span` is the byte range of `[[…]]` in the body.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Occurrence {
15    pub span: (usize, usize),
16    pub raw: String,
17    pub target: String,
18    pub label: Option<String>,
19}
20
21/// A reference and where it leads. `target_id` is set for a document here or in a remote;
22/// `reason` is set when it does not resolve.
23#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
24pub struct Link {
25    pub span: (usize, usize),
26    pub raw: String,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub label: Option<String>,
29    pub target_id: Option<String>,
30    pub anchor: Option<String>,
31    pub remote: Option<String>,
32    pub resolved_path: Option<String>,
33    pub title: Option<String>,
34    pub status: Option<String>,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub reason: Option<String>,
37    /// The local document index, for exporters inside specfold.
38    #[serde(skip)]
39    pub idx: Option<usize>,
40}
41
42/// The references in `body`, skipping fenced code blocks and inline code like rule L1 does.
43pub fn occurrences(body: &str) -> Vec<Occurrence> {
44    let mut out = Vec::new();
45    outside_code(body, wiki_re(), |start, m| {
46        if !is_wiki_link(m) {
47            return;
48        }
49        let whole = m.get(0).expect("capture group 0 always exists");
50        let inner = &whole.as_str()[2..whole.as_str().len() - 2];
51        let label = inner.split_once('|').map(|(_, l)| l.trim().to_string()).filter(|l| !l.is_empty());
52        out.push(Occurrence {
53            span: (start + whole.start(), start + whole.end()),
54            raw: whole.as_str().to_string(),
55            target: m[1].trim().to_string(),
56            label,
57        });
58    });
59    out
60}
61
62/// `[text](plan:root/…)`: a Markdown link whose target has the shape of a document id. Such a
63/// link is not a reference: rule L1 warns and points at `[[id]]`, and the built-in export
64/// rewrites the ones that resolve.
65fn md_id_re() -> &'static regex::Regex {
66    static R: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
67    R.get_or_init(|| {
68        regex::Regex::new(r"(^|[^!\]])\[([^\[\]\n]*)\]\(<?([a-z][a-z0-9_-]*:[^\s()<>/:]+/[^\s()<>]+)>?\)")
69            .expect("static regex is valid")
70    })
71}
72
73/// The Markdown links in `body` whose target looks like `<type>:<owner>/<rest>`, outside code.
74pub fn md_id_occurrences(body: &str) -> Vec<Occurrence> {
75    let mut out = Vec::new();
76    outside_code(body, md_id_re(), |start, m| {
77        let lead = m.get(1).map_or(0, |g| g.len());
78        let whole = m.get(0).expect("capture group 0 always exists");
79        let text = m[2].trim().to_string();
80        out.push(Occurrence {
81            span: (start + whole.start() + lead, start + whole.end()),
82            raw: whole.as_str()[lead..].to_string(),
83            target: m[3].to_string(),
84            label: Some(text).filter(|l| !l.is_empty()),
85        });
86    });
87    out
88}
89
90/// A plain Markdown link or image: `[text](target)` or `![alt](target "title")`.
91#[derive(Debug, Clone, PartialEq)]
92pub struct MdLink {
93    /// Byte offset in the body.
94    pub start: usize,
95    pub image: bool,
96    pub text: String,
97    pub target: String,
98}
99
100pub(crate) fn md_link_re() -> &'static regex::Regex {
101    static R: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
102    R.get_or_init(|| {
103        regex::Regex::new(
104            r#"(!?)\[([^\[\]\n]*)\]\(\s*(?:<([^<>\n]*)>|([^\s()<>]*))(?:\s+(?:"[^"\n]*"|'[^'\n]*'))?\s*\)"#,
105        )
106        .expect("static regex is valid")
107    })
108}
109
110/// Every inline Markdown link and image in `body`, outside code.
111pub fn md_links(body: &str) -> Vec<MdLink> {
112    let mut out = Vec::new();
113    outside_code(body, md_link_re(), |start, m| {
114        let target = m.get(3).or(m.get(4)).map_or("", |g| g.as_str()).to_string();
115        out.push(MdLink {
116            start: start + m.get(0).expect("capture group 0 always exists").start(),
117            image: !m[1].is_empty(),
118            text: m[2].to_string(),
119            target,
120        });
121    });
122    out
123}
124
125/// `[label]: target "title"`: a reference-style link definition (not a footnote `[^1]:`).
126pub(crate) fn md_ref_def_re() -> &'static regex::Regex {
127    static R: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
128    R.get_or_init(|| {
129        regex::Regex::new(r"^ {0,3}\[([^\]^\n][^\]\n]*)\]:[ \t]*(?:<([^<>\n]*)>|([^\s<>]+))")
130            .expect("static regex is valid")
131    })
132}
133
134/// Every reference-style link definition in `body`, outside code (C180).
135pub fn md_ref_defs(body: &str) -> Vec<MdLink> {
136    let mut out = Vec::new();
137    outside_code(body, md_ref_def_re(), |start, m| {
138        out.push(MdLink {
139            start: start + m.get(0).expect("capture group 0 always exists").start(),
140            image: false,
141            text: m[1].to_string(),
142            target: m.get(2).or(m.get(3)).map_or("", |g| g.as_str()).to_string(),
143        });
144    });
145    out
146}
147
148/// Calls `each(line_start, captures)` for every match of `re` outside fences and inline code.
149pub(crate) fn outside_code(body: &str, re: &regex::Regex, mut each: impl FnMut(usize, &regex::Captures)) {
150    let mut fence = crate::model::markdown::Fence::default();
151    let mut offset = 0;
152    for line in body.split_inclusive('\n') {
153        let start = offset;
154        offset += line.len();
155        let trimmed = line.trim_start();
156        if fence.step(trimmed) || fence.inside() {
157            continue;
158        }
159        let code = code_spans(line);
160        for m in re.captures_iter(line) {
161            let whole = m.get(0).expect("capture group 0 always exists");
162            if code.iter().any(|&(a, b)| whole.start() < b && whole.end() > a) {
163                continue;
164            }
165            each(start, &m);
166        }
167    }
168}
169
170/// Byte ranges of inline code on one line.
171fn code_spans(line: &str) -> Vec<(usize, usize)> {
172    let b = line.as_bytes();
173    let mut out = Vec::new();
174    let mut i = 0;
175    while i < b.len() {
176        if b[i] != b'`' {
177            i += 1;
178            continue;
179        }
180        let n = b[i..].iter().take_while(|&&c| c == b'`').count();
181        let open = i;
182        i += n;
183        let mut j = i;
184        let mut closed = false;
185        while j < b.len() {
186            if b[j] == b'`' {
187                let m = b[j..].iter().take_while(|&&c| c == b'`').count();
188                if m == n {
189                    out.push((open, j + m));
190                    i = j + m;
191                    closed = true;
192                    break;
193                }
194                j += m;
195            } else {
196                j += 1;
197            }
198        }
199        if !closed {
200            break;
201        }
202    }
203    out
204}
205
206/// Resolves one reference.
207pub fn resolve(c: &Corpus, g: &Graph, o: &Occurrence) -> Link {
208    let r = RefText::parse(&o.target);
209    let mut l = Link {
210        span: o.span,
211        raw: o.raw.clone(),
212        label: o.label.clone(),
213        target_id: None,
214        anchor: r.anchor,
215        remote: None,
216        resolved_path: None,
217        title: None,
218        status: None,
219        reason: None,
220        idx: None,
221    };
222    match g.resolve(&o.target) {
223        Resolution::Doc { idx, anchor, .. } => {
224            let d = &c.docs[idx];
225            l.target_id = Some(d.id.to_string());
226            l.anchor = anchor;
227            l.resolved_path = Some(d.path.clone());
228            l.title = d.title.clone();
229            l.status = d.status();
230            l.idx = Some(idx);
231        }
232        Resolution::Ambiguous(list) => {
233            l.reason = Some(format!("ambiguous ({} documents)", list.len()));
234        }
235        Resolution::MissingAnchor { idx, anchor } => {
236            l.target_id = Some(c.docs[idx].id.to_string());
237            l.resolved_path = Some(c.docs[idx].path.clone());
238            l.reason = Some(format!("{} has no anchor #{anchor}", c.docs[idx].id));
239        }
240        Resolution::Missing => remote(&c.cfg, &o.target, &mut l),
241    }
242    l
243}
244
245fn remote(cfg: &Config, text: &str, l: &mut Link) {
246    l.reason = Some(match remotes::resolve(cfg, text) {
247        Remote::Local => "names no document".into(),
248        Remote::Found { name, id, title, file, .. } => {
249            l.target_id = Some(id);
250            l.remote = Some(name);
251            l.title = Some(title).filter(|t| !t.is_empty());
252            l.resolved_path = Some(file.display().to_string());
253            return;
254        }
255        Remote::Absent { name, .. } => {
256            l.remote = Some(name.clone());
257            format!("remote {name} is not on disk")
258        }
259        Remote::Missing { name, id } => {
260            l.remote = Some(name.clone());
261            format!("{id} is not in remote {name}")
262        }
263        Remote::MissingAnchor { name, id, anchor } => {
264            l.remote = Some(name);
265            format!("{id} has no anchor #{anchor}")
266        }
267        Remote::Ambiguous { name, ids } => {
268            l.remote = Some(name);
269            format!("ambiguous ({} documents)", ids.len())
270        }
271    });
272}
273
274/// Every reference in `body`, resolved.
275/// Markdown links to a document id count as references here when they resolve, so an export
276/// rewrites them; one that resolves to nothing is left as written.
277pub fn of_body(c: &Corpus, g: &Graph, body: &str) -> Vec<Link> {
278    let mut out: Vec<Link> = occurrences(body).iter().map(|o| resolve(c, g, o)).collect();
279    out.extend(
280        md_id_occurrences(body).iter().map(|o| resolve(c, g, o)).filter(|l| l.idx.is_some() && l.remote.is_none()),
281    );
282    out.sort_by_key(|l| l.span.0);
283    out
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn spans_skip_code() {
292        let body = "See [[a:b/c|the c]] and `[[x:y]]`.\n```\n[[no:pe]]\n```\nAnd [[d:e#F]].\n";
293        let o = occurrences(body);
294        assert_eq!(o.len(), 2);
295        assert_eq!(&body[o[0].span.0..o[0].span.1], "[[a:b/c|the c]]");
296        assert_eq!(o[0].target, "a:b/c");
297        assert_eq!(o[0].label.as_deref(), Some("the c"));
298        assert_eq!(&body[o[1].span.0..o[1].span.1], "[[d:e#F]]");
299    }
300
301    #[test]
302    fn plain_links_and_images() {
303        let b = "See [a](x.md#Top) and ![](d.png \"t\"), `[no](code)`.\n```\n[no](fence)\n```\n![alt](<a b.png>)\n";
304        let l = md_links(b);
305        let t: Vec<(&str, bool, &str)> = l.iter().map(|x| (x.target.as_str(), x.image, x.text.as_str())).collect();
306        assert_eq!(t, [("x.md#Top", false, "a"), ("d.png", true, ""), ("a b.png", true, "alt")]);
307    }
308
309    #[test]
310    fn markdown_links_shaped_like_ids() {
311        let body = "See [the plan](plan:root/2026) and [x](https://a.b/c), ![i](img:a/b),\n`[c](plan:a/b)` [d](<adr:shop/x#Y>).\n";
312        let o = md_id_occurrences(body);
313        assert_eq!(o.len(), 2, "{o:?}");
314        assert_eq!(&body[o[0].span.0..o[0].span.1], "[the plan](plan:root/2026)");
315        assert_eq!(o[0].target, "plan:root/2026");
316        assert_eq!(o[0].label.as_deref(), Some("the plan"));
317        assert_eq!(o[1].target, "adr:shop/x#Y");
318    }
319}