1use crate::error::DocsError;
7use crate::island::Island;
8use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
9use std::fmt::Write as _;
10
11pub fn render(markdown: &str, base: &str) -> Result<String, DocsError> {
18 render_inner(markdown, base, true)
19}
20
21pub(crate) fn render_inner(
25 markdown: &str,
26 base: &str,
27 allow_islands: bool,
28) -> Result<String, DocsError> {
29 let mut options = Options::empty();
30 options.insert(Options::ENABLE_TABLES);
31 options.insert(Options::ENABLE_STRIKETHROUGH);
32 options.insert(Options::ENABLE_TASKLISTS);
33 options.insert(Options::ENABLE_FOOTNOTES);
34 options.insert(Options::ENABLE_MATH);
37
38 let mut out = String::new();
39 let mut headings: Vec<u8> = Vec::new();
40 let mut list_stack: Vec<bool> = Vec::new();
44 let mut in_code_block = false;
45 let mut parser = Parser::new_ext(markdown, options);
46
47 while let Some(event) = parser.next() {
48 match event {
49 Event::Start(Tag::Heading { level, .. }) => {
50 headings.push(level as u8);
52 let _ = write!(out, "<{level}>");
53 }
54 Event::End(TagEnd::Heading(_)) => {
55 let level = headings.pop().unwrap_or(1);
56 let _ = write!(out, "</h{level}>");
57 }
58 Event::Start(Tag::Paragraph) => {
59 if list_stack.is_empty() {
60 out.push_str("<p>");
61 }
62 }
63 Event::End(TagEnd::Paragraph) => {
64 if list_stack.is_empty() {
65 out.push_str("</p>");
66 }
67 }
68 Event::Start(Tag::Emphasis) => out.push_str("<em>"),
69 Event::End(TagEnd::Emphasis) => out.push_str("</em>"),
70 Event::Start(Tag::Strong) => out.push_str("<strong>"),
71 Event::End(TagEnd::Strong) => out.push_str("</strong>"),
72 Event::Start(Tag::Strikethrough) => out.push_str("<del>"),
73 Event::End(TagEnd::Strikethrough) => out.push_str("</del>"),
74 Event::Code(code) => {
75 let _ = write!(out, "<code>{}</code>", escape_html(&code));
76 }
77 Event::Start(Tag::Link { dest_url, .. }) => {
78 let _ = write!(out, "<a href=\"{}\">", escape_attr(&dest_url));
79 }
80 Event::End(TagEnd::Link) => out.push_str("</a>"),
81 Event::Start(Tag::Image {
82 dest_url, title, ..
83 }) => {
84 let mut alt = String::new();
88 for inner in parser.by_ref() {
89 match inner {
90 Event::Text(t) => alt.push_str(&t),
91 Event::End(TagEnd::Image) => break,
92 _ => {}
93 }
94 }
95 let _ = write!(
96 out,
97 "<img src=\"{}\" alt=\"{}\"{}>",
98 escape_attr(&dest_url),
99 escape_attr(&alt),
100 if title.is_empty() {
101 String::new()
102 } else {
103 format!(" title=\"{}\"", escape_attr(&title))
104 }
105 );
106 }
107 Event::End(TagEnd::Image) => {}
108 Event::Start(Tag::BlockQuote(_)) => out.push_str("<blockquote>"),
109 Event::End(TagEnd::BlockQuote(_)) => out.push_str("</blockquote>"),
110 Event::Start(Tag::CodeBlock(kind)) => match kind {
111 CodeBlockKind::Fenced(info) if info.starts_with("island") => {
112 let mut body = String::new();
116 for inner in parser.by_ref() {
117 match inner {
118 Event::Text(t) => {
119 body.push_str(&t);
120 break;
121 }
122 Event::End(TagEnd::CodeBlock) => break,
123 _ => {}
124 }
125 }
126 if allow_islands {
127 let island = Island::parse(&info, &body)?;
128 out.push_str(&island.to_html(base));
129 }
130 let _ = parser.next(); }
134 _ => {
135 in_code_block = true;
136 out.push_str("<pre><code>");
137 }
138 },
139 Event::End(TagEnd::CodeBlock) => {
140 if in_code_block {
141 in_code_block = false;
142 out.push_str("</code></pre>");
143 }
144 }
145 Event::Start(Tag::List(start)) => {
146 let ordered = start.is_some();
147 let _ = write!(out, "<{}>", if ordered { "ol" } else { "ul" });
148 list_stack.push(ordered);
149 }
150 Event::End(TagEnd::List(_)) => {
151 match list_stack.pop() {
155 Some(true) => out.push_str("</ol>"),
156 Some(false) => out.push_str("</ul>"),
157 None => {}
158 }
159 }
160 Event::Start(Tag::Item) => out.push_str("<li>"),
161 Event::End(TagEnd::Item) => out.push_str("</li>"),
162 Event::TaskListMarker(checked) => {
163 let _ = write!(
164 out,
165 "<input type=\"checkbox\" disabled{}>",
166 if checked { " checked" } else { "" }
167 );
168 }
169 Event::Rule => out.push_str("<hr>"),
170 Event::Text(text) => out.push_str(&escape_html(&text)),
177 Event::Html(text) | Event::InlineHtml(text) => out.push_str(&text),
178 Event::SoftBreak => out.push('\n'),
179 Event::HardBreak => out.push_str("<br>"),
180 Event::InlineMath(tex) => {
184 let mathml = mathml(&tex, latex2mathml::DisplayStyle::Inline)?;
185 out.push_str(&mathml);
186 }
187 Event::DisplayMath(tex) => {
188 let mathml = mathml(&tex, latex2mathml::DisplayStyle::Block)?;
189 out.push_str(&mathml);
190 }
191 _ => {}
192 }
193 }
194 Ok(out)
195}
196
197fn escape_html(src: &str) -> String {
198 src.replace('&', "&")
199 .replace('<', "<")
200 .replace('>', ">")
201}
202
203fn mathml(latex: &str, style: latex2mathml::DisplayStyle) -> Result<String, DocsError> {
206 latex2mathml::latex_to_mathml(latex, style).map_err(|_| DocsError::BadMath(latex.to_owned()))
207}
208
209fn escape_attr(src: &str) -> String {
210 escape_html(src).replace('"', """)
211}