Skip to main content

specfold_core/export/markdown/
rewrite.rs

1//! A page body with each [[reference]] written as its target's link, or as plain text and
2//! reported when it leads nowhere in the tree.
3
4use super::page::Page;
5use super::types::{Target, Unresolved};
6use crate::paths::relative_from_file;
7use std::collections::HashMap;
8
9/// GitHub's heading slug: lower case, punctuation dropped, spaces to `-`.
10pub fn github_slug(heading: &str) -> String {
11    heading
12        .trim()
13        .to_lowercase()
14        .chars()
15        .filter_map(|c| {
16            if c.is_alphanumeric() || c == '-' || c == '_' {
17                Some(c)
18            } else if c == ' ' {
19                Some('-')
20            } else {
21                None
22            }
23        })
24        .collect()
25}
26
27pub(super) fn rewrite(
28    p: &Page,
29    t: Target,
30    pages: &[Page],
31    by_idx: &HashMap<usize, usize>,
32    unresolved: &mut Vec<Unresolved>,
33    src: &str,
34) -> String {
35    let mut out = String::new();
36    let mut at = 0;
37    for l in &p.links {
38        out.push_str(&p.body[at..l.span.0]);
39        at = l.span.1;
40        let dest = l.idx.and_then(|i| by_idx.get(&i)).map(|&i| &pages[i]);
41        let text = l.label.clone().or_else(|| dest.map(|q| q.title.clone())).or_else(|| l.title.clone());
42        let Some(q) = dest.filter(|_| l.reason.is_none()) else {
43            let reason = l.reason.clone().unwrap_or_else(|| {
44                if l.remote.is_some() {
45                    format!("in remote {}", l.remote.clone().unwrap_or_default())
46                } else {
47                    "not part of this export".into()
48                }
49            });
50            unresolved.push(Unresolved { path: src.into(), raw: l.raw.clone(), reason });
51            let inner = l.raw.trim_start_matches("[[").trim_end_matches("]]");
52            out.push_str(&text.unwrap_or_else(|| inner.split('|').next().unwrap_or(inner).trim().to_string()));
53            continue;
54        };
55        let text = text.unwrap_or_else(|| q.title.clone());
56        let heading = l.anchor.as_ref().map(|a| q.headings.get(a).cloned().unwrap_or_else(|| a.clone()));
57        out.push_str(&match t {
58            Target::Obsidian => {
59                let h = heading.map(|h| format!("#{h}")).unwrap_or_default();
60                format!("[[{}{h}|{text}]]", q.file.trim_end_matches(".md"))
61            }
62            Target::Mkdocs | Target::Docusaurus => {
63                let a = l.anchor.as_ref().map(|a| format!("#{a}")).unwrap_or_default();
64                format!("[{text}]({}{a})", relative_from_file(&p.file, &q.file))
65            }
66            Target::GithubWiki => {
67                let a = heading.map(|h| format!("#{}", github_slug(&h))).unwrap_or_default();
68                format!("[{text}]({}{a})", q.file.trim_end_matches(".md"))
69            }
70        });
71    }
72    out.push_str(&p.body[at..]);
73    if t.keeps_anchors() { out } else { strip_anchors(&out) }
74}
75
76/// Removes `{#anchor}` from headings outside code fences.
77pub(super) fn strip_anchors(text: &str) -> String {
78    let re = regex::Regex::new(r"\s*\{#[A-Za-z0-9][A-Za-z0-9_.-]*\}\s*$").expect("static regex is valid");
79    let mut fence = crate::model::markdown::Fence::default();
80    let mut out = String::new();
81    for line in text.split_inclusive('\n') {
82        let tr = line.trim_start();
83        fence.step(tr);
84        if !fence.inside() && tr.starts_with('#') {
85            let nl = if line.ends_with('\n') { "\n" } else { "" };
86            out.push_str(&re.replace(line.trim_end_matches(['\n', '\r']), ""));
87            out.push_str(nl);
88        } else {
89            out.push_str(line);
90        }
91    }
92    out
93}