ctb_formats_markdown/
markdown.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Markdown parsing and HTML rendering utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use ctb_utilities::anyhow::anyhow;
30use markdown::Options;
31
32fn get_markdown_options(allow_dangerous_html: bool) -> Options {
33    let mut options = Options::default();
34    options.parse.constructs.gfm_table = true;
35    options.parse.constructs.gfm_strikethrough = true;
36    options.parse.constructs.gfm_footnote_definition = true;
37    options.parse.constructs.gfm_label_start_footnote = true;
38    options.compile.allow_dangerous_html = allow_dangerous_html;
39    options
40}
41
42/// Embedded HTML will be broken by this function.
43pub fn markdown2html(markdown: Vec<u8>) -> Vec<u8> {
44    markdown2html_str(&String::from_utf8_lossy(&markdown)).into_bytes()
45}
46
47pub fn markdown2html_str(markdown: &str) -> String {
48    let replaced = branding::replace_magic_strings(markdown);
49    // Reason for fallback: markdown parser returns default empty string if HTML compilation produces an error.
50    markdown::to_html_with_options(&replaced, &get_markdown_options(false))
51        .unwrap_or_default()
52}
53
54/// Allows Embedded HTML, which can cause security issues. Use only for trusted markdown content.
55pub fn markdown2html_unsafe(markdown: Vec<u8>) -> Result<Vec<u8>> {
56    Ok(
57        markdown2html_str_unsafe(&String::from_utf8_lossy(&markdown))?
58            .into_bytes(),
59    )
60}
61
62pub fn markdown2html_str_unsafe(markdown: &str) -> Result<String> {
63    let replaced = branding::replace_magic_strings(markdown);
64    markdown::to_html_with_options(&replaced, &get_markdown_options(true))
65        .map_err(|e| anyhow!("Failed to convert markdown to HTML: {e}"))
66}
67
68#[cfg(test)]
69#[allow(
70    clippy::panic,
71    clippy::expect_used,
72    clippy::unwrap_used,
73    clippy::unwrap_in_result,
74    clippy::panic_in_result_fn,
75    clippy::indexing_slicing,
76    clippy::arithmetic_side_effects,
77    reason = "Standard repository test boilerplate"
78)]
79mod tests {
80    use super::*;
81
82    #[crate::ctb_test]
83    fn test_markdown_gfm_features() {
84        // Test Table
85        let table_md = "| Head 1 | Head 2 |\n|---|---|\n| Cell 1 | Cell 2 |";
86        let table_html = markdown2html_str(table_md);
87        assert!(table_html.contains("<table>"));
88        assert!(table_html.contains("<th>Head 1</th>"));
89        assert!(table_html.contains("<td>Cell 1</td>"));
90
91        // Test Strikethrough (both single and double tildes are supported by GFM)
92        let strikethrough_md = "~strike~ and ~~double strike~~";
93        let strikethrough_html = markdown2html_str(strikethrough_md);
94        assert!(strikethrough_html.contains("<del>strike</del>"));
95        assert!(strikethrough_html.contains("<del>double strike</del>"));
96
97        // Test Footnotes
98        let footnote_md = "Here is a footnote[^1].\n\n[^1]: Footnote content.";
99        let footnote_html = markdown2html_str(footnote_md);
100        assert!(footnote_html.contains("<sup"));
101        assert!(footnote_html.contains("data-footnote-ref"));
102        assert!(footnote_html.contains("class=\"footnotes\""));
103        assert!(footnote_html.contains("Footnote content."));
104    }
105}