Skip to main content

prov_graph/
content.rs

1//! Body-prose parsing via `twig` — prov's answer to the `content_format`
2//! knob deferred in `docs/next-steps.md`, and the ingredient that makes
3//! body-link findings code-aware (DESIGN §8's principle: a `[[…]]` that is
4//! really code, e.g. `[[inf] * n for _ in range(m)]]` inside backticks, must
5//! never be treated as a link).
6//!
7//! `twig` (a sister Zig-backed project) parses Markdown/Djot into a shared AST.
8//! [`render_html`] and [`code_spans`] are direct FFI calls into it — `twig`'s C
9//! ABI exposes `twig_document_render_html` and `twig_document_nodes`, no
10//! subprocess involved. (`code_spans` used to bind a code-block-specific
11//! accessor, then a selector query per code-bearing kind; it now filters the
12//! flat node array by kind, which needs one call and reaches the detached
13//! definition subtrees a query does not — see `spans_where`.) `twig` is a
14//! required dependency, so these are always available.
15//!
16//! Pair [`code_spans`] with [`crate::link::scan_wikilinks`] (which is what
17//! actually uses it) to keep a body-link scan from ever treating code as
18//! prose.
19
20use std::ops::Range;
21use std::path::Path;
22
23/// Which body-prose grammar a document is written in. Maps to a `twig`
24/// [`twig::Format`] one-to-one; kept as prov's own type so callers can name
25/// a format without depending on `twig` directly, e.g. for the `content_format`
26/// config knob.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum ContentFormat {
29    Markdown,
30    Djot,
31    Html,
32}
33
34impl ContentFormat {
35    /// Infer the content format from a path's extension. `None` for anything
36    /// unrecognized (including config extensions, which have no body).
37    pub fn from_extension(path: &Path) -> Option<Self> {
38        match path.extension()?.to_str()? {
39            "md" | "markdown" => Some(Self::Markdown),
40            "dj" | "djot" => Some(Self::Djot),
41            "html" | "htm" => Some(Self::Html),
42            _ => None,
43        }
44    }
45
46    fn twig_format(self) -> twig::Format {
47        match self {
48            Self::Markdown => twig::Format::Markdown,
49            Self::Djot => twig::Format::Djot,
50            Self::Html => twig::Format::Html,
51        }
52    }
53
54    /// The canonical file extension for this grammar (no leading dot) — what a
55    /// freshly authored document's filename gets when prov derives a name
56    /// from a title (`prov new "A Title"`). The inverse of the primary
57    /// [`from_extension`](Self::from_extension) spelling.
58    pub fn extension(self) -> &'static str {
59        match self {
60            Self::Markdown => "md",
61            Self::Djot => "dj",
62            Self::Html => "html",
63        }
64    }
65
66    /// The `content_format` config-document spelling for this grammar.
67    pub fn as_config_str(self) -> &'static str {
68        match self {
69            Self::Markdown => "markdown",
70            Self::Djot => "djot",
71            Self::Html => "html",
72        }
73    }
74
75    /// Parse a `content_format` config value. Unknown → `None` (keep default).
76    pub fn from_config_str(value: &str) -> Option<Self> {
77        match value {
78            "markdown" | "md" => Some(Self::Markdown),
79            "djot" | "dj" => Some(Self::Djot),
80            "html" | "htm" => Some(Self::Html),
81            _ => None,
82        }
83    }
84
85    /// Whether [transcoding](transcode) between `self` and `other` loses authored
86    /// structure badly enough to need an explicit `--force`.
87    ///
88    /// HTML is the lossy endpoint, in both directions. *Into* HTML is a one-way
89    /// trip: the result is a rendering, and the Markdown or Djot the author wrote
90    /// — the `#`, the `_emph_`, the fence — is gone from the file, recoverable
91    /// only by re-deriving a guess at it. *Out of* HTML is that trip run
92    /// backwards, and everything HTML carries that a prose grammar has no spelling
93    /// for (attributes, nested inline markup, whole elements) survives only as a
94    /// raw-HTML escape, or not at all.
95    ///
96    /// Markdown ↔ Djot is deliberately not gated: twig re-spells emphasis,
97    /// headings and raw HTML into the target grammar and carries footnotes,
98    /// tables, code fences and `[[wikilinks]]` through intact. The one wart is a
99    /// reference-style link, which is inlined (`[x][ref]` → `[x](notes/b.md)`),
100    /// leaving its now-unused `[ref]:` definition behind — untidy, but nothing a
101    /// reader loses.
102    pub fn is_lossy_to(self, other: Self) -> bool {
103        self != other && (self == Self::Html || other == Self::Html)
104    }
105}
106
107/// Parse `body` as `format` with `twig`. Shared by [`render_html`] and
108/// [`code_spans`] so both go through the same error mapping.
109fn parse(body: &str, format: ContentFormat) -> crate::error::Result<twig::Document> {
110    twig::Document::parse_str(body, format.twig_format())
111        .map_err(|e| crate::error::Error::Content(format!("twig parse: {e}")))
112}
113
114/// Transcode a body from the `from` grammar into the `to` grammar.
115///
116/// Two callers, one move. It is what every page prov *authors* rather than reads
117/// goes through — `prov`'s `about` page, the history store's index and event
118/// bodies are written as Markdown in the Rust source, where they are legible to
119/// whoever maintains them, and converted here to whatever grammar the workspace
120/// actually uses (without which an HTML workspace ends up holding `.html` files
121/// whose bodies are literal `# Heading` Markdown: prov reads them back fine, and
122/// every other tool in the world does not). It is also the engine behind
123/// `convert <file> content_format`, where `from` is the grammar the document's
124/// own extension declares rather than always Markdown.
125///
126/// A body already in the target grammar is returned untouched: twig's serializer
127/// is idempotent here, but round-tripping would buy nothing and risks reflowing
128/// prose the author deliberately wrapped.
129pub fn transcode(
130    body: &str,
131    from: ContentFormat,
132    to: ContentFormat,
133) -> crate::error::Result<String> {
134    if from == to {
135        return Ok(body.to_string());
136    }
137    let mut doc = parse(body, from)?;
138    let out = doc
139        .serialize(to.twig_format())
140        .map_err(|e| crate::error::Error::Content(format!("twig serialize: {e}")))?;
141    String::from_utf8(out)
142        .map_err(|e| crate::error::Error::Content(format!("twig produced non-UTF-8: {e}")))
143}
144
145/// Parse `body` as `format` and render it to HTML, via `twig`'s FFI.
146pub fn render_html(body: &str, format: ContentFormat) -> crate::error::Result<String> {
147    let mut doc = parse(body, format)?;
148    let html = doc
149        .render_html()
150        .map_err(|e| crate::error::Error::Content(format!("twig render: {e}")))?;
151    String::from_utf8(html)
152        .map_err(|e| crate::error::Error::Content(format!("twig produced non-UTF-8 HTML: {e}")))
153}
154
155/// Whether a node kind is one `twig` parses as opaque code — inline code spans
156/// (`Verbatim`), fenced/indented code blocks (`CodeBlock`), and raw
157/// inline/block escapes (`RawInline` / `RawBlock`).
158fn is_code(kind: &twig::Kind) -> bool {
159    matches!(
160        kind,
161        twig::Kind::Verbatim | twig::Kind::CodeBlock | twig::Kind::RawInline | twig::Kind::RawBlock
162    )
163}
164
165/// What one parse of a body yields for a link scan: the spans twig reads as
166/// code, and the spans it reads as inline links, each sorted by start offset.
167///
168/// A named pair rather than a bare tuple because the two lists are the same
169/// shape, and telling them apart at a call site should not depend on getting
170/// their order right.
171#[derive(Debug, Clone, Default, PartialEq, Eq)]
172pub struct BodySpans {
173    /// Everything a link scan must treat as opaque — see [`code_spans`].
174    pub code: Vec<Range<usize>>,
175    /// Each inline `[label](target)` construct — see [`link_spans`].
176    pub links: Vec<Range<usize>>,
177}
178
179/// The code spans and the inline-link spans of `body`, in **one parse**.
180///
181/// Both are read off the same node array, because a body-link scan wants both
182/// and twig's parse is the expensive part: [`crate::link::scan_body_links`]
183/// asked for them separately and so parsed every document's prose twice, which
184/// a profile of `check` put at 41% of the run. The two lists come back sorted
185/// by start offset, each exactly as its single-kind accessor would have
186/// returned it.
187pub fn code_and_link_spans(body: &str, format: ContentFormat) -> crate::error::Result<BodySpans> {
188    let mut doc = parse(body, format)?;
189    let nodes = doc
190        .nodes()
191        .map_err(|e| crate::error::Error::Content(format!("twig nodes: {e}")))?;
192    let mut code = Vec::new();
193    let mut links = Vec::new();
194    for node in nodes {
195        if is_code(&node.kind) {
196            code.push(node.span);
197        } else if node.kind == twig::Kind::Link {
198            links.push(node.span);
199        }
200    }
201    code.sort_by_key(|s: &Range<usize>| s.start);
202    links.sort_by_key(|s: &Range<usize>| s.start);
203    Ok(BodySpans { code, links })
204}
205
206/// The spans of every node in `body` whose kind satisfies `want`, sorted by
207/// start offset. The one walk [`code_spans`] and [`link_spans`] share.
208///
209/// **Why the flat node array and not `twig`'s selector query.** A parsed
210/// document is not one tree. Footnote and link-reference definitions resolve by
211/// *label* rather than by position, so twig attaches them to no parent — and
212/// `twig_document_query` walks from the root, which means it never enters them.
213/// Both of prov's uses were wrong inside a footnote in the two opposite
214/// directions at once: a `` `[[x]]` `` in a footnote body was not reported as
215/// code, so the lexical wikilink scan promoted it to a link (DESIGN §8's
216/// false positive, the exact thing [`code_spans`] exists to prevent), and a real
217/// `[a](b.md)` in a footnote body was not reported as a link, so a rename never
218/// rewrote it and no broken-link finding was ever raised for it.
219///
220/// `Document::nodes` is indexed over the whole arena rather than walked from the
221/// root, so the detached definition subtrees are simply in it. It also replaces
222/// the four separate queries [`code_spans`] used to issue — twig's selector
223/// grammar has no union combinator, and a kind predicate needs none.
224fn spans_where(
225    body: &str,
226    format: ContentFormat,
227    want: impl Fn(&twig::Kind) -> bool,
228) -> crate::error::Result<Vec<std::ops::Range<usize>>> {
229    let mut doc = parse(body, format)?;
230    let nodes = doc
231        .nodes()
232        .map_err(|e| crate::error::Error::Content(format!("twig nodes: {e}")))?;
233    let mut spans: Vec<_> = nodes
234        .into_iter()
235        .filter(|n| want(&n.kind))
236        .map(|n| n.span)
237        .collect();
238    spans.sort_by_key(|s| s.start);
239    Ok(spans)
240}
241
242/// The byte ranges in `body` that `twig` parses as code (inline code spans,
243/// fenced code blocks, raw inline/block escapes) — everything a link scan
244/// should treat as opaque; see [`crate::link::scan_wikilinks`]. Spans are
245/// returned sorted by start offset, and cover code inside a footnote definition
246/// as well as code in the document body (see `spans_where`).
247pub fn code_spans(
248    body: &str,
249    format: ContentFormat,
250) -> crate::error::Result<Vec<std::ops::Range<usize>>> {
251    spans_where(body, format, is_code)
252}
253
254/// The byte ranges in `body` that `twig` parses as inline links — the whole
255/// `[text](target)` construct of each `link` node, in source order. This is the
256/// syntax-aware, code-aware complement to prov's lexical `[[…]]` scan: twig
257/// never reports a `[x](y)` inside a code fence, an autolink's angle brackets,
258/// or bracket text that is not actually a link, so a body-link scan built on
259/// these spans cannot mistake prose or code for a link. The caller slices each
260/// span and parses it with [`crate::link::Link::parse`] to read the target —
261/// each span holds exactly one link, so the parse never over-reaches.
262///
263/// Reference-style and autolink forms also surface as `link` nodes; the caller
264/// keeps only the inline `[label](target)` ones (a successful markdown parse),
265/// which is the form prov can resolve and rewrite in place.
266///
267/// Links inside a footnote definition are included, which a walk from the
268/// document root does not reach — see `spans_where`.
269pub fn link_spans(
270    body: &str,
271    format: ContentFormat,
272) -> crate::error::Result<Vec<std::ops::Range<usize>>> {
273    spans_where(body, format, |k| *k == twig::Kind::Link)
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    fn infers_format_from_extension() {
282        assert_eq!(
283            ContentFormat::from_extension(Path::new("a.md")),
284            Some(ContentFormat::Markdown)
285        );
286        assert_eq!(
287            ContentFormat::from_extension(Path::new("a.markdown")),
288            Some(ContentFormat::Markdown)
289        );
290        assert_eq!(
291            ContentFormat::from_extension(Path::new("a.dj")),
292            Some(ContentFormat::Djot)
293        );
294        assert_eq!(
295            ContentFormat::from_extension(Path::new("a.djot")),
296            Some(ContentFormat::Djot)
297        );
298        assert_eq!(
299            ContentFormat::from_extension(Path::new("a.html")),
300            Some(ContentFormat::Html)
301        );
302        assert_eq!(
303            ContentFormat::from_extension(Path::new("a.htm")),
304            Some(ContentFormat::Html)
305        );
306        assert_eq!(ContentFormat::from_extension(Path::new("a.yaml")), None);
307        assert_eq!(ContentFormat::from_extension(Path::new("noext")), None);
308    }
309
310    #[test]
311    fn extension_matches_the_primary_from_extension_spelling() {
312        // The derived filename's extension must round-trip back to the same format.
313        for f in [
314            ContentFormat::Markdown,
315            ContentFormat::Djot,
316            ContentFormat::Html,
317        ] {
318            let name = format!("derived.{}", f.extension());
319            assert_eq!(ContentFormat::from_extension(Path::new(&name)), Some(f));
320        }
321    }
322
323    #[test]
324    fn transcode_respells_the_grammar_and_leaves_a_matching_body_alone() {
325        // Markdown → Djot is a genuine re-spelling, not a copy: setext headings
326        // become ATX and emphasis takes djot's markers. `[[wikilinks]]` are prov's
327        // notation rather than twig's, and must ride through untouched — the
328        // `convert` engine renames files on this promise.
329        let md = "Title\n=====\n\n*emph* and [[a:b]] and `code`.\n";
330        let dj = transcode(md, ContentFormat::Markdown, ContentFormat::Djot).unwrap();
331        assert!(dj.contains("# Title"), "{dj}");
332        assert!(dj.contains("_emph_"), "{dj}");
333        assert!(dj.contains("[[a:b]]"), "wikilink verbatim: {dj}");
334        assert!(dj.contains("`code`"), "{dj}");
335
336        // Same grammar in and out: returned verbatim, so prose the author wrapped
337        // by hand is never silently reflowed.
338        assert_eq!(
339            transcode(md, ContentFormat::Markdown, ContentFormat::Markdown).unwrap(),
340            md
341        );
342
343        // And the source grammar is honoured, not assumed: djot's `_emph_` read as
344        // djot survives, where reading it as Markdown would not.
345        let back = transcode(&dj, ContentFormat::Djot, ContentFormat::Markdown).unwrap();
346        assert!(back.contains("*emph*"), "djot read as djot: {back}");
347    }
348
349    #[test]
350    fn html_is_the_lossy_endpoint_in_both_directions() {
351        // What `convert --force` gates: the prose grammars interconvert freely,
352        // and every pairing with HTML is lossy whichever way it runs.
353        assert!(!ContentFormat::Markdown.is_lossy_to(ContentFormat::Djot));
354        assert!(!ContentFormat::Djot.is_lossy_to(ContentFormat::Markdown));
355        assert!(ContentFormat::Markdown.is_lossy_to(ContentFormat::Html));
356        assert!(ContentFormat::Html.is_lossy_to(ContentFormat::Djot));
357        // A conversion to the grammar already in use is not a conversion at all.
358        for f in [
359            ContentFormat::Markdown,
360            ContentFormat::Djot,
361            ContentFormat::Html,
362        ] {
363            assert!(!f.is_lossy_to(f));
364        }
365    }
366
367    #[test]
368    fn code_and_link_spans_reach_inside_a_footnote_definition() {
369        // A footnote definition resolves by label, so twig attaches it to no
370        // parent and a walk from the document root never enters it. Both spans
371        // are read out of the flat node array for exactly this case.
372        //
373        // The code half is DESIGN §8's false positive: unmasked, the lexical
374        // `[[…]]` scan promotes this code to a link.
375        for format in [ContentFormat::Markdown, ContentFormat::Djot] {
376            let body = "Body.[^n]\n\n[^n]: A note with `[[inf] * n]` code.\n";
377            let spans = code_spans(body, format).unwrap();
378            assert_eq!(
379                spans.iter().map(|s| &body[s.clone()]).collect::<Vec<_>>(),
380                ["`[[inf] * n]`"],
381                "{format:?}"
382            );
383
384            // The link half: unreported, a rename never rewrites it and no
385            // broken-link finding is ever raised for it.
386            let body = "Body.[^n]\n\n[^n]: See [b](notes/b.md) here.\n";
387            let spans = link_spans(body, format).unwrap();
388            assert_eq!(
389                spans.iter().map(|s| &body[s.clone()]).collect::<Vec<_>>(),
390                ["[b](notes/b.md)"],
391                "{format:?}"
392            );
393        }
394    }
395
396    /// The combined accessor exists only to save a parse, so it must answer
397    /// exactly what the two single-kind ones do — including the sort order and
398    /// the footnote-definition subtrees a walk from the root would miss.
399    #[test]
400    fn one_parse_reports_what_the_two_separate_ones_do() {
401        let body = concat!(
402            "A [real](a.md) link and `[[code]]` and a [second](b.md).\n\n",
403            "```\n[fenced](c.md)\n```\n\n",
404            "Text[^fn]\n\n[^fn]: a note with [a link](d.md) and `code`.\n",
405        );
406        let spans = code_and_link_spans(body, ContentFormat::Markdown).unwrap();
407        assert_eq!(
408            spans.code,
409            code_spans(body, ContentFormat::Markdown).unwrap()
410        );
411        assert_eq!(
412            spans.links,
413            link_spans(body, ContentFormat::Markdown).unwrap()
414        );
415        assert!(
416            !spans.code.is_empty() && !spans.links.is_empty(),
417            "fixture found nothing"
418        );
419    }
420
421    #[test]
422    fn code_spans_covers_every_code_bearing_kind_in_one_pass() {
423        // One kind predicate over the flat array replaces four separate
424        // selector queries; all four kinds must still be reported, in source
425        // order regardless of the order the arena holds them in.
426        let body = "`v`\n\n```\nfenced\n```\n\n<span>raw</span>\n\n<div>\nblock\n</div>\n";
427        let spans = code_spans(body, ContentFormat::Markdown).unwrap();
428        assert!(
429            spans.windows(2).all(|w| w[0].start <= w[1].start),
430            "sorted by start: {spans:?}"
431        );
432        let covered: String = spans.iter().map(|s| &body[s.clone()]).collect();
433        // One fixture per kind: verbatim, code_block, raw_inline, raw_block.
434        // A raw *inline* is the tag alone — the prose between `<span>` and
435        // `</span>` is not code and is deliberately left unmasked — whereas a
436        // raw *block* is the whole element, its interior included.
437        for expected in ["`v`", "fenced", "<span>", "<div>\nblock\n</div>"] {
438            assert!(
439                covered.contains(expected),
440                "{expected} missing: {covered:?}"
441            );
442        }
443    }
444
445    #[test]
446    fn renders_markdown_to_html_via_twig_ffi() {
447        let html = render_html("# hi\n", ContentFormat::Markdown).unwrap();
448        assert_eq!(html, "<h1>hi</h1>\n");
449    }
450
451    #[test]
452    fn renders_djot_to_html_via_twig_ffi() {
453        let html = render_html("_hi_\n", ContentFormat::Djot).unwrap();
454        assert_eq!(html, "<p><em>hi</em></p>\n");
455    }
456
457    #[test]
458    fn renders_html_via_twig_ffi() {
459        let html = render_html("<p>hi</p>", ContentFormat::Html).unwrap();
460        assert!(html.contains("hi"));
461    }
462
463    #[test]
464    fn link_spans_find_inline_links_but_not_code_or_prose() {
465        let body = "See [the doc](notes/a.md) and `[not](a link)` and plain [text].";
466        let spans = link_spans(body, ContentFormat::Markdown).unwrap();
467        // The real inline link is found, its span the whole `[label](target)`.
468        let want = body.find("[the doc](notes/a.md)").unwrap();
469        assert!(
470            spans
471                .iter()
472                .any(|s| s.start == want && &body[s.clone()] == "[the doc](notes/a.md)"),
473            "expected the inline link span, got {spans:?}"
474        );
475        // The backtick-wrapped `[not](a link)` is code, not a link.
476        let code_at = body.find("[not]").unwrap();
477        assert!(
478            !spans.iter().any(|s| s.contains(&code_at)),
479            "code must not be a link: {spans:?}"
480        );
481        // `[text]` with no destination is not a link either.
482        let bracket_at = body.find("[text]").unwrap();
483        assert!(
484            !spans.iter().any(|s| s.contains(&bracket_at)),
485            "bare brackets are not a link"
486        );
487    }
488
489    #[test]
490    fn link_spans_read_djot_links_too() {
491        let body = "Here is [a link](../b.dj) inline.\n";
492        let spans = link_spans(body, ContentFormat::Djot).unwrap();
493        assert!(
494            spans
495                .iter()
496                .any(|s| &body[s.clone()] == "[a link](../b.dj)"),
497            "djot inline link span, got {spans:?}"
498        );
499    }
500
501    #[test]
502    fn code_spans_cover_verbatim_but_not_prose() {
503        let body = "See [[colophon:abc123]] and `[[inf] * n for _ in range(m)]]` here.";
504        let spans = code_spans(body, ContentFormat::Markdown).unwrap();
505
506        // The plain wikilink is untouched by any code span...
507        let wikilink_span = body.find("[[colophon:abc123]]").unwrap()
508            ..body.find("[[colophon:abc123]]").unwrap() + "[[colophon:abc123]]".len();
509        assert!(
510            !spans
511                .iter()
512                .any(|cs| cs.start < wikilink_span.end && wikilink_span.start < cs.end)
513        );
514
515        // ...but the backtick-wrapped one is inside exactly one code span.
516        let code_start = body.find('`').unwrap();
517        let code_end = body.rfind('`').unwrap() + 1;
518        assert!(
519            spans
520                .iter()
521                .any(|cs| cs.start <= code_start && code_end <= cs.end)
522        );
523    }
524}