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.

287 lines
10KB

  1. use std::borrow::Cow::{Borrowed, Owned};
  2. use pulldown_cmark as cmark;
  3. use slug::slugify;
  4. use syntect::easy::HighlightLines;
  5. use syntect::html::{
  6. start_highlighted_html_snippet, styled_line_to_highlighted_html, IncludeBackground,
  7. };
  8. use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET};
  9. use context::RenderContext;
  10. use errors::{Error, Result};
  11. use front_matter::InsertAnchor;
  12. use link_checker::check_url;
  13. use table_of_contents::{make_table_of_contents, Header};
  14. use utils::site::resolve_internal_link;
  15. use utils::vec::InsertMany;
  16. use self::cmark::{Event, Options, Parser, Tag};
  17. const CONTINUE_READING: &str =
  18. "<p id=\"zola-continue-reading\"><a name=\"continue-reading\"></a></p>\n";
  19. const ANCHOR_LINK_TEMPLATE: &str = "anchor-link.html";
  20. #[derive(Debug)]
  21. pub struct Rendered {
  22. pub body: String,
  23. pub summary_len: Option<usize>,
  24. pub toc: Vec<Header>,
  25. }
  26. // tracks a header in a slice of pulldown-cmark events
  27. #[derive(Debug)]
  28. struct HeaderRef {
  29. start_idx: usize,
  30. end_idx: usize,
  31. level: i32,
  32. }
  33. impl HeaderRef {
  34. fn new(start: usize, level: i32) -> HeaderRef {
  35. HeaderRef { start_idx: start, end_idx: 0, level }
  36. }
  37. }
  38. // We might have cases where the slug is already present in our list of anchor
  39. // for example an article could have several titles named Example
  40. // We add a counter after the slug if the slug is already present, which
  41. // means we will have example, example-1, example-2 etc
  42. fn find_anchor(anchors: &[String], name: String, level: u8) -> String {
  43. if level == 0 && !anchors.contains(&name) {
  44. return name;
  45. }
  46. let new_anchor = format!("{}-{}", name, level + 1);
  47. if !anchors.contains(&new_anchor) {
  48. return new_anchor;
  49. }
  50. find_anchor(anchors, name, level + 1)
  51. }
  52. // Colocated asset links refers to the files in the same directory,
  53. // there it should be a filename only
  54. fn is_colocated_asset_link(link: &str) -> bool {
  55. !link.contains('/') // http://, ftp://, ../ etc
  56. && !link.starts_with("mailto:")
  57. }
  58. fn fix_link(link: &str, context: &RenderContext) -> Result<String> {
  59. // A few situations here:
  60. // - it could be a relative link (starting with `./`)
  61. // - it could be a link to a co-located asset
  62. // - it could be a normal link
  63. let result = if link.starts_with("./") {
  64. match resolve_internal_link(&link, context.permalinks) {
  65. Ok(url) => url,
  66. Err(_) => {
  67. return Err(format!("Relative link {} not found.", link).into());
  68. }
  69. }
  70. } else if is_colocated_asset_link(&link) {
  71. format!("{}{}", context.current_page_permalink, link)
  72. } else if context.config.check_external_links
  73. && !link.starts_with('#')
  74. && !link.starts_with("mailto:")
  75. {
  76. let res = check_url(&link);
  77. if res.is_valid() {
  78. link.to_string()
  79. } else {
  80. return Err(format!("Link {} is not valid: {}", link, res.message()).into());
  81. }
  82. } else {
  83. link.to_string()
  84. };
  85. Ok(result)
  86. }
  87. /// get only text in a slice of events
  88. fn get_text(parser_slice: &[Event]) -> String {
  89. let mut title = String::new();
  90. for event in parser_slice.iter() {
  91. if let Event::Text(text) = event {
  92. title += text;
  93. }
  94. }
  95. title
  96. }
  97. fn get_header_refs(events: &[Event]) -> Vec<HeaderRef> {
  98. let mut header_refs = vec![];
  99. for (i, event) in events.iter().enumerate() {
  100. match event {
  101. Event::Start(Tag::Header(level)) => {
  102. header_refs.push(HeaderRef::new(i, *level));
  103. }
  104. Event::End(Tag::Header(_)) => {
  105. let msg = "Header end before start?";
  106. header_refs.last_mut().expect(msg).end_idx = i;
  107. }
  108. _ => (),
  109. }
  110. }
  111. header_refs
  112. }
  113. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Rendered> {
  114. // the rendered html
  115. let mut html = String::with_capacity(content.len());
  116. // Set while parsing
  117. let mut error = None;
  118. let mut background = IncludeBackground::Yes;
  119. let mut highlighter: Option<(HighlightLines, bool)> = None;
  120. let mut inserted_anchors: Vec<String> = vec![];
  121. let mut headers: Vec<Header> = vec![];
  122. let mut opts = Options::empty();
  123. let mut has_summary = false;
  124. opts.insert(Options::ENABLE_TABLES);
  125. opts.insert(Options::ENABLE_FOOTNOTES);
  126. {
  127. let mut events = Parser::new_ext(content, opts)
  128. .map(|event| {
  129. match event {
  130. Event::Text(text) => {
  131. // if we are in the middle of a code block
  132. if let Some((ref mut highlighter, in_extra)) = highlighter {
  133. let highlighted = if in_extra {
  134. if let Some(ref extra) = context.config.extra_syntax_set {
  135. highlighter.highlight(&text, &extra)
  136. } else {
  137. unreachable!(
  138. "Got a highlighter from extra syntaxes but no extra?"
  139. );
  140. }
  141. } else {
  142. highlighter.highlight(&text, &SYNTAX_SET)
  143. };
  144. //let highlighted = &highlighter.highlight(&text, ss);
  145. let html = styled_line_to_highlighted_html(&highlighted, background);
  146. return Event::Html(Owned(html));
  147. }
  148. // Business as usual
  149. Event::Text(text)
  150. }
  151. Event::Start(Tag::CodeBlock(ref info)) => {
  152. if !context.config.highlight_code {
  153. return Event::Html(Borrowed("<pre><code>"));
  154. }
  155. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  156. highlighter = Some(get_highlighter(info, &context.config));
  157. // This selects the background color the same way that start_coloured_html_snippet does
  158. let color = theme
  159. .settings
  160. .background
  161. .unwrap_or(::syntect::highlighting::Color::WHITE);
  162. background = IncludeBackground::IfDifferent(color);
  163. let snippet = start_highlighted_html_snippet(theme);
  164. Event::Html(Owned(snippet.0))
  165. }
  166. Event::End(Tag::CodeBlock(_)) => {
  167. if !context.config.highlight_code {
  168. return Event::Html(Borrowed("</code></pre>\n"));
  169. }
  170. // reset highlight and close the code block
  171. highlighter = None;
  172. Event::Html(Borrowed("</pre>"))
  173. }
  174. Event::Start(Tag::Image(src, title)) => {
  175. if is_colocated_asset_link(&src) {
  176. return Event::Start(Tag::Image(
  177. Owned(format!("{}{}", context.current_page_permalink, src)),
  178. title,
  179. ));
  180. }
  181. Event::Start(Tag::Image(src, title))
  182. }
  183. Event::Start(Tag::Link(link, title)) => {
  184. let fixed_link = match fix_link(&link, context) {
  185. Ok(fixed_link) => fixed_link,
  186. Err(err) => {
  187. error = Some(err);
  188. return Event::Html(Borrowed(""));
  189. }
  190. };
  191. Event::Start(Tag::Link(Owned(fixed_link), title))
  192. }
  193. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  194. has_summary = true;
  195. Event::Html(Borrowed(CONTINUE_READING))
  196. }
  197. _ => event,
  198. }
  199. })
  200. .collect::<Vec<_>>(); // We need to collect the events to make a second pass
  201. let header_refs = get_header_refs(&events);
  202. let mut anchors_to_insert = vec![];
  203. for header_ref in header_refs {
  204. let start_idx = header_ref.start_idx;
  205. let end_idx = header_ref.end_idx;
  206. let title = get_text(&events[start_idx + 1..end_idx]);
  207. let id = find_anchor(&inserted_anchors, slugify(&title), 0);
  208. inserted_anchors.push(id.clone());
  209. // insert `id` to the tag
  210. let html = format!("<h{lvl} id=\"{id}\">", lvl = header_ref.level, id = id);
  211. events[start_idx] = Event::Html(Owned(html));
  212. // generate anchors and places to insert them
  213. if context.insert_anchor != InsertAnchor::None {
  214. let anchor_idx = match context.insert_anchor {
  215. InsertAnchor::Left => start_idx + 1,
  216. InsertAnchor::Right => end_idx,
  217. InsertAnchor::None => 0, // Not important
  218. };
  219. let mut c = tera::Context::new();
  220. c.insert("id", &id);
  221. let anchor_link = utils::templates::render_template(
  222. &ANCHOR_LINK_TEMPLATE,
  223. context.tera,
  224. c,
  225. &None,
  226. )
  227. .map_err(|e| Error::chain("Failed to render anchor link template", e))?;
  228. anchors_to_insert.push((anchor_idx, Event::Html(Owned(anchor_link))));
  229. }
  230. // record header to make table of contents
  231. let permalink = format!("{}#{}", context.current_page_permalink, id);
  232. let h = Header { level: header_ref.level, id, permalink, title, children: Vec::new() };
  233. headers.push(h);
  234. }
  235. if context.insert_anchor != InsertAnchor::None {
  236. events.insert_many(anchors_to_insert);
  237. }
  238. cmark::html::push_html(&mut html, events.into_iter());
  239. }
  240. if let Some(e) = error {
  241. return Err(e);
  242. } else {
  243. Ok(Rendered {
  244. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  245. body: html,
  246. toc: make_table_of_contents(headers),
  247. })
  248. }
  249. }