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