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.

207 lines
8.4KB

  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 highlighting::{get_highlighter, THEME_SET};
  10. use table_of_contents::{TempHeader, Header, make_table_of_contents};
  11. use context::RenderContext;
  12. // We might have cases where the slug is already present in our list of anchor
  13. // for example an article could have several titles named Example
  14. // We add a counter after the slug if the slug is already present, which
  15. // means we will have example, example-1, example-2 etc
  16. fn find_anchor(anchors: &[String], name: String, level: u8) -> String {
  17. if level == 0 && !anchors.contains(&name) {
  18. return name.to_string();
  19. }
  20. let new_anchor = format!("{}-{}", name, level + 1);
  21. if !anchors.contains(&new_anchor) {
  22. return new_anchor;
  23. }
  24. find_anchor(anchors, name, level + 1)
  25. }
  26. fn is_colocated_asset_link(link: &str) -> bool {
  27. !link.contains("/") // http://, ftp://, ../ etc
  28. && !link.starts_with("mailto:")
  29. }
  30. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<(String, Vec<Header>)> {
  31. // the rendered html
  32. let mut html = String::with_capacity(content.len());
  33. // Set while parsing
  34. let mut error = None;
  35. let mut highlighter: Option<HighlightLines> = None;
  36. // If we get text in header, we need to insert the id and a anchor
  37. let mut in_header = false;
  38. // pulldown_cmark can send several text events for a title if there are markdown
  39. // specific characters like `!` in them. We only want to insert the anchor the first time
  40. let mut header_created = false;
  41. let mut anchors: Vec<String> = vec![];
  42. let mut headers = vec![];
  43. // Defaults to a 0 level so not a real header
  44. // It should be an Option ideally but not worth the hassle to update
  45. let mut temp_header = TempHeader::default();
  46. let mut opts = Options::empty();
  47. opts.insert(OPTION_ENABLE_TABLES);
  48. opts.insert(OPTION_ENABLE_FOOTNOTES);
  49. {
  50. let parser = Parser::new_ext(content, opts).map(|event| {
  51. match event {
  52. Event::Text(text) => {
  53. // Header first
  54. if in_header {
  55. if header_created {
  56. temp_header.push(&text);
  57. return Event::Html(Owned(String::new()));
  58. }
  59. let id = find_anchor(&anchors, slugify(&text), 0);
  60. anchors.push(id.clone());
  61. // update the header and add it to the list
  62. temp_header.permalink = format!("{}#{}", context.current_page_permalink, id);
  63. temp_header.id = id;
  64. // += as we might have some <code> or other things already there
  65. temp_header.title += &text;
  66. header_created = true;
  67. return Event::Html(Owned(String::new()));
  68. }
  69. // if we are in the middle of a code block
  70. if let Some(ref mut highlighter) = highlighter {
  71. let highlighted = &highlighter.highlight(&text);
  72. let html = styles_to_coloured_html(highlighted, IncludeBackground::Yes);
  73. return Event::Html(Owned(html));
  74. }
  75. // Business as usual
  76. Event::Text(text)
  77. },
  78. Event::Start(Tag::CodeBlock(ref info)) => {
  79. if !context.config.highlight_code {
  80. return Event::Html(Owned("<pre><code>".to_string()));
  81. }
  82. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  83. highlighter = Some(get_highlighter(&theme, info));
  84. let snippet = start_coloured_html_snippet(theme);
  85. Event::Html(Owned(snippet))
  86. },
  87. Event::End(Tag::CodeBlock(_)) => {
  88. if !context.config.highlight_code {
  89. return Event::Html(Owned("</code></pre>\n".to_string()))
  90. }
  91. // reset highlight and close the code block
  92. highlighter = None;
  93. Event::Html(Owned("</pre>".to_string()))
  94. },
  95. Event::Start(Tag::Image(src, title)) => {
  96. if is_colocated_asset_link(&src) {
  97. return Event::Start(
  98. Tag::Image(
  99. Owned(format!("{}{}", context.current_page_permalink, src)),
  100. title,
  101. )
  102. );
  103. }
  104. Event::Start(Tag::Image(src, title))
  105. },
  106. Event::Start(Tag::Link(link, title)) => {
  107. // A few situations here:
  108. // - it could be a relative link (starting with `./`)
  109. // - it could be a link to a co-located asset
  110. // - it could be a normal link
  111. // - any of those can be in a header or not: if it's in a header
  112. // we need to append to a string
  113. let fixed_link = if link.starts_with("./") {
  114. match resolve_internal_link(&link, context.permalinks) {
  115. Ok(url) => url,
  116. Err(_) => {
  117. error = Some(format!("Relative link {} not found.", link).into());
  118. return Event::Html(Owned(String::new()));
  119. }
  120. }
  121. } else if is_colocated_asset_link(&link) {
  122. format!("{}{}", context.current_page_permalink, link)
  123. } else {
  124. link.to_string()
  125. };
  126. if in_header {
  127. let html = if title.is_empty() {
  128. format!("<a href=\"{}\">", fixed_link)
  129. } else {
  130. format!("<a href=\"{}\" title=\"{}\">", fixed_link, title)
  131. };
  132. temp_header.push(&html);
  133. return Event::Html(Owned(String::new()));
  134. }
  135. Event::Start(Tag::Link(Owned(fixed_link), title))
  136. },
  137. Event::End(Tag::Link(_, _)) => {
  138. if in_header {
  139. temp_header.push("</a>");
  140. return Event::Html(Owned(String::new()));
  141. }
  142. event
  143. },
  144. Event::Start(Tag::Code) => {
  145. if in_header {
  146. temp_header.push("<code>");
  147. return Event::Html(Owned(String::new()));
  148. }
  149. event
  150. },
  151. Event::End(Tag::Code) => {
  152. if in_header {
  153. temp_header.push("</code>");
  154. return Event::Html(Owned(String::new()));
  155. }
  156. event
  157. },
  158. Event::Start(Tag::Header(num)) => {
  159. in_header = true;
  160. temp_header = TempHeader::new(num);
  161. Event::Html(Owned(String::new()))
  162. },
  163. Event::End(Tag::Header(_)) => {
  164. // End of a header, reset all the things and return the stringified
  165. // version of the header
  166. in_header = false;
  167. header_created = false;
  168. let val = temp_header.to_string(context.tera, context.insert_anchor);
  169. headers.push(temp_header.clone());
  170. temp_header = TempHeader::default();
  171. Event::Html(Owned(val))
  172. },
  173. _ => event,
  174. }
  175. });
  176. cmark::html::push_html(&mut html, parser);
  177. }
  178. match error {
  179. Some(e) => Err(e),
  180. None => Ok((
  181. html.replace("<p></p>", "").replace("</p></p>", "</p>"),
  182. make_table_of_contents(&headers)
  183. )),
  184. }
  185. }