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.

273 lines
10KB

  1. use std::borrow::Cow::{Borrowed, Owned};
  2. use self::cmark::{Event, Options, Parser, Tag};
  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 id=\"zola-continue-reading\"><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;
  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. // Colocated asset links refers to the files in the same directory,
  37. // there it should be a filename only
  38. fn is_colocated_asset_link(link: &str) -> bool {
  39. !link.contains('/') // http://, ftp://, ../ etc
  40. && !link.starts_with("mailto:")
  41. }
  42. fn fix_link(link: &str, context: &RenderContext) -> Result<String> {
  43. // A few situations here:
  44. // - it could be a relative link (starting with `./`)
  45. // - it could be a link to a co-located asset
  46. // - it could be a normal link
  47. let result = if link.starts_with("./") {
  48. match resolve_internal_link(&link, context.permalinks) {
  49. Ok(url) => url,
  50. Err(_) => {
  51. return Err(format!("Relative link {} not found.", link).into());
  52. }
  53. }
  54. } else if is_colocated_asset_link(&link) {
  55. format!("{}{}", context.current_page_permalink, link)
  56. } else if context.config.check_external_links
  57. && !link.starts_with('#')
  58. && !link.starts_with("mailto:") {
  59. let res = check_url(&link);
  60. if res.is_valid() {
  61. link.to_string()
  62. } else {
  63. return Err(
  64. format!("Link {} is not valid: {}", link, res.message()).into(),
  65. );
  66. }
  67. } else {
  68. link.to_string()
  69. };
  70. Ok(result)
  71. }
  72. fn push_start_tag(temp_header: &mut TempHeader, tag: &Tag) -> bool {
  73. match tag {
  74. Tag::Emphasis => temp_header.add_html("<em>"),
  75. Tag::Strong => temp_header.add_html("<strong>"),
  76. Tag::Code => temp_header.add_html("<code>"),
  77. // Tag::Link is handled in `markdown_to_html`
  78. _ => return false,
  79. }
  80. true
  81. }
  82. fn push_end_tag(temp_header: &mut TempHeader, tag: &Tag) -> bool {
  83. match tag {
  84. Tag::Emphasis => temp_header.add_html("</em>"),
  85. Tag::Strong => temp_header.add_html("</strong>"),
  86. Tag::Code => temp_header.add_html("</code>"),
  87. Tag::Link(_, _) => temp_header.add_html("</a>"),
  88. _ => return false,
  89. }
  90. true
  91. }
  92. /// returns true if event have been processed
  93. fn push_to_temp_header(event: &Event, temp_header: &mut TempHeader) -> bool {
  94. match event {
  95. Event::Start(tag) => push_start_tag(temp_header, tag),
  96. Event::End(tag) => push_end_tag(temp_header, tag),
  97. _ => false,
  98. }
  99. }
  100. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Rendered> {
  101. // the rendered html
  102. let mut html = String::with_capacity(content.len());
  103. // Set while parsing
  104. let mut error = None;
  105. let mut background = IncludeBackground::Yes;
  106. let mut highlighter: Option<(HighlightLines, bool)> = None;
  107. // If we get text in header, we need to insert the id and a anchor
  108. let mut in_header = false;
  109. // pulldown_cmark can send several text events for a title if there are markdown
  110. // specific characters like `!` in them. We only want to insert the anchor the first time
  111. let mut header_created = false;
  112. let mut anchors: Vec<String> = vec![];
  113. let mut headers = vec![];
  114. // Defaults to a 0 level so not a real header
  115. // It should be an Option ideally but not worth the hassle to update
  116. let mut temp_header = TempHeader::default();
  117. let mut opts = Options::empty();
  118. let mut has_summary = false;
  119. opts.insert(Options::ENABLE_TABLES);
  120. opts.insert(Options::ENABLE_FOOTNOTES);
  121. {
  122. let parser = Parser::new_ext(content, opts).map(|event| {
  123. // if in header, just do the parse ourselves
  124. if in_header && push_to_temp_header(&event, &mut temp_header) {
  125. return Event::Html(Borrowed(""));
  126. }
  127. match event {
  128. Event::Text(text) => {
  129. // Header first
  130. if in_header {
  131. if header_created {
  132. temp_header.add_text(&text);
  133. return Event::Html(Borrowed(""));
  134. }
  135. // += as we might have some <code> or other things already there
  136. temp_header.add_text(&text);
  137. header_created = true;
  138. return Event::Html(Borrowed(""));
  139. }
  140. // if we are in the middle of a code block
  141. if let Some((ref mut highlighter, in_extra)) = highlighter {
  142. let highlighted = if in_extra {
  143. if let Some(ref extra) = context.config.extra_syntax_set {
  144. highlighter.highlight(&text, &extra)
  145. } else {
  146. unreachable!("Got a highlighter from extra syntaxes but no extra?");
  147. }
  148. } else {
  149. highlighter.highlight(&text, &SYNTAX_SET)
  150. };
  151. //let highlighted = &highlighter.highlight(&text, ss);
  152. let html = styled_line_to_highlighted_html(&highlighted, background);
  153. return Event::Html(Owned(html));
  154. }
  155. // Business as usual
  156. Event::Text(text)
  157. }
  158. Event::Start(Tag::CodeBlock(ref info)) => {
  159. if !context.config.highlight_code {
  160. return Event::Html(Borrowed("<pre><code>"));
  161. }
  162. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  163. highlighter = Some(get_highlighter(info, &context.config));
  164. // This selects the background color the same way that start_coloured_html_snippet does
  165. let color =
  166. theme.settings.background.unwrap_or(::syntect::highlighting::Color::WHITE);
  167. background = IncludeBackground::IfDifferent(color);
  168. let snippet = start_highlighted_html_snippet(theme);
  169. Event::Html(Owned(snippet.0))
  170. }
  171. Event::End(Tag::CodeBlock(_)) => {
  172. if !context.config.highlight_code {
  173. return Event::Html(Borrowed("</code></pre>\n"));
  174. }
  175. // reset highlight and close the code block
  176. highlighter = None;
  177. Event::Html(Borrowed("</pre>"))
  178. }
  179. Event::Start(Tag::Image(src, title)) => {
  180. if is_colocated_asset_link(&src) {
  181. return Event::Start(Tag::Image(
  182. Owned(format!("{}{}", context.current_page_permalink, src)),
  183. title,
  184. ));
  185. }
  186. Event::Start(Tag::Image(src, title))
  187. }
  188. Event::Start(Tag::Link(link, title)) => {
  189. let fixed_link = match fix_link(&link, context) {
  190. Ok(fixed_link) => fixed_link,
  191. Err(err) => {
  192. error = Some(err);
  193. return Event::Html(Borrowed(""))
  194. }
  195. };
  196. if in_header {
  197. let html = if title.is_empty() {
  198. format!("<a href=\"{}\">", fixed_link)
  199. } else {
  200. format!("<a href=\"{}\" title=\"{}\">", fixed_link, title)
  201. };
  202. temp_header.add_html(&html);
  203. return Event::Html(Borrowed(""));
  204. }
  205. Event::Start(Tag::Link(Owned(fixed_link), title))
  206. }
  207. Event::Start(Tag::Header(num)) => {
  208. in_header = true;
  209. temp_header = TempHeader::new(num);
  210. Event::Html(Borrowed(""))
  211. }
  212. Event::End(Tag::Header(_)) => {
  213. // End of a header, reset all the things and return the header string
  214. let id = find_anchor(&anchors, slugify(&temp_header.title), 0);
  215. anchors.push(id.clone());
  216. temp_header.permalink = format!("{}#{}", context.current_page_permalink, id);
  217. temp_header.id = id;
  218. in_header = false;
  219. header_created = false;
  220. let val = temp_header.to_string(context.tera, context.insert_anchor);
  221. headers.push(temp_header.clone());
  222. temp_header = TempHeader::default();
  223. Event::Html(Owned(val))
  224. }
  225. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  226. has_summary = true;
  227. Event::Html(Borrowed(CONTINUE_READING))
  228. }
  229. _ => event,
  230. }
  231. });
  232. cmark::html::push_html(&mut html, parser);
  233. }
  234. if let Some(e) = error {
  235. return Err(e);
  236. } else {
  237. Ok(Rendered {
  238. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  239. body: html,
  240. toc: make_table_of_contents(&headers),
  241. })
  242. }
  243. }