Skip to main content

carve/extensions/
code_callouts.rs

1//! CodeCallouts (#88, Tier-2). `<n>` markers at the end of fenced-code lines
2//! render as `<b class="callout">` bubbles, and an immediately following
3//! paragraph of `<n> text` lines binds as `<ol class="callouts">`. carve-rs has
4//! no per-node block render hook, so (like `glossary` / `list-table`) a
5//! `before_render` transform rewrites a code-block-with-markers into a
6//! [`BlockNode::ExtensionCarrier`] carrier and the bound paragraph into another, both
7//! rendered by [`CarveExtension::render_extension_carrier`]. Off by default;
8//! optional-corpus pinned when enabled. See docs/extensions.md §10.
9
10use crate::ast::{Attrs, BlockNode, CodeBlock, Document, ExtensionCarrier, InlineNode, Paragraph};
11use crate::escape::escape_attr;
12use crate::extension::{BeforeRenderContext, CarveExtension, RenderContext};
13use crate::render::render_attrs;
14
15const CODE_CARRIER: &str = "code-callouts-code";
16const LIST_CARRIER: &str = "code-callouts-list";
17
18/// The CodeCallouts Tier-2 extension. Off by default; enable per processor.
19#[derive(Debug, Default, Clone)]
20pub struct CodeCallouts;
21
22impl CodeCallouts {
23    /// Create the code-callout extension with its defaults.
24    pub fn new() -> Self {
25        Self
26    }
27}
28
29impl CarveExtension for CodeCallouts {
30    fn name(&self) -> &'static str {
31        "codeCallouts"
32    }
33
34    fn before_render(&self, mut doc: Document, _ctx: &BeforeRenderContext<'_>) -> Document {
35        bind_blocks(&mut doc.children);
36        doc
37    }
38
39    fn render_extension_carrier(
40        &self,
41        node: &ExtensionCarrier,
42        ctx: &RenderContext<'_>,
43    ) -> Option<String> {
44        match node.name.as_str() {
45            CODE_CARRIER => Some(render_code(node, ctx)),
46            LIST_CARRIER => Some(render_list(node, ctx)),
47            _ => None,
48        }
49    }
50}
51
52// ----- before_render: wrap code-with-markers + the bound list ------------------
53
54fn bind_blocks(blocks: &mut [BlockNode]) {
55    for b in blocks.iter_mut() {
56        descend(b);
57    }
58    let mut i = 0;
59    while i < blocks.len() {
60        let has_marker =
61            matches!(&blocks[i], BlockNode::CodeBlock(c) if content_has_marker(&c.content));
62        if has_marker {
63            let bind_list = matches!(blocks.get(i + 1), Some(BlockNode::Paragraph(p)) if is_callout_candidate(p));
64            let code = std::mem::replace(&mut blocks[i], placeholder());
65            blocks[i] = carrier(CODE_CARRIER, code);
66            if bind_list {
67                let para = std::mem::replace(&mut blocks[i + 1], placeholder());
68                blocks[i + 1] = carrier(LIST_CARRIER, para);
69                i += 1;
70            }
71        }
72        i += 1;
73    }
74}
75
76fn descend(b: &mut BlockNode) {
77    match b {
78        BlockNode::BlockQuote(q) => bind_blocks(&mut q.children),
79        BlockNode::Directive(d) => bind_blocks(&mut d.children),
80        BlockNode::Div(d) => bind_blocks(&mut d.children),
81        BlockNode::Admonition(a) => bind_blocks(&mut a.children),
82        BlockNode::ExtensionCarrier(e) => bind_blocks(&mut e.children),
83        BlockNode::List(l) => {
84            for item in &mut l.items {
85                bind_blocks(&mut item.children);
86            }
87        }
88        BlockNode::DefinitionList(dl) => {
89            for item in &mut dl.items {
90                for def in &mut item.definitions {
91                    bind_blocks(def);
92                }
93            }
94        }
95        _ => {}
96    }
97}
98
99fn placeholder() -> BlockNode {
100    BlockNode::Paragraph(Paragraph {
101        attrs: None,
102        children: Vec::new(),
103        ..Default::default()
104    })
105}
106
107fn carrier(name: &str, inner: BlockNode) -> BlockNode {
108    BlockNode::ExtensionCarrier(ExtensionCarrier {
109        attrs: None,
110        name: name.to_string(),
111        children: vec![inner],
112        summary: None,
113        label: None,
114        pos: None,
115    })
116}
117
118// ----- marker / item recognition ----------------------------------------------
119
120/// A `<n>` (ASCII digits) that is the last non-whitespace content on `line`.
121/// Returns `(prefix, whitespace_before_marker, digits)`.
122fn parse_marker(line: &str) -> Option<(&str, &str, &str)> {
123    let trimmed = line.trim_end_matches([' ', '\t']);
124    let inner = trimmed.strip_suffix('>')?;
125    let open = inner.rfind('<')?;
126    let digits = &inner[open + 1..];
127    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
128        return None;
129    }
130    let before = &inner[..open];
131    let prefix = before.trim_end_matches([' ', '\t']);
132    let ws = &before[prefix.len()..];
133    Some((prefix, ws, digits))
134}
135
136fn content_has_marker(content: &str) -> bool {
137    content.lines().any(|l| parse_marker(l).is_some())
138}
139
140/// `<n> ` at the very start of a line's first text node → the marker number.
141fn item_number(line: &[InlineNode]) -> Option<String> {
142    let InlineNode::Text(t) = line.first()? else {
143        return None;
144    };
145    let rest = t.value.strip_prefix('<')?;
146    let gt = rest.find('>')?;
147    let digits = &rest[..gt];
148    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
149        return None;
150    }
151    if rest.as_bytes().get(gt + 1) != Some(&b' ') {
152        return None;
153    }
154    Some(digits.to_string())
155}
156
157fn is_callout_candidate(p: &Paragraph) -> bool {
158    let lines = split_lines(&p.children);
159    !lines.is_empty() && lines.iter().all(|line| item_number(line).is_some())
160}
161
162// ----- render -----------------------------------------------------------------
163
164fn render_code(node: &ExtensionCarrier, ctx: &RenderContext<'_>) -> String {
165    let Some(BlockNode::CodeBlock(c)) = node.children.first() else {
166        // Another code-block transformer (MathBlock / FencedRender) registered
167        // before us may have replaced the carrier's inner CodeBlock; render
168        // whatever it became so the content is never dropped.
169        return ctx.render_blocks_at(&node.children, ctx.level());
170    };
171    let pad = ctx.indent(ctx.level());
172    let body = c
173        .content
174        .split('\n')
175        .map(|line| match parse_marker(line) {
176            Some((prefix, ws, n)) => format!(
177                "{}{}<b class=\"callout\" data-callout=\"{}\">{}</b>",
178                ctx.escape_html(prefix),
179                ws,
180                n,
181                n
182            ),
183            None => ctx.escape_html(line),
184        })
185        .collect::<Vec<_>>()
186        .join("\n");
187    let title = code_title_attr(c);
188    let lang = c
189        .lang
190        .as_ref()
191        .map(|l| format!(" class=\"language-{l}\""))
192        .unwrap_or_default();
193    format!(
194        "{pad}<pre{title}{attrs}><code{lang}>{body}</code></pre>",
195        attrs = render_attrs(&c.attrs)
196    )
197}
198
199/// Mirror the core code renderer: an opener `header` is carried on `title` and
200/// emitted as a `title="..."` attribute unless the author already set one.
201fn code_title_attr(c: &CodeBlock) -> String {
202    match &c.title {
203        Some(title)
204            if !c
205                .attrs
206                .as_ref()
207                .is_some_and(|a| a.key_values.keys().any(|k| k.eq_ignore_ascii_case("title"))) =>
208        {
209            format!(" title=\"{}\"", escape_attr(title))
210        }
211        _ => String::new(),
212    }
213}
214
215fn render_list(node: &ExtensionCarrier, ctx: &RenderContext<'_>) -> String {
216    let Some(BlockNode::Paragraph(p)) = node.children.first() else {
217        return String::new();
218    };
219    let pad = ctx.indent(ctx.level());
220    let inner = ctx.indent(ctx.level() + 1);
221    let items = split_lines(&p.children)
222        .into_iter()
223        .map(|line| {
224            let n = item_number(&line).unwrap_or_default();
225            let mut rest: Vec<InlineNode> = Vec::with_capacity(line.len());
226            if let Some(InlineNode::Text(t)) = line.first() {
227                rest.push(InlineNode::text(strip_item_prefix(&t.value)));
228            }
229            rest.extend(line.iter().skip(1).cloned());
230            format!(
231                "{}<li value=\"{}\">{}</li>",
232                inner,
233                n,
234                ctx.render_inlines(&rest)
235            )
236        })
237        .collect::<Vec<_>>()
238        .join("\n");
239    format!(
240        "{pad}<ol{attrs}>\n{items}\n{pad}</ol>",
241        attrs = render_attrs(&Some(with_base_class(&p.attrs, "callouts")))
242    )
243}
244
245/// Strip a leading `<n> ` from the first text node.
246fn strip_item_prefix(t: &str) -> String {
247    if let Some(rest) = t.strip_prefix('<') {
248        if let Some(gt) = rest.find('>') {
249            return rest[gt + 2..].to_string();
250        }
251    }
252    t.to_string()
253}
254
255fn with_base_class(attrs: &Option<Attrs>, base: &str) -> Attrs {
256    let mut a = attrs.clone().unwrap_or_default();
257    a.classes.insert(0, base.to_string());
258    a
259}
260
261// ----- helpers ----------------------------------------------------------------
262
263/// Split an inline run into per-line segments at each soft-break (dropping
264/// empties).
265fn split_lines(nodes: &[InlineNode]) -> Vec<Vec<InlineNode>> {
266    let mut lines: Vec<Vec<InlineNode>> = vec![Vec::new()];
267    for n in nodes {
268        if matches!(n, InlineNode::SoftBreak(_)) {
269            lines.push(Vec::new());
270        } else {
271            lines.last_mut().unwrap().push(n.clone());
272        }
273    }
274    lines.retain(|l| !l.is_empty());
275    lines
276}