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.

194 lines
8.0KB

  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. // Need to handle relative links
  96. Event::Start(Tag::Link(link, title)) => {
  97. // A few situations here:
  98. // - it could be a relative link (starting with `./`)
  99. // - it could be a link to a co-located asset
  100. // - it could be a normal link
  101. // - any of those can be in a header or not: if it's in a header we need to append to a string
  102. let fixed_link = if link.starts_with("./") {
  103. match resolve_internal_link(&link, context.permalinks) {
  104. Ok(url) => url,
  105. Err(_) => {
  106. error = Some(format!("Relative link {} not found.", link).into());
  107. return Event::Html(Owned(String::new()));
  108. }
  109. }
  110. } else if is_colocated_asset_link(&link) {
  111. format!("{}{}", context.current_page_permalink, link)
  112. } else {
  113. link.to_string()
  114. };
  115. if in_header {
  116. let html = if title.is_empty() {
  117. format!("<a href=\"{}\">", fixed_link)
  118. } else {
  119. format!("<a href=\"{}\" title=\"{}\">", fixed_link, title)
  120. };
  121. temp_header.push(&html);
  122. return Event::Html(Owned(String::new()));
  123. }
  124. Event::Start(Tag::Link(Owned(fixed_link), title))
  125. },
  126. Event::End(Tag::Link(_, _)) => {
  127. if in_header {
  128. temp_header.push("</a>");
  129. return Event::Html(Owned(String::new()));
  130. }
  131. event
  132. },
  133. Event::Start(Tag::Code) => {
  134. if in_header {
  135. temp_header.push("<code>");
  136. return Event::Html(Owned(String::new()));
  137. }
  138. event
  139. },
  140. Event::End(Tag::Code) => {
  141. if in_header {
  142. temp_header.push("</code>");
  143. return Event::Html(Owned(String::new()));
  144. }
  145. event
  146. },
  147. Event::Start(Tag::Header(num)) => {
  148. in_header = true;
  149. temp_header = TempHeader::new(num);
  150. Event::Html(Owned(String::new()))
  151. },
  152. Event::End(Tag::Header(_)) => {
  153. // End of a header, reset all the things and return the stringified version of the header
  154. in_header = false;
  155. header_created = false;
  156. let val = temp_header.to_string(context.tera, context.insert_anchor);
  157. headers.push(temp_header.clone());
  158. temp_header = TempHeader::default();
  159. Event::Html(Owned(val))
  160. },
  161. _ => event,
  162. }
  163. });
  164. cmark::html::push_html(&mut html, parser);
  165. }
  166. match error {
  167. Some(e) => Err(e),
  168. None => Ok((
  169. html.replace("<p></p>", "").replace("</p></p>", "</p>"),
  170. make_table_of_contents(&headers)
  171. )),
  172. }
  173. }