Skip to main content

markdown2html_converter/
options.rs

1use std::{
2    fmt::{self, Display, Formatter},
3    path::Path,
4    str::FromStr,
5};
6
7/// The color theme of the output HTML.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum Theme {
10    /// Follow the `prefers-color-scheme` media feature.
11    #[default]
12    Auto,
13    /// Always use the light theme.
14    Light,
15    /// Always use the dark theme.
16    Dark,
17}
18
19impl Theme {
20    /// The value of the `data-theme` attribute of the `<html>` element, if the theme is fixed.
21    #[inline]
22    pub const fn attribute_value(self) -> Option<&'static str> {
23        match self {
24            Self::Auto => None,
25            Self::Light => Some("light"),
26            Self::Dark => Some("dark"),
27        }
28    }
29}
30
31impl Display for Theme {
32    #[inline]
33    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
34        f.write_str(match self {
35            Self::Auto => "auto",
36            Self::Light => "light",
37            Self::Dark => "dark",
38        })
39    }
40}
41
42impl FromStr for Theme {
43    type Err = UnknownTheme;
44
45    #[inline]
46    fn from_str(s: &str) -> Result<Self, Self::Err> {
47        match s {
48            "auto" => Ok(Self::Auto),
49            "light" => Ok(Self::Light),
50            "dark" => Ok(Self::Dark),
51            _ => Err(UnknownTheme),
52        }
53    }
54}
55
56/// The error of parsing a [`Theme`] from a string.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct UnknownTheme;
59
60impl Display for UnknownTheme {
61    #[inline]
62    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
63        f.write_str("the theme should be one of `auto`, `light` and `dark`")
64    }
65}
66
67impl std::error::Error for UnknownTheme {}
68
69/// How the math in a Markdown file is rendered.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71pub enum MathMode {
72    /// Embed the **MathJax** bundle; extra fonts and TeX extensions may still need the network.
73    MathJaxEmbedded,
74    /// Load **MathJax** from a CDN.
75    MathJaxClient,
76    /// Embed the whole **KaTeX** bundle, its fonts included.
77    KatexEmbedded,
78    /// Load **KaTeX** from a CDN.
79    #[default]
80    KatexClient,
81}
82
83impl MathMode {
84    /// Whether this mode renders the math with **KaTeX**.
85    #[inline]
86    pub const fn is_katex(self) -> bool {
87        matches!(self, Self::KatexEmbedded | Self::KatexClient)
88    }
89}
90
91impl Display for MathMode {
92    #[inline]
93    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
94        f.write_str(match self {
95            Self::MathJaxEmbedded => "mathjax-embedded",
96            Self::MathJaxClient => "mathjax-client",
97            Self::KatexEmbedded => "katex-embedded",
98            Self::KatexClient => "katex-client",
99        })
100    }
101}
102
103impl FromStr for MathMode {
104    type Err = UnknownMathMode;
105
106    #[inline]
107    fn from_str(s: &str) -> Result<Self, Self::Err> {
108        match s {
109            "mathjax-embedded" => Ok(Self::MathJaxEmbedded),
110            "mathjax-client" => Ok(Self::MathJaxClient),
111            "katex-embedded" => Ok(Self::KatexEmbedded),
112            "katex-client" => Ok(Self::KatexClient),
113            _ => Err(UnknownMathMode),
114        }
115    }
116}
117
118/// The error of parsing a [`MathMode`] from a string.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub struct UnknownMathMode;
121
122impl Display for UnknownMathMode {
123    #[inline]
124    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
125        f.write_str(
126            "the math mode should be one of `mathjax-embedded`, `mathjax-client`, \
127             `katex-embedded` and `katex-client`",
128        )
129    }
130}
131
132impl std::error::Error for UnknownMathMode {}
133
134/// How the **Mermaid** diagrams in a Markdown file are rendered.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
136pub enum MermaidMode {
137    /// Embed the whole **Mermaid** bundle.
138    Embedded,
139    /// Load **Mermaid** from a CDN.
140    #[default]
141    Client,
142}
143
144impl Display for MermaidMode {
145    #[inline]
146    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
147        f.write_str(match self {
148            Self::Embedded => "embedded",
149            Self::Client => "client",
150        })
151    }
152}
153
154impl FromStr for MermaidMode {
155    type Err = UnknownMermaidMode;
156
157    #[inline]
158    fn from_str(s: &str) -> Result<Self, Self::Err> {
159        match s {
160            "embedded" => Ok(Self::Embedded),
161            "client" => Ok(Self::Client),
162            _ => Err(UnknownMermaidMode),
163        }
164    }
165}
166
167/// The error of parsing a [`MermaidMode`] from a string.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct UnknownMermaidMode;
170
171impl Display for UnknownMermaidMode {
172    #[inline]
173    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
174        f.write_str("the Mermaid mode should be either `embedded` or `client`")
175    }
176}
177
178impl std::error::Error for UnknownMermaidMode {}
179
180/// Which code block languages make **highlight.js** be embedded. Languages are matched case-insensitively.
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
182pub enum HighlightLanguages<'a> {
183    /// The languages which the built-in **highlight.js** supports.
184    #[default]
185    BuiltIn,
186    /// Every language.
187    Any,
188    /// Only the given languages.
189    Only(&'a [&'a str]),
190}
191
192/// Options for [`convert`](crate::convert).
193#[derive(Debug, Clone)]
194pub struct ConvertOptions<'a> {
195    /// The title of the HTML file. When it is `None`, the title is looked up in the front matter and then in the first level-1 heading.
196    pub title:               Option<&'a str>,
197    /// The title to use when no title can be found in the Markdown file.
198    pub default_title:       Option<&'a str>,
199    /// The `lang` attribute of the `<html>` element. An empty string omits the attribute.
200    pub lang:                &'a str,
201    /// The color theme.
202    pub theme:               Theme,
203    /// Allow raw HTML and dangerous URLs.
204    pub allow_unsafe:        bool,
205    /// Treat a single line break as a `<br>`.
206    pub hardbreaks:          bool,
207    /// Embed **highlight.js** when the Markdown file has code blocks with a supported language.
208    pub highlight:           bool,
209    /// Which code block languages make **highlight.js** be embedded.
210    pub highlight_languages: HighlightLanguages<'a>,
211    /// How the math is rendered. `None` leaves the math alone.
212    pub math:                Option<MathMode>,
213    /// How the **Mermaid** diagrams are rendered. `None` leaves a ```` ```mermaid ```` block as a code block.
214    pub mermaid:             Option<MermaidMode>,
215    /// Embed the CJK fonts.
216    pub cjk_fonts:           bool,
217    /// Minify the output HTML.
218    pub minify:              bool,
219    /// Embed local images as `data` URLs.
220    pub embed_images:        bool,
221    /// The directory that relative paths in the Markdown file are resolved against.
222    pub base_path:           Option<&'a Path>,
223    /// A stylesheet which replaces the built-in one.
224    pub css:                 Option<&'a str>,
225    /// A stylesheet which is appended after all the other stylesheets.
226    pub extra_css:           Option<&'a str>,
227    /// A script which replaces the built-in **highlight.js**.
228    pub highlight_js:        Option<&'a str>,
229    /// A stylesheet which replaces the built-in **highlight.js** theme.
230    pub highlight_css:       Option<&'a str>,
231    /// A script which replaces the built-in **MathJax**.
232    pub mathjax_js:          Option<&'a str>,
233    /// A script which replaces the built-in **KaTeX**.
234    pub katex_js:            Option<&'a str>,
235    /// A stylesheet which replaces the built-in **KaTeX** one.
236    pub katex_css:           Option<&'a str>,
237    /// A script which replaces the built-in **Mermaid**.
238    pub mermaid_js:          Option<&'a str>,
239}
240
241impl Default for ConvertOptions<'_> {
242    #[inline]
243    fn default() -> Self {
244        Self {
245            title:               None,
246            default_title:       None,
247            lang:                "en",
248            theme:               Theme::default(),
249            allow_unsafe:        false,
250            hardbreaks:          true,
251            highlight:           true,
252            highlight_languages: HighlightLanguages::default(),
253            math:                Some(MathMode::default()),
254            mermaid:             Some(MermaidMode::default()),
255            cjk_fonts:           true,
256            minify:              true,
257            embed_images:        false,
258            base_path:           None,
259            css:                 None,
260            extra_css:           None,
261            highlight_js:        None,
262            highlight_css:       None,
263            mathjax_js:          None,
264            katex_js:            None,
265            katex_css:           None,
266            mermaid_js:          None,
267        }
268    }
269}