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.

250 lines
10KB

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