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 let mut slug_counts: std::collections::HashMap<String, usize> =
52 std::collections::HashMap::new();
53 let mut heading_text = String::new();
54 let mut heading_open: Option<(usize, u8)> = None; while let Some(event) = parser.next() {
57 match event {
58 Event::Start(Tag::Heading { level, .. }) => {
59 headings.push(level as u8);
61 heading_text.clear();
62 heading_open = Some((out.len(), level as u8));
63 let _ = write!(out, "<{level}>");
64 }
65 Event::End(TagEnd::Heading(_)) => {
66 let level = headings.pop().unwrap_or(1);
67 let slug = slugify(&heading_text);
68 let count = slug_counts.entry(slug.clone()).or_insert(0);
69 *count += 1;
70 let id = if *count == 1 {
71 slug
72 } else {
73 format!("{slug}-{count}")
74 };
75 if let Some((offset, _)) = heading_open.take() {
76 let tag = format!("<h{level}>");
77 let with_id = format!("<h{level} id=\"{id}\">");
78 out.replace_range(offset..offset + tag.len(), &with_id);
79 }
80 let _ = write!(out, "</h{level}>");
81 }
82 Event::Start(Tag::Paragraph) => {
83 if list_stack.is_empty() {
84 out.push_str("<p>");
85 }
86 }
87 Event::End(TagEnd::Paragraph) => {
88 if list_stack.is_empty() {
89 out.push_str("</p>");
90 }
91 }
92 Event::Start(Tag::Emphasis) => out.push_str("<em>"),
93 Event::End(TagEnd::Emphasis) => out.push_str("</em>"),
94 Event::Start(Tag::Strong) => out.push_str("<strong>"),
95 Event::End(TagEnd::Strong) => out.push_str("</strong>"),
96 Event::Start(Tag::Strikethrough) => out.push_str("<del>"),
97 Event::End(TagEnd::Strikethrough) => out.push_str("</del>"),
98 Event::Code(code) => {
99 let _ = write!(out, "<code>{}</code>", escape_html(&code));
100 }
101 Event::Start(Tag::Link { dest_url, .. }) => {
102 let _ = write!(out, "<a href=\"{}\">", escape_attr(&dest_url));
103 }
104 Event::End(TagEnd::Link) => out.push_str("</a>"),
105 Event::Start(Tag::Image {
106 dest_url, title, ..
107 }) => {
108 let mut alt = String::new();
112 for inner in parser.by_ref() {
113 match inner {
114 Event::Text(t) => alt.push_str(&t),
115 Event::End(TagEnd::Image) => break,
116 _ => {}
117 }
118 }
119 let _ = write!(
120 out,
121 "<img src=\"{}\" alt=\"{}\"{}>",
122 escape_attr(&dest_url),
123 escape_attr(&alt),
124 if title.is_empty() {
125 String::new()
126 } else {
127 format!(" title=\"{}\"", escape_attr(&title))
128 }
129 );
130 }
131 Event::End(TagEnd::Image) => {}
132 Event::Start(Tag::BlockQuote(_)) => out.push_str("<blockquote>"),
133 Event::End(TagEnd::BlockQuote(_)) => out.push_str("</blockquote>"),
134 Event::Start(Tag::CodeBlock(kind)) => match kind {
135 CodeBlockKind::Fenced(info) if info.starts_with("island") => {
136 let mut body = String::new();
140 for inner in parser.by_ref() {
141 match inner {
142 Event::Text(t) => {
143 body.push_str(&t);
144 break;
145 }
146 Event::End(TagEnd::CodeBlock) => break,
147 _ => {}
148 }
149 }
150 if allow_islands {
151 let island = Island::parse(&info, &body)?;
152 out.push_str(&island.to_html(base));
153 }
154 let _ = parser.next(); }
158 _ => {
159 in_code_block = true;
160 out.push_str("<pre><code>");
161 }
162 },
163 Event::End(TagEnd::CodeBlock) => {
164 if in_code_block {
165 in_code_block = false;
166 out.push_str("</code></pre>");
167 }
168 }
169 Event::Start(Tag::List(start)) => {
170 let ordered = start.is_some();
171 let _ = write!(out, "<{}>", if ordered { "ol" } else { "ul" });
172 list_stack.push(ordered);
173 }
174 Event::End(TagEnd::List(_)) => {
175 match list_stack.pop() {
179 Some(true) => out.push_str("</ol>"),
180 Some(false) => out.push_str("</ul>"),
181 None => {}
182 }
183 }
184 Event::Start(Tag::Item) => out.push_str("<li>"),
185 Event::End(TagEnd::Item) => out.push_str("</li>"),
186 Event::TaskListMarker(checked) => {
187 let _ = write!(
188 out,
189 "<input type=\"checkbox\" disabled{}>",
190 if checked { " checked" } else { "" }
191 );
192 }
193 Event::Rule => out.push_str("<hr>"),
194 Event::Text(text) => {
201 if !headings.is_empty() {
203 heading_text.push_str(&text);
204 }
205 out.push_str(&escape_html(&text));
206 }
207 Event::Html(text) | Event::InlineHtml(text) => out.push_str(&text),
208 Event::SoftBreak => out.push('\n'),
209 Event::HardBreak => out.push_str("<br>"),
210 Event::InlineMath(tex) => {
214 let mathml = mathml(&tex, latex2mathml::DisplayStyle::Inline)?;
215 out.push_str(&mathml);
216 }
217 Event::DisplayMath(tex) => {
218 let mathml = mathml(&tex, latex2mathml::DisplayStyle::Block)?;
219 out.push_str(&mathml);
220 }
221 _ => {}
222 }
223 }
224 Ok(out)
225}
226
227fn escape_html(src: &str) -> String {
228 src.replace('&', "&")
229 .replace('<', "<")
230 .replace('>', ">")
231}
232
233fn slugify(text: &str) -> String {
236 let mut slug = String::with_capacity(text.len());
237 let mut last_hyphen = true;
238 for c in text.chars() {
239 if c.is_alphanumeric() {
240 for lower in c.to_lowercase() {
241 slug.push(lower);
242 }
243 last_hyphen = false;
244 } else if !last_hyphen {
245 slug.push('-');
246 last_hyphen = true;
247 }
248 }
249 let slug = slug.trim_end_matches('-').to_string();
250 if slug.is_empty() {
251 "heading".to_string()
252 } else {
253 slug
254 }
255}
256
257fn mathml(latex: &str, style: latex2mathml::DisplayStyle) -> Result<String, DocsError> {
260 latex2mathml::latex_to_mathml(latex, style).map_err(|_| DocsError::BadMath(latex.to_owned()))
261}
262
263fn escape_attr(src: &str) -> String {
264 escape_html(src).replace('"', """)
265}