ctb_formats_markdown/
markdown.rs1#[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
42pub 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 markdown::to_html_with_options(&replaced, &get_markdown_options(false))
51 .unwrap_or_default()
52}
53
54pub 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 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 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 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}