Skip to main content

carve/
extension.rs

1//! Extension contracts for opt-in Carve behavior.
2//!
3//! The model mirrors the language-level extension lifecycle:
4//! parse matchers, `after_parse`, `before_render`, then renderer hooks.
5//! Implementations register extensions through [`Options`].
6
7use std::any::Any;
8use std::collections::BTreeMap;
9use std::collections::HashMap;
10
11use crate::ast::{Attrs, BlockNode, Document, ExtensionCarrier, InlineExtension, InlineNode};
12use crate::escape::{escape_attr, escape_text};
13use crate::parse::{parse_blocks_with_options, parse_matcher_inlines};
14use crate::profile::Profile;
15
16/// Render mode - a render OPTION, not document syntax. See the
17/// [extensions contract](https://markup-carve.github.io/carve/extensions)
18/// §2.5 "Static rendering mode".
19///
20/// - [`Mode::Interactive`] (default): online HTML - extensions render their
21///   interactive form (live disclosures, mermaid via a client script, KaTeX).
22/// - [`Mode::Static`]: HTML for a medium that cannot interact or run client
23///   scripts (print, PDF source, archival HTML). Extensions render through
24///   their static path (disclosures expand, diagrams/math become build-rendered
25///   output or source). The Markdown, plain-text and ANSI renderers are
26///   inherently static and reach the same end by flattening containers (they do
27///   not consult this mode).
28///
29/// `"print"` / `"email"` and similar names are RESERVED for future named
30/// presets; this enum admits only the two valid values, so an unknown mode is
31/// rejected by construction (the spec requires rejecting, not guessing).
32/// Omitting the mode means [`Mode::Interactive`], so existing callers are
33/// unaffected.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35pub enum Mode {
36    /// Live HTML (the default).
37    #[default]
38    Interactive,
39    /// Self-contained HTML for print / PDF / archival - no client scripts.
40    Static,
41}
42
43/// A build-time renderer for a diagram extension (mermaid / chart): source
44/// string in, self-contained HTML out (an `<svg>` / `<img>`).
45pub type DiagramRenderer = Box<dyn Fn(&str) -> String + 'static>;
46
47/// A build-time renderer for math: the TeX source plus a `display` flag in,
48/// MathML / HTML out.
49pub type MathRenderer = Box<dyn Fn(&str, bool) -> String + 'static>;
50
51/// A borrowed diagram renderer, as threaded into an extension's static path.
52pub(crate) type DiagramRendererRef<'r> = &'r (dyn Fn(&str) -> String + 'static);
53
54/// A borrowed math renderer, as threaded into an extension's static path.
55pub(crate) type MathRendererRef<'r> = &'r (dyn Fn(&str, bool) -> String + 'static);
56
57/// Build-time renderers for client-script extensions, supplied for a
58/// [`Mode::Static`] HTML render. Each maps the construct's source to a
59/// self-contained string the engine emits directly (an `<svg>` / `<img>` for a
60/// diagram, MathML / HTML for math). When the renderer a node needs is absent,
61/// the extension's static path falls back to source - never blank.
62///
63/// The map is **open**: a diagram renderer is keyed by the fence's css class
64/// (`mermaid`, `chart`, `graphviz`, `plantuml`, or any custom fence word), so a
65/// custom [`crate::FencedRender`] instance is static-capable without any change to this
66/// type. `math` is the one distinct entry (its closure also takes a display
67/// flag). A caller injects renderers with the builder:
68///
69/// ```
70/// use carve::{Mode, Options, StaticRenderers};
71/// let renderers = StaticRenderers::new()
72///     .diagram("mermaid", |src: &str| format!("<svg data-len=\"{}\"></svg>", src.len()))
73///     .diagram("myuml", |src: &str| format!("<img data-len=\"{}\">", src.len()))
74///     .math(|tex: &str, display: bool| format!("<math data-display=\"{display}\">{tex}</math>"));
75/// let opts = Options::new().with_mode(Mode::Static).with_renderers(renderers);
76/// ```
77#[derive(Default)]
78pub struct StaticRenderers {
79    /// Diagram renderers keyed by fence css class. source -> SVG / HTML string.
80    pub diagrams: HashMap<String, DiagramRenderer>,
81    /// Math TeX source -> MathML / HTML string. The `bool` flags display math.
82    pub math: Option<MathRenderer>,
83}
84
85impl StaticRenderers {
86    /// An empty renderer set.
87    pub fn new() -> Self {
88        Self::default()
89    }
90
91    /// Register a diagram renderer under a css-class key (chainable). Any key is
92    /// accepted, including a custom fence word's class.
93    pub fn diagram<F>(mut self, key: impl Into<String>, f: F) -> Self
94    where
95        F: Fn(&str) -> String + 'static,
96    {
97        self.diagrams.insert(key.into(), Box::new(f));
98        self
99    }
100
101    /// Register the math renderer (chainable).
102    pub fn math<F>(mut self, f: F) -> Self
103    where
104        F: Fn(&str, bool) -> String + 'static,
105    {
106        self.math = Some(Box::new(f));
107        self
108    }
109
110    /// Borrow the diagram renderer registered under `key`, if any.
111    pub fn get_diagram(&self, key: &str) -> Option<DiagramRendererRef<'_>> {
112        self.diagrams.get(key).map(|b| b.as_ref())
113    }
114}
115
116impl std::fmt::Debug for StaticRenderers {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        let mut keys: Vec<&str> = self.diagrams.keys().map(String::as_str).collect();
119        keys.sort_unstable();
120        f.debug_struct("StaticRenderers")
121            .field("diagrams", &keys)
122            .field("math", &self.math.as_ref().map(|_| "<fn>"))
123            .finish()
124    }
125}
126
127/// Whether smart typography renders as its glyph or as the source run the
128/// author typed.
129///
130/// Presentation output wants the glyph. Output written for a machine to read
131/// ASCII-folding for auto-generated heading ids (spec PART 9 section 12,
132/// "Automatic Identifiers"): an OPT-IN, orthogonal transform, matching carve-js
133/// `asciiHeadingIds` and carve-php `AsciiHeadingIdsExtension`.
134///
135/// The transliteration table is bounded (Latin, IPA, combining marks, Cyrillic,
136/// punctuation, currency, letterlike) and is the same table the other two
137/// engines carry, which is what makes the ids byte-identical across them. What
138/// it does NOT cover - Greek, CJK, Arabic, emoji - is where the two modes part.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
140pub enum AsciiHeadingIds {
141    /// No transliteration. A heading keeps its own characters, which is the
142    /// default and what the spec's core rule describes.
143    #[default]
144    Off,
145    /// Best effort: transliterate what the table covers, and KEEP what it does
146    /// not. `Grüße` becomes `Grusse`; a CJK heading keeps its characters, so it
147    /// still has a usable and unique anchor rather than an empty one.
148    Fold,
149    /// Guaranteed ASCII: transliterate as `Fold` does, then drop the residue the
150    /// table could not map, so the id matches `[0-9A-Za-z-]`. `Ωmega` becomes
151    /// `mega` - the price of the guarantee, and the reason it is not the
152    /// default.
153    Strict,
154}
155
156/// The heading-id transforms as one value.
157///
158/// The two flags are orthogonal but are applied in ONE order (transliterate,
159/// then lowercase), and every producer of an id has to apply both or neither.
160/// Passing them as separate booleans is how a call site ends up applying one.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
162pub struct HeadingIdOptions {
163    /// Lowercase the kept characters, per code point.
164    pub lowercase: bool,
165    /// Transliterate to ASCII.
166    pub ascii: AsciiHeadingIds,
167}
168
169impl HeadingIdOptions {
170    /// The case-preserving, non-folding default, spelled for a call site that
171    /// is not reading an `Options` (an id that is not a heading's).
172    pub(crate) const PLAIN: Self = Self {
173        lowercase: false,
174        ascii: AsciiHeadingIds::Off,
175    };
176
177    /// Lowercased with no folding: what index-term ids use, which group
178    /// spellings rather than anchor a heading.
179    pub(crate) const LOWERCASE: Self = Self {
180        lowercase: true,
181        ascii: AsciiHeadingIds::Off,
182    };
183}
184
185/// is usually better off with the characters that were actually typed: the
186/// glyph is a presentation choice the consumer did not ask for and cannot
187/// undo, and a search for the source spelling misses it.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
189pub enum SmartTypographyMode {
190    /// Render the resolved glyph, so `...` becomes an ellipsis. The default.
191    #[default]
192    Glyph,
193    /// Render the author's source run, so `...` stays three periods.
194    Source,
195    /// Render quote source runs while keeping other resolved glyphs.
196    QuotesSource,
197}
198
199impl SmartTypographyMode {
200    pub(crate) fn uses_source(self, kind: &str) -> bool {
201        self == Self::Source
202            || (self == Self::QuotesSource
203                && matches!(
204                    kind,
205                    "left_double_quote"
206                        | "right_double_quote"
207                        | "left_single_quote"
208                        | "right_single_quote"
209                ))
210    }
211}
212
213/// Record an engine-written attribute at the END of the author's order.
214///
215/// With an EMPTY order the renderer falls back to the canonical slots and then
216/// `key_values` in map order, which is alphabetical - so `aria-label` came out
217/// ahead of `role` and the three engines disagreed byte-for-byte on a shape the
218/// optional corpus pins. Recording the slots makes the order explicit and
219/// APPENDED, so naming a block also never moves an attribute the author placed
220/// (markup-carve/carve#1468).
221///
222/// An author's order carries no class slot when the attribute line held no
223/// class, and the renderer's fallback then writes the class LAST - behind the
224/// key recorded here, which PART 10 §1 ranks below a structural attribute. So
225/// the class slot is recorded too, after the authored slots and ahead of the
226/// minted key (markup-carve/carve-rs#1970, ruled on markup-carve/carve#2328).
227pub(crate) fn record_attr_order(attrs: &mut crate::ast::Attrs, key: &str) {
228    use crate::ast::AttrSlot;
229    if attrs.order.is_empty() {
230        // Seed the slots the renderer would otherwise have supplied itself.
231        attrs.order.push(AttrSlot::Class);
232        if attrs.id.is_some() {
233            attrs.order.push(AttrSlot::Id);
234        }
235        let existing: Vec<String> = attrs.key_values.keys().cloned().collect();
236        for k in existing {
237            if !k.eq_ignore_ascii_case(key) {
238                attrs.order.push(AttrSlot::Key(k));
239            }
240        }
241    } else if !attrs.order.iter().any(|s| matches!(s, AttrSlot::Class)) {
242        attrs.order.push(AttrSlot::Class);
243    }
244    if !attrs
245        .order
246        .iter()
247        .any(|s| matches!(s, AttrSlot::Key(k) if k.eq_ignore_ascii_case(key)))
248    {
249        attrs.order.push(AttrSlot::Key(key.to_string()));
250    }
251}
252
253/// The `labels` key for the endnote backlink's accessible name (PART 9 §16a).
254pub const LABEL_FOOTNOTE_BACKLINK: &str = "footnoteBacklink";
255pub const LABEL_ENDNOTES: &str = "endnotes";
256
257/// The `labels` key for the leading words of an index back-link's name.
258pub const LABEL_INDEX_BACKREF: &str = "indexBackref";
259
260/// The `labels` key for a tab set's accessible name.
261pub const LABEL_TABS_GROUP: &str = "tabsGroup";
262
263/// The `labels` key for a code group's accessible name.
264pub const LABEL_CODE_GROUP: &str = "codeGroup";
265
266/// The `labels` key for the table-of-contents nav's accessible name.
267///
268/// `<nav>` is a navigation landmark unconditionally - unlike `<section>`, which
269/// maps to `generic` until it is named - so an unnamed one is an entry in a
270/// reader's landmark list reading only "navigation", and a page can hold more
271/// than one (Extensions §8b.1, markup-carve/carve#1509).
272pub const LABEL_TOC_NAV: &str = "tocNav";
273
274/// The English default for a `labels` key, and the whole set.
275///
276/// The EXTENSION keys are here rather than only on their extensions so that ONE
277/// `labels` map localizes a whole document. PART 9 §16a's rule is that an
278/// extension MUST NOT require the host to configure the same text twice - and
279/// with a per-option spelling alone, switching a document to German meant
280/// finding several separate call sites and silently missing any one of them. An
281/// option set on the extension still wins for that instance.
282pub fn label_default(key: &str) -> &'static str {
283    match key {
284        LABEL_FOOTNOTE_BACKLINK => "Back to reference",
285        LABEL_ENDNOTES => "Footnotes",
286        "admonitionNote" => "Note",
287        "admonitionTip" => "Tip",
288        "admonitionWarning" => "Warning",
289        "admonitionDanger" => "Danger",
290        "admonitionInfo" => "Info",
291        "admonitionSuccess" => "Success",
292        "admonitionExample" => "Example",
293        "admonitionQuote" => "Quote",
294        LABEL_INDEX_BACKREF => "Back to",
295        LABEL_TABS_GROUP => "Tabs",
296        LABEL_CODE_GROUP => "Code examples",
297        LABEL_TOC_NAV => "Table of contents",
298        _ => "",
299    }
300}
301
302/// The two core social-token node kinds accepted by a resolver.
303#[non_exhaustive]
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum SocialLinkKind {
306    /// A mention token such as `@name`.
307    Mention,
308    /// A tag token such as `#name`.
309    Tag,
310}
311
312/// Read-only data supplied to one social-link resolver invocation.
313#[non_exhaustive]
314pub struct SocialLinkResolverInput<'a> {
315    /// Kind of token being resolved.
316    pub kind: SocialLinkKind,
317    /// Name without the token marker.
318    pub name: &'a str,
319    /// Attributes attached to the token, if any.
320    pub attrs: Option<&'a Attrs>,
321    /// Host data supplied through [`Options::social_context`].
322    pub context: Option<&'a dyn Any>,
323}
324
325impl<'a> SocialLinkResolverInput<'a> {
326    /// Assemble the read-only input for a resolver call.
327    pub fn new(
328        kind: SocialLinkKind,
329        name: &'a str,
330        attrs: Option<&'a Attrs>,
331        context: Option<&'a dyn Any>,
332    ) -> Self {
333        Self {
334            kind,
335            name,
336            attrs,
337            context,
338        }
339    }
340}
341
342/// A host lookup that returns one complete destination, no match, or an error.
343/// Errors and unresolved results have the same inert rendered form.
344pub type SocialLinkResolver<'a> =
345    dyn Fn(&SocialLinkResolverInput<'_>) -> Result<Option<String>, String> + 'a;
346
347/// Parser and renderer settings for one Carve operation.
348pub struct Options<'a> {
349    /// Include settings used by include-aware linting.
350    pub lint_includes: Option<crate::includes::IncludeOptions<'a>>,
351    /// Report caption-like paragraphs beside images or tables during linting.
352    pub lint_caption_looking_paragraph: bool,
353    /// Extensions applied in registration order.
354    pub extensions: Vec<&'a dyn CarveExtension>,
355    /// URL template used when a mention has no resolver.
356    pub mention_url: Option<String>,
357    /// URL template used when a tag has no resolver.
358    pub tag_url: Option<String>,
359    /// Host resolver for mention destinations.
360    pub mention_resolver: Option<&'a SocialLinkResolver<'a>>,
361    /// Host resolver for tag destinations.
362    pub tag_resolver: Option<&'a SocialLinkResolver<'a>>,
363    /// Opaque host data passed to social-link resolvers.
364    pub social_context: Option<&'a dyn Any>,
365    /// `:name:` replacements, applied by the HTML renderer ONLY, in all three
366    /// engines. The other targets emit the shortcode as the author wrote it:
367    /// the value is trusted RAW markup, which has no meaning in Markdown,
368    /// plain text or ANSI (markup-carve/carve-rs#1668).
369    pub symbols: BTreeMap<String, String>,
370    /// The strings the ENGINE writes rather than the author (PART 9 §16a).
371    ///
372    /// A key left out keeps its English default; [`label_default`] is the whole
373    /// set, one key today. NOT the `symbols` map's twin: a symbol is emitted
374    /// RAW because processor configuration is trusted, a label is TEXT and is
375    /// escaped where it lands, so a host feeding these from a translation
376    /// catalog is not handing the renderer an injection vector.
377    ///
378    /// A caption's label is the author's word (`^ Figure #: …`), and
379    /// extension-written strings stay options on the extension that writes them
380    /// (`HeadingPermalinks`' `aria_label`, ...), so this map stays small on
381    /// purpose.
382    pub labels: BTreeMap<String, String>,
383    /// Allow raw HTML passthrough (`` `…`{=html} `` inline and ` ```=html `
384    /// block) to emit verbatim. Default `true` (matches the corpus). Set
385    /// `false` for UNTRUSTED input: raw-HTML content is then escaped to text
386    /// instead of emitted, closing the one author-controlled raw-HTML vector.
387    pub allow_raw_html: bool,
388    /// Whether the Markdown renderer emits smart-typography glyphs or the
389    /// author's source run. Default `Glyph`; only the Markdown target reads
390    /// this.
391    pub smart_typography: SmartTypographyMode,
392    /// Roundtrip export: add the preservation carriers PART 10 §13 names, so
393    /// a render-and-import cycle recovers distinctions the serialization has no
394    /// spelling for. OFF by default on every surface, and enabling it neither
395    /// removes nor reorders an attribute §1 to §12 write.
396    ///
397    /// The TARGET decides the carrier (§13). HTML writes the attribute
398    /// inventory of §13a; Markdown writes the container carrier comments
399    /// of PART 11 §10s.
400    ///
401    /// It is an EXPORT option (§13b). It never enables a trusted HTML import,
402    /// never widens an importer's mode and never relaxes a destination check.
403    pub roundtrip: bool,
404    /// Align table columns when writing Carve source. Default `false`.
405    pub align_tables: bool,
406    /// When `true`, lowercase the kept characters of an auto-generated heading
407    /// id per code point (`char::to_lowercase`). Default `false`: heading ids
408    /// are CASE-PRESERVING (`# Getting Started` -> `Getting-Started`), matching
409    /// carve-js / carve-php.
410    pub lowercase_heading_ids: bool,
411    /// Transliterate an auto-generated heading id to ASCII, for URL and
412    /// CSS-fragment portability. Default [`AsciiHeadingIds::Off`]. Orthogonal to
413    /// `lowercase_heading_ids`: combine them for a lowercase ASCII slug.
414    pub ascii_heading_ids: AsciiHeadingIds,
415    /// When `true`, stamp each top-level block element with a `data-source-line`
416    /// attribute holding the 1-based source line where the block starts, so an
417    /// editor live-preview can sync scroll to the source. Opt-in (default
418    /// `false`) so normal rendering output is unchanged.
419    pub source_lines: bool,
420    /// Record a source span on every node that supports one (spec PART 12
421    /// section 4).
422    ///
423    /// Off by default, and the spec allows that: tracking may be gated behind a
424    /// parse option, and must be enabled when serializing. An ordinary parse
425    /// does not pay for spans it never reads.
426    pub positions: bool,
427    /// Optional feature-restriction profile. When set, disallowed nodes are
428    /// converted to text / stripped / error'd per the profile's action,
429    /// link/image URLs are gated by its link policy, and `max_nesting` /
430    /// `max_length` are enforced. The transform runs on the parsed document
431    /// before rendering, so it holds for every renderer. See [`Profile`].
432    pub profile: Option<Profile>,
433    /// Current document host, used by the profile's link policy to tell
434    /// internal from external links.
435    pub profile_base_host: Option<String>,
436    /// Render mode. [`Mode::Interactive`] (default) emits live HTML; the HTML
437    /// renderer's [`Mode::Static`] path flattens interactive constructs and
438    /// degrades client-script visuals (mermaid / chart / math) to a supplied
439    /// build renderer's output, else source. Ignored by the Markdown,
440    /// plain-text and ANSI renderers (they are inherently static). See [`Mode`].
441    pub mode: Mode,
442    /// Build-time renderers for client-script extensions, consulted only on the
443    /// HTML [`Mode::Static`] path. See [`StaticRenderers`].
444    pub renderers: StaticRenderers,
445    /// Wrap each top-level heading, and the content following it up to the next
446    /// same-or-shallower heading, in a `<section id="{slug}">` (spec PART 9
447    /// §13). Default `true`, which is what the conformance corpus pins.
448    ///
449    /// Set `false` to render headings flat: the id goes back on the `<h*>`
450    /// alongside its other attributes, and the blocks that would have been the
451    /// section's children stay as siblings - so they also lose the two-space
452    /// indentation they carried as container children.
453    ///
454    /// ```text
455    /// # A          sections: true      sections: false
456    /// p            <section id="A">    <h1 id="A">A</h1>
457    ///                <h1>A</h1>        <p>p</p>
458    ///                <p>p</p>
459    ///              </section>
460    /// ```
461    ///
462    /// For a site whose CSS or JS assumes rendered blocks are direct children
463    /// of the content container (the `.stack > * + *` spacing idiom,
464    /// `:first-child`, `nth-child()` counting, DOM child walks), the wrapper is
465    /// the one output change a clean source migration still breaks.
466    ///
467    /// Nothing else is affected: ids, collision dedup, `</#id>` crossrefs,
468    /// implicit `[Heading][]` references and heading numbering all resolve
469    /// against the slug rather than the element carrying it. The endnotes
470    /// `<section role="doc-endnotes">` is a separate construct and is emitted
471    /// either way. A heading inside a container was never wrapped, so it
472    /// renders identically under both settings.
473    pub sections: bool,
474}
475
476impl Default for Options<'_> {
477    fn default() -> Self {
478        Self {
479            extensions: Vec::new(),
480            lint_includes: None,
481            lint_caption_looking_paragraph: false,
482            mention_url: None,
483            tag_url: None,
484            mention_resolver: None,
485            tag_resolver: None,
486            social_context: None,
487            symbols: BTreeMap::new(),
488            labels: BTreeMap::new(),
489            allow_raw_html: true,
490            smart_typography: SmartTypographyMode::Glyph,
491            roundtrip: false,
492            align_tables: false,
493            lowercase_heading_ids: false,
494            ascii_heading_ids: AsciiHeadingIds::Off,
495            source_lines: false,
496            positions: false,
497            profile: None,
498            profile_base_host: None,
499            mode: Mode::Interactive,
500            renderers: StaticRenderers::default(),
501            sections: true,
502        }
503    }
504}
505
506impl<'a> Options<'a> {
507    /// The same parse settings with positions on. Renderers do not reach the
508    /// parser, so the copy leaves them empty.
509    pub(crate) fn positioned_parse_copy(&self) -> Self {
510        Self {
511            extensions: self.extensions.clone(),
512            lint_includes: self.lint_includes.clone(),
513            lint_caption_looking_paragraph: self.lint_caption_looking_paragraph,
514            mention_url: self.mention_url.clone(),
515            tag_url: self.tag_url.clone(),
516            mention_resolver: self.mention_resolver,
517            tag_resolver: self.tag_resolver,
518            social_context: self.social_context,
519            symbols: self.symbols.clone(),
520            labels: self.labels.clone(),
521            allow_raw_html: self.allow_raw_html,
522            smart_typography: self.smart_typography,
523            roundtrip: self.roundtrip,
524            align_tables: self.align_tables,
525            lowercase_heading_ids: self.lowercase_heading_ids,
526            ascii_heading_ids: self.ascii_heading_ids,
527            source_lines: self.source_lines,
528            positions: true,
529            profile: self.profile.clone(),
530            profile_base_host: self.profile_base_host.clone(),
531            mode: self.mode,
532            renderers: StaticRenderers::default(),
533            sections: self.sections,
534        }
535    }
536
537    /// Supply include settings for linting.
538    pub fn with_lint_includes(mut self, includes: crate::includes::IncludeOptions<'a>) -> Self {
539        self.lint_includes = Some(includes);
540        self
541    }
542
543    /// Create options with the defaults.
544    pub fn new() -> Self {
545        Self::default()
546    }
547
548    /// Allow or suppress raw HTML passthrough. Pass `false` for untrusted
549    /// input to escape `=html` raw inline/block content instead of emitting it.
550    pub fn with_raw_html(mut self, allow: bool) -> Self {
551        self.allow_raw_html = allow;
552        self
553    }
554
555    /// Stamp top-level block elements with a `data-source-line` attribute
556    /// (1-based). Opt-in; for editor preview scroll-sync.
557    pub fn with_source_lines(mut self, enabled: bool) -> Self {
558        self.source_lines = enabled;
559        self
560    }
561
562    /// Wrap top-level headings in `<section>`. Default `true`; pass `false` to
563    /// render headings flat with the id on the `<h*>`. See [`Options::sections`].
564    pub fn with_sections(mut self, enabled: bool) -> Self {
565        self.sections = enabled;
566        self
567    }
568
569    /// Align table columns when writing Carve source.
570    pub fn with_align_tables(mut self, enabled: bool) -> Self {
571        self.align_tables = enabled;
572        self
573    }
574
575    /// Turn roundtrip export on or off (PART 10 §13). See [`Options::roundtrip`].
576    pub fn with_roundtrip(mut self, enabled: bool) -> Self {
577        self.roundtrip = enabled;
578        self
579    }
580
581    /// Whether the HTML target writes the §13a carriers.
582    pub fn html_carriers(&self) -> bool {
583        self.roundtrip
584    }
585
586    /// Record source spans on AST nodes that support them.
587    pub fn with_positions(mut self, enabled: bool) -> Self {
588        self.positions = enabled;
589        self
590    }
591
592    /// Register an extension after those already present.
593    pub fn with_extension(mut self, extension: &'a dyn CarveExtension) -> Self {
594        self.extensions.push(extension);
595        self
596    }
597
598    /// Set the fallback URL template for mentions.
599    pub fn with_mention_url(mut self, template: impl Into<String>) -> Self {
600        self.mention_url = Some(template.into());
601        self
602    }
603
604    /// Set the fallback URL template for tags.
605    pub fn with_tag_url(mut self, template: impl Into<String>) -> Self {
606        self.tag_url = Some(template.into());
607        self
608    }
609
610    /// Use a host callback to resolve mention destinations.
611    pub fn with_mention_resolver(mut self, resolver: &'a SocialLinkResolver<'a>) -> Self {
612        self.mention_resolver = Some(resolver);
613        self
614    }
615
616    /// Use a host callback to resolve tag destinations.
617    pub fn with_tag_resolver(mut self, resolver: &'a SocialLinkResolver<'a>) -> Self {
618        self.tag_resolver = Some(resolver);
619        self
620    }
621
622    /// Pass host data to social-link resolvers.
623    pub fn with_social_context(mut self, context: &'a dyn Any) -> Self {
624        self.social_context = Some(context);
625        self
626    }
627
628    /// Add an HTML-only shortcode replacement.
629    pub fn with_symbol(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
630        self.symbols.insert(name.into(), value.into());
631        self
632    }
633
634    /// The engine-written string for `key`, or its English default.
635    pub fn label(&self, key: &str) -> &str {
636        self.labels
637            .get(key)
638            .map(String::as_str)
639            .unwrap_or_else(|| label_default(key))
640    }
641
642    /// Override one of the strings the engine writes itself (PART 9 §16a).
643    ///
644    /// ```
645    /// # use carve::Options;
646    /// let opts = Options::new().with_label("footnoteBacklink", "Zurück zur Fußnote");
647    /// ```
648    pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
649        self.labels.insert(key.into(), value.into());
650        self
651    }
652
653    /// Opt in to lowercasing auto-generated heading ids (default is
654    /// case-preserving). See [`Options::lowercase_heading_ids`].
655    pub fn with_lowercase_heading_ids(mut self, lowercase: bool) -> Self {
656        self.lowercase_heading_ids = lowercase;
657        self
658    }
659
660    /// Opt in to ASCII-folding auto-generated heading ids. See
661    /// [`AsciiHeadingIds`] for what each mode does with a code point the
662    /// transliteration table does not cover.
663    pub fn with_ascii_heading_ids(mut self, ascii: AsciiHeadingIds) -> Self {
664        self.ascii_heading_ids = ascii;
665        self
666    }
667
668    /// The heading-id transforms this `Options` asks for, as the one value the
669    /// slug function takes. Threading the two flags separately is how a call
670    /// site ends up applying one and not the other.
671    pub(crate) fn heading_id_options(&self) -> HeadingIdOptions {
672        HeadingIdOptions {
673            lowercase: self.lowercase_heading_ids,
674            ascii: self.ascii_heading_ids,
675        }
676    }
677
678    /// Apply a feature-restriction [`Profile`] before rendering.
679    pub fn with_profile(mut self, profile: Profile) -> Self {
680        self.profile = Some(profile);
681        self
682    }
683
684    /// Set the base host for the profile's link policy (internal/external
685    /// link detection).
686    pub fn with_profile_base_host(mut self, host: impl Into<String>) -> Self {
687        self.profile_base_host = Some(host.into());
688        self
689    }
690
691    /// Set the render [`Mode`]. Omitting it leaves [`Mode::Interactive`]
692    /// (the default). [`Mode::Static`] only affects the HTML renderer; the
693    /// Markdown / plain-text / ANSI renderers are inherently static.
694    pub fn with_mode(mut self, mode: Mode) -> Self {
695        self.mode = mode;
696        self
697    }
698
699    /// Supply the [`StaticRenderers`] map for an HTML [`Mode::Static`] render
700    /// (build-time mermaid / chart / math renderers). Without a renderer the
701    /// matching static path degrades to source, never blank.
702    pub fn with_renderers(mut self, renderers: StaticRenderers) -> Self {
703        self.renderers = renderers;
704        self
705    }
706
707    /// True when this render is in HTML static mode.
708    pub(crate) fn is_static(&self) -> bool {
709        self.mode == Mode::Static
710    }
711}
712
713/// Hooks for recognizing, transforming, and rendering extension nodes.
714pub trait CarveExtension {
715    /// Stable name used to identify the extension.
716    fn name(&self) -> &'static str;
717
718    /// Semantic span attribute names this extension adds (spec PART 9 §10).
719    ///
720    /// DECLARATIVE ON PURPOSE. The nesting order, the value mapping and §9's
721    /// riding rule live in ONE renderer; an extension that re-implemented them
722    /// for its own names would be a second copy of the feature, drifting from
723    /// core the first time either side changed. So an extension names what it
724    /// claims and core renders it.
725    fn semantic_span_names(&self) -> &'static [&'static str] {
726        &[]
727    }
728
729    /// The [`StaticRenderers::diagram`] key this extension is consulted under,
730    /// when it has one. `None` for everything that is not a fenced-render
731    /// preset.
732    ///
733    /// `name()` cannot answer it: every preset answers `fenced-render`, so a
734    /// binding validating a caller's `renderers.diagrams` keys would otherwise
735    /// keep a list of its own.
736    fn diagram_key(&self) -> Option<&str> {
737        None
738    }
739
740    /// Match an inline construct beginning at `pos` in `text`.
741    fn match_inline(
742        &self,
743        _text: &str,
744        _pos: usize,
745        _ctx: &MatcherContext<'_>,
746    ) -> Option<InlineMatch> {
747        None
748    }
749
750    /// Match a block construct beginning at `start` in `lines`.
751    fn match_block(
752        &self,
753        _lines: &[&str],
754        _start: usize,
755        _ctx: &MatcherContext<'_>,
756    ) -> Option<BlockMatch> {
757        None
758    }
759
760    /// Rewrite the parsed document before render preparation.
761    fn after_parse(&self, doc: Document) -> Document {
762        doc
763    }
764
765    /// `beforeRender` transform. Receives a [`BeforeRenderContext`] carrying the
766    /// render [`Options`] AND the *effective* [`Mode`] for the actual target
767    /// format. An extension that emits its final HTML here (the carve-rs
768    /// transform model for `FencedRender` / `MathBlock`) branches on
769    /// `ctx.mode()` / `ctx.is_static()` and consults `ctx.options.renderers`.
770    ///
771    /// The effective mode is `Interactive` for the Markdown / plain-text / ANSI
772    /// renderers regardless of `Options::mode` - static rendering is an
773    /// HTML-only concern (those renderers reach the same end by flattening), so
774    /// a caller reusing one `Options` across formats gets unchanged non-HTML
775    /// output. Most extensions ignore this hook entirely.
776    fn before_render(&self, doc: Document, _ctx: &BeforeRenderContext<'_>) -> Document {
777        doc
778    }
779
780    /// Render an inline extension node as HTML, if this extension owns it.
781    fn render_inline_extension(
782        &self,
783        _node: &InlineExtension,
784        _ctx: &RenderContext<'_>,
785    ) -> Option<String> {
786        None
787    }
788
789    /// Render a block carrier left by a render-stage transform.
790    fn render_extension_carrier(
791        &self,
792        _node: &ExtensionCarrier,
793        _ctx: &RenderContext<'_>,
794    ) -> Option<String> {
795        None
796    }
797
798    /// Does this extension's carrier anchor its element at column 0 whatever the
799    /// nesting, rather than at the ambient block indentation?
800    ///
801    /// CARVE-P10-010 allows either, but ONE COLUMN SERVES BOTH TAGS. A column-0
802    /// fragment writes its own closer at 0, so the caller's first-line indent
803    /// would put only the opener a level deeper and the element would conform
804    /// under neither choice (carve-rs#1969). Ambient-anchored renderers, which
805    /// are all the others, leave this alone.
806    fn carrier_anchored_at_column_zero(&self, _node: &ExtensionCarrier) -> bool {
807        false
808    }
809}
810
811/// Context handed to [`CarveExtension::before_render`]. Carries the render
812/// [`Options`] and the *effective* [`Mode`] for the target format - which is
813/// always [`Mode::Interactive`] for the non-HTML renderers, so static rendering
814/// stays an HTML-only concern even when a single `Options` is reused across
815/// formats.
816pub struct BeforeRenderContext<'a> {
817    options: &'a Options<'a>,
818    effective_mode: Mode,
819    target_is_html: bool,
820}
821
822impl<'a> BeforeRenderContext<'a> {
823    pub(crate) fn new(
824        options: &'a Options<'a>,
825        effective_mode: Mode,
826        target_is_html: bool,
827    ) -> Self {
828        Self {
829            options,
830            effective_mode,
831            target_is_html,
832        }
833    }
834
835    /// The render options.
836    pub fn options(&self) -> &Options<'a> {
837        self.options
838    }
839
840    /// The effective render [`Mode`] for the target format.
841    pub fn mode(&self) -> Mode {
842        self.effective_mode
843    }
844
845    /// True when the effective mode is [`Mode::Static`] (HTML static path).
846    pub fn is_static(&self) -> bool {
847        self.effective_mode == Mode::Static
848    }
849
850    /// True when the final render target is HTML. The Markdown / plain / ANSI
851    /// renderers set this `false`, so an extension that emits HTML in
852    /// `before_render` (e.g. a client-script hydration element) can skip its
853    /// transform and leave the source node for the non-HTML renderer to emit as
854    /// source.
855    pub fn target_is_html(&self) -> bool {
856        self.target_is_html
857    }
858
859    /// The build-time [`StaticRenderers`] map (shorthand for
860    /// `self.options().renderers`).
861    pub fn renderers(&self) -> &StaticRenderers {
862        &self.options.renderers
863    }
864}
865
866/// Inline node and endpoint returned by an extension matcher.
867pub struct InlineMatch {
868    /// Matched node.
869    pub node: InlineNode,
870    /// Exclusive end byte offset in the matched text.
871    pub end: usize,
872}
873
874/// Block node and line count returned by an extension matcher.
875pub struct BlockMatch {
876    /// Matched node.
877    pub node: BlockNode,
878    /// Number of input lines consumed.
879    pub lines_consumed: usize,
880}
881
882/// Parser access supplied to an extension matcher.
883pub struct MatcherContext<'a> {
884    options: &'a Options<'a>,
885    citation_brackets: Option<(&'a str, &'a std::cell::OnceCell<HashMap<usize, usize>>)>,
886}
887
888impl<'a> MatcherContext<'a> {
889    pub(crate) fn new(options: &'a Options<'a>) -> Self {
890        Self {
891            options,
892            citation_brackets: None,
893        }
894    }
895
896    pub(crate) fn for_inline(
897        options: &'a Options<'a>,
898        text: &'a str,
899        brackets: &'a std::cell::OnceCell<HashMap<usize, usize>>,
900    ) -> Self {
901        Self {
902            options,
903            citation_brackets: Some((text, brackets)),
904        }
905    }
906
907    pub(crate) fn citation_close_bracket(&self, text: &str, open: usize) -> Option<usize> {
908        if let Some((source, cache)) = self.citation_brackets {
909            if source.as_ptr() == text.as_ptr() && source.len() == text.len() {
910                if let Some(pairs) = cache.get() {
911                    return pairs.get(&open).copied();
912                }
913                // Short balanced citations need no map. Limit this scan so
914                // repeated unclosed or deeply nested openers remain bounded.
915                const SHORT_SCAN_BYTES: usize = 64;
916                if let Some(close) = crate::citations::close_bracket(text, open, SHORT_SCAN_BYTES) {
917                    return Some(close);
918                }
919                if text.len().saturating_sub(open) <= SHORT_SCAN_BYTES {
920                    return None;
921                }
922                return cache
923                    .get_or_init(|| crate::citations::bracket_pairs(text))
924                    .get(&open)
925                    .copied();
926            }
927        }
928        crate::citations::close_bracket(text, open, usize::MAX)
929    }
930
931    /// Parse inline content with the active options.
932    pub fn parse_inlines(&self, text: &str) -> Vec<InlineNode> {
933        parse_matcher_inlines(text, self.options)
934    }
935
936    /// Parse blocks with the active options.
937    pub fn parse_blocks(&self, source: &str) -> Vec<BlockNode> {
938        parse_blocks_with_options(source, self.options)
939    }
940}
941
942/// Rendering helpers and settings supplied to extension hooks.
943pub struct RenderContext<'a> {
944    pub(crate) options: &'a Options<'a>,
945    /// Indentation level of the node currently being rendered. Zero on the
946    /// inline path (inline extensions never indent); set to the block node's
947    /// level when a block extension is rendered, so a block-extension renderer
948    /// can emit nesting-aware indentation (mirrors carve-js
949    /// `BlockExtensionRenderContext.level`).
950    level: usize,
951    /// The live document render state (heading-id counter) when rendering a
952    /// block extension, so nested rendering continues the document's heading
953    /// numbering and depth budget across the extension boundary. `None` on the
954    /// inline path.
955    state: Option<&'a std::cell::RefCell<&'a mut crate::render::RenderState>>,
956}
957
958/// Drop one `pad` from the first line of a placed extension's HTML.
959///
960/// `render_extension_carrier` indents that line itself, so a renderer whose
961/// parts all self-indent - which is what every line after the first needs -
962/// would otherwise put its first line one level too deep.
963pub(crate) fn unpad_first_line(html: String, pad: &str) -> String {
964    if pad.is_empty() {
965        return html;
966    }
967    match html.strip_prefix(pad) {
968        Some(rest) => rest.to_string(),
969        None => html,
970    }
971}
972
973pub(crate) fn directive_tokens(
974    node: &crate::ast::ExtensionCarrier,
975    ctx: &RenderContext<'_>,
976    level: usize,
977    title_id: Option<&str>,
978) -> Vec<String> {
979    let mut tokens = Vec::new();
980    let pad = ctx.indent(level);
981    if let Some(title) = &node.summary {
982        let id = title_id
983            .map(|id| format!(" id=\"{}\"", escape_attr(id)))
984            .unwrap_or_default();
985        tokens.push(format!(
986            "{pad}<p class=\"admonition-title\"{id}>{}</p>",
987            ctx.render_inlines(title)
988        ));
989    }
990    if let Some(label) = &node.label {
991        tokens.push(format!(
992            "{pad}<p class=\"div-label\">{}</p>",
993            crate::render::render_container_label(label, ctx.options)
994        ));
995    }
996    tokens
997}
998
999impl<'a> RenderContext<'a> {
1000    pub(crate) fn new(options: &'a Options<'a>) -> Self {
1001        Self {
1002            options,
1003            level: 0,
1004            state: None,
1005        }
1006    }
1007
1008    pub(crate) fn with_level_and_state(
1009        options: &'a Options<'a>,
1010        level: usize,
1011        state: &'a std::cell::RefCell<&'a mut crate::render::RenderState>,
1012    ) -> Self {
1013        Self {
1014            options,
1015            level,
1016            state: Some(state),
1017        }
1018    }
1019
1020    /// Render an inline run with the active options.
1021    pub fn render_inlines(&self, nodes: &[InlineNode]) -> String {
1022        crate::render::render_inlines_with_options(nodes, self.options)
1023    }
1024
1025    /// A container label's inline run, rendered - what an extension writing its
1026    /// own `<p class="div-label">` puts inside it. Escaping the label instead
1027    /// published the author's characters where the core floor publishes a run.
1028    pub fn render_container_label(&self, label: &str) -> String {
1029        crate::render::render_container_label(label, self.options)
1030    }
1031
1032    /// [`RenderContext::render_inlines`], for nodes the caller is about to place
1033    /// inside an anchor of its own. A construct that would open its own anchor
1034    /// renders its non-anchor form instead (PART 12 section 3a, LINKS NEVER
1035    /// NEST) - what a table-of-contents entry needs, since the entry is written
1036    /// into an `<a href="#id">` the extension emits.
1037    pub fn render_inlines_inside_anchor(&self, nodes: &[InlineNode]) -> String {
1038        crate::render::render_inlines_inside_anchor(nodes, self.options)
1039    }
1040
1041    /// Render block nodes at level 0 (no leading indentation), while preserving
1042    /// the current recursion depth when called by a block extension. Use
1043    /// [`RenderContext::render_blocks_at`] to render at a specific indentation
1044    /// level.
1045    pub fn render_blocks(&self, nodes: &[BlockNode]) -> String {
1046        match self.state {
1047            Some(cell) => {
1048                let mut state = cell.borrow_mut();
1049                crate::render::render_blocks_with_state_from_depth(
1050                    nodes,
1051                    self.options,
1052                    self.level.saturating_add(1),
1053                    &mut state,
1054                )
1055            }
1056            None => crate::render::render_blocks_with_options(nodes, self.options),
1057        }
1058    }
1059
1060    /// Render block nodes indented to `level`, matching the core renderer's
1061    /// two-space-per-level layout. A block-extension renderer uses this to
1062    /// place its children at `ctx.level() + 1` so a details/disclosure block
1063    /// nests identically wherever it sits (top level, list item, blockquote).
1064    /// When this context carries the live document state, the heading-id
1065    /// counter continues across the extension boundary (a duplicate slug gets
1066    /// its numeric suffix); otherwise it falls back to a fresh counter.
1067    pub fn render_blocks_at(&self, nodes: &[BlockNode], level: usize) -> String {
1068        match self.state {
1069            Some(cell) => {
1070                let mut state = cell.borrow_mut();
1071                crate::render::render_blocks_at_with_state(nodes, self.options, level, &mut state)
1072            }
1073            None => crate::render::render_blocks_at_with_options(nodes, self.options, level),
1074        }
1075    }
1076
1077    /// The indentation level of the block node being rendered. Zero on the
1078    /// inline path.
1079    /// The engine-written string for `key`, with the host's `labels` override
1080    /// applied, else its English default (PART 9 §16a).
1081    ///
1082    /// An extension reads its own key from here so ONE `labels` map localizes
1083    /// the whole document; an option set on the extension still wins for that
1084    /// instance.
1085    pub fn label(&self, key: &str) -> String {
1086        self.options
1087            .labels
1088            .get(key)
1089            .cloned()
1090            .unwrap_or_else(|| label_default(key).to_string())
1091    }
1092
1093    /// Current block indentation level.
1094    pub fn level(&self) -> usize {
1095        self.level
1096    }
1097
1098    /// The two-space-per-level indent string for `level`.
1099    pub fn indent(&self, level: usize) -> String {
1100        "  ".repeat(level)
1101    }
1102
1103    /// The active render [`Mode`]. A block-extension renderer branches on this
1104    /// to emit its static (flattened, no-interaction) form.
1105    pub fn mode(&self) -> Mode {
1106        self.options.mode
1107    }
1108
1109    /// True when this render is in HTML static mode.
1110    pub fn is_static(&self) -> bool {
1111        self.options.is_static()
1112    }
1113
1114    /// The build-time [`StaticRenderers`] map for this render. Used by a
1115    /// client-script extension's static path to server-render mermaid / chart /
1116    /// math, falling back to source when the needed renderer is absent.
1117    pub fn renderers(&self) -> &StaticRenderers {
1118        &self.options.renderers
1119    }
1120
1121    /// Reserve a DOM id in the shared per-render document id namespace (see
1122    /// the [extensions contract](https://markup-carve.github.io/carve/extensions)
1123    /// §2.6 "Generated ids"): returns `base_id` when the name is free, else
1124    /// the next free numeric suffix (`base_id-2`, `-3`, ...), never colliding
1125    /// with an explicit `{#id}` attribute, a generated heading id, or a
1126    /// previously generated id. The namespace is seeded from the whole
1127    /// document before rendering starts, so first-in-source wins. Outside an
1128    /// active HTML render the base id is returned unchanged.
1129    pub fn unique_id(&self, base_id: &str) -> String {
1130        crate::document_ids::unique_id(base_id)
1131    }
1132
1133    pub(crate) fn mint_admonition_id(&self) -> String {
1134        self.state
1135            .expect("block extension render state")
1136            .borrow_mut()
1137            .mint_admonition_id()
1138    }
1139
1140    /// Escape text for an HTML element body.
1141    pub fn escape_html(&self, input: &str) -> String {
1142        escape_text(input)
1143    }
1144
1145    /// Escape text for an HTML attribute value.
1146    pub fn escape_attr(&self, input: &str) -> String {
1147        escape_attr(input)
1148    }
1149}