You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

288 lines
12KB

  1. use std::borrow::Cow::Owned;
  2. use pulldown_cmark as cmark;
  3. use self::cmark::{Parser, Event, Tag, Options, OPTION_ENABLE_TABLES, OPTION_ENABLE_FOOTNOTES};
  4. use slug::slugify;
  5. use syntect::easy::HighlightLines;
  6. use syntect::html::{start_coloured_html_snippet, styles_to_coloured_html, IncludeBackground};
  7. use errors::Result;
  8. use utils::site::resolve_internal_link;
  9. use context::Context;
  10. use highlighting::{SYNTAX_SET, THEME_SET};
  11. use short_code::{SHORTCODE_RE, ShortCode, parse_shortcode, render_simple_shortcode};
  12. use table_of_contents::{TempHeader, Header, make_table_of_contents};
  13. pub fn markdown_to_html(content: &str, context: &Context) -> Result<(String, Vec<Header>)> {
  14. // We try to be smart about highlighting code as it can be time-consuming
  15. // If the global config disables it, then we do nothing. However,
  16. // if we see a code block in the content, we assume that this page needs
  17. // to be highlighted. It could potentially have false positive if the content
  18. // has ``` in it but that seems kind of unlikely
  19. let should_highlight = if context.highlight_code {
  20. content.contains("```")
  21. } else {
  22. false
  23. };
  24. // Set while parsing
  25. let mut error = None;
  26. let mut highlighter: Option<HighlightLines> = None;
  27. // the markdown parser will send several Text event if a markdown character
  28. // is present in it, for example `hello_test` will be split in 2: hello and _test.
  29. // Since we can use those chars in shortcode arguments, we need to collect
  30. // the full shortcode somehow first
  31. let mut current_shortcode = String::new();
  32. let mut shortcode_block = None;
  33. // shortcodes live outside of paragraph so we need to ensure we don't close
  34. // a paragraph that has already been closed
  35. let mut added_shortcode = false;
  36. // Don't transform things that look like shortcodes in code blocks
  37. let mut in_code_block = false;
  38. // If we get text in header, we need to insert the id and a anchor
  39. let mut in_header = false;
  40. // pulldown_cmark can send several text events for a title if there are markdown
  41. // specific characters like `!` in them. We only want to insert the anchor the first time
  42. let mut header_created = false;
  43. let mut anchors: Vec<String> = vec![];
  44. // the rendered html
  45. let mut html = String::new();
  46. // We might have cases where the slug is already present in our list of anchor
  47. // for example an article could have several titles named Example
  48. // We add a counter after the slug if the slug is already present, which
  49. // means we will have example, example-1, example-2 etc
  50. fn find_anchor(anchors: &[String], name: String, level: u8) -> String {
  51. if level == 0 && !anchors.contains(&name) {
  52. return name.to_string();
  53. }
  54. let new_anchor = format!("{}-{}", name, level + 1);
  55. if !anchors.contains(&new_anchor) {
  56. return new_anchor;
  57. }
  58. find_anchor(anchors, name, level + 1)
  59. }
  60. let mut headers = vec![];
  61. // Defaults to a 0 level so not a real header
  62. // It should be an Option ideally but not worth the hassle to update
  63. let mut temp_header = TempHeader::default();
  64. let mut opts = Options::empty();
  65. opts.insert(OPTION_ENABLE_TABLES);
  66. opts.insert(OPTION_ENABLE_FOOTNOTES);
  67. {
  68. let parser = Parser::new_ext(content, opts).map(|event| match event {
  69. Event::Text(mut text) => {
  70. // Header first
  71. if in_header {
  72. if header_created {
  73. temp_header.push(&text);
  74. return Event::Html(Owned(String::new()));
  75. }
  76. let id = find_anchor(&anchors, slugify(&text), 0);
  77. anchors.push(id.clone());
  78. // update the header and add it to the list
  79. temp_header.id = id.clone();
  80. // += as we might have some <code> or other things already there
  81. temp_header.title += &text;
  82. temp_header.permalink = format!("{}#{}", context.current_page_permalink, id);
  83. header_created = true;
  84. return Event::Html(Owned(String::new()));
  85. }
  86. // if we are in the middle of a code block
  87. if let Some(ref mut highlighter) = highlighter {
  88. let highlighted = &highlighter.highlight(&text);
  89. let html = styles_to_coloured_html(highlighted, IncludeBackground::Yes);
  90. return Event::Html(Owned(html));
  91. }
  92. if in_code_block {
  93. return Event::Text(text);
  94. }
  95. // Are we in the middle of a shortcode that somehow got cut off
  96. // by the markdown parser?
  97. if current_shortcode.is_empty() {
  98. if text.starts_with("{{") && !text.ends_with("}}") {
  99. current_shortcode += &text;
  100. } else if text.starts_with("{%") && !text.ends_with("%}") {
  101. current_shortcode += &text;
  102. }
  103. } else {
  104. current_shortcode += &text;
  105. }
  106. if current_shortcode.ends_with("}}") || current_shortcode.ends_with("%}") {
  107. text = Owned(current_shortcode.clone());
  108. current_shortcode = String::new();
  109. }
  110. // Shortcode without body
  111. if shortcode_block.is_none() && text.starts_with("{{") && text.ends_with("}}") && SHORTCODE_RE.is_match(&text) {
  112. let (name, args) = parse_shortcode(&text);
  113. added_shortcode = true;
  114. match render_simple_shortcode(context.tera, &name, &args) {
  115. Ok(s) => return Event::Html(Owned(format!("</p>{}", s))),
  116. Err(e) => {
  117. error = Some(e);
  118. return Event::Html(Owned(String::new()));
  119. }
  120. }
  121. }
  122. // Shortcode with a body
  123. if shortcode_block.is_none() && text.starts_with("{%") && text.ends_with("%}") {
  124. if SHORTCODE_RE.is_match(&text) {
  125. let (name, args) = parse_shortcode(&text);
  126. shortcode_block = Some(ShortCode::new(&name, args));
  127. }
  128. // Don't return anything
  129. return Event::Text(Owned(String::new()));
  130. }
  131. // If we have some text while in a shortcode, it's either the body
  132. // or the end tag
  133. if shortcode_block.is_some() {
  134. if let Some(ref mut shortcode) = shortcode_block {
  135. if text.trim() == "{% end %}" {
  136. added_shortcode = true;
  137. match shortcode.render(context.tera) {
  138. Ok(s) => return Event::Html(Owned(format!("</p>{}", s))),
  139. Err(e) => {
  140. error = Some(e);
  141. return Event::Html(Owned(String::new()));
  142. }
  143. }
  144. } else {
  145. shortcode.append(&text);
  146. return Event::Html(Owned(String::new()));
  147. }
  148. }
  149. }
  150. // Business as usual
  151. Event::Text(text)
  152. },
  153. Event::Start(Tag::CodeBlock(ref info)) => {
  154. in_code_block = true;
  155. if !should_highlight {
  156. return Event::Html(Owned("<pre><code>".to_owned()));
  157. }
  158. let theme = &THEME_SET.themes[&context.highlight_theme];
  159. highlighter = SYNTAX_SET.with(|ss| {
  160. let syntax = info
  161. .split(' ')
  162. .next()
  163. .and_then(|lang| ss.find_syntax_by_token(lang))
  164. .unwrap_or_else(|| ss.find_syntax_plain_text());
  165. Some(HighlightLines::new(syntax, theme))
  166. });
  167. let snippet = start_coloured_html_snippet(theme);
  168. Event::Html(Owned(snippet))
  169. },
  170. Event::End(Tag::CodeBlock(_)) => {
  171. in_code_block = false;
  172. if !should_highlight{
  173. return Event::Html(Owned("</code></pre>\n".to_owned()))
  174. }
  175. // reset highlight and close the code block
  176. highlighter = None;
  177. Event::Html(Owned("</pre>".to_owned()))
  178. },
  179. // Need to handle relative links
  180. Event::Start(Tag::Link(ref link, ref title)) => {
  181. if in_header {
  182. return Event::Html(Owned("".to_owned()));
  183. }
  184. if link.starts_with("./") {
  185. match resolve_internal_link(link, context.permalinks) {
  186. Ok(url) => {
  187. return Event::Start(Tag::Link(Owned(url), title.clone()));
  188. },
  189. Err(_) => {
  190. error = Some(format!("Relative link {} not found.", link).into());
  191. return Event::Html(Owned("".to_string()));
  192. }
  193. };
  194. }
  195. Event::Start(Tag::Link(link.clone(), title.clone()))
  196. },
  197. Event::End(Tag::Link(_, _)) => {
  198. if in_header {
  199. return Event::Html(Owned("".to_owned()));
  200. }
  201. event
  202. }
  203. // need to know when we are in a code block to disable shortcodes in them
  204. Event::Start(Tag::Code) => {
  205. in_code_block = true;
  206. if in_header {
  207. temp_header.push("<code>");
  208. return Event::Html(Owned(String::new()));
  209. }
  210. event
  211. },
  212. Event::End(Tag::Code) => {
  213. in_code_block = false;
  214. if in_header {
  215. temp_header.push("</code>");
  216. return Event::Html(Owned(String::new()));
  217. }
  218. event
  219. },
  220. Event::Start(Tag::Header(num)) => {
  221. in_header = true;
  222. temp_header = TempHeader::new(num);
  223. Event::Html(Owned(String::new()))
  224. },
  225. Event::End(Tag::Header(_)) => {
  226. // End of a header, reset all the things and return the stringified version of the header
  227. in_header = false;
  228. header_created = false;
  229. let val = temp_header.to_string(context);
  230. headers.push(temp_header.clone());
  231. temp_header = TempHeader::default();
  232. Event::Html(Owned(val))
  233. },
  234. // If we added shortcodes, don't close a paragraph since there's none
  235. Event::End(Tag::Paragraph) => {
  236. if added_shortcode {
  237. added_shortcode = false;
  238. return Event::Html(Owned("".to_owned()));
  239. }
  240. event
  241. },
  242. // Ignore softbreaks inside shortcodes
  243. Event::SoftBreak => {
  244. if shortcode_block.is_some() {
  245. return Event::Html(Owned("".to_owned()));
  246. }
  247. event
  248. },
  249. _ => {
  250. // println!("event = {:?}", event);
  251. event
  252. },
  253. });
  254. cmark::html::push_html(&mut html, parser);
  255. }
  256. if !current_shortcode.is_empty() {
  257. return Err(format!("A shortcode was not closed properly:\n{:?}", current_shortcode).into());
  258. }
  259. match error {
  260. Some(e) => Err(e),
  261. None => Ok((html.replace("<p></p>", ""), make_table_of_contents(&headers))),
  262. }
  263. }