comrak/
adapters.rs

1//! Adapter traits for plugins.
2//!
3//! Each plugin has to implement one of the traits available in this module.
4
5use std::collections::HashMap;
6use std::io::{self, Write};
7
8use crate::nodes::Sourcepos;
9
10/// Implement this adapter for creating a plugin for custom syntax highlighting of codefence blocks.
11pub trait SyntaxHighlighterAdapter: Send + Sync {
12    /// Generates a syntax highlighted HTML output.
13    ///
14    /// lang: Name of the programming language (the info string of the codefence block after the initial "```" part).
15    /// code: The source code to be syntax highlighted.
16    fn write_highlighted(
17        &self,
18        output: &mut dyn Write,
19        lang: Option<&str>,
20        code: &str,
21    ) -> io::Result<()>;
22
23    /// Generates the opening `<pre>` tag. Some syntax highlighter libraries might include their own
24    /// `<pre>` tag possibly with some HTML attribute pre-filled.
25    ///
26    /// `attributes`: A map of HTML attributes provided by comrak.
27    fn write_pre_tag(
28        &self,
29        output: &mut dyn Write,
30        attributes: HashMap<String, String>,
31    ) -> io::Result<()>;
32
33    /// Generates the opening `<code>` tag. Some syntax highlighter libraries might include their own
34    /// `<code>` tag possibly with some HTML attribute pre-filled.
35    ///
36    /// `attributes`: A map of HTML attributes provided by comrak.
37    fn write_code_tag(
38        &self,
39        output: &mut dyn Write,
40        attributes: HashMap<String, String>,
41    ) -> io::Result<()>;
42}
43
44/// The struct passed to the [`HeadingAdapter`] for custom heading implementations.
45#[derive(Clone, Debug)]
46pub struct HeadingMeta {
47    /// The level of the heading; from 1 to 6 for ATX headings, 1 or 2 for setext headings.
48    pub level: u8,
49
50    /// The content of the heading as a "flattened" string&mdash;flattened in the sense that any
51    /// `<strong>` or other tags are removed. In the Markdown heading `## This is **bold**`, for
52    /// example, the would be the string `"This is bold"`.
53    pub content: String,
54}
55
56/// Implement this adapter for creating a plugin for custom headings (`h1`, `h2`, etc.). The `enter`
57/// method defines what's rendered prior the AST content of the heading while the `exit` method
58/// defines what's rendered after it. Both methods provide access to a [`HeadingMeta`] struct and
59/// leave the AST content of the heading unchanged.
60pub trait HeadingAdapter: Send + Sync {
61    /// Render the opening tag.
62    fn enter(
63        &self,
64        output: &mut dyn Write,
65        heading: &HeadingMeta,
66        sourcepos: Option<Sourcepos>,
67    ) -> io::Result<()>;
68
69    /// Render the closing tag.
70    fn exit(&self, output: &mut dyn Write, heading: &HeadingMeta) -> io::Result<()>;
71}