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.

310 lines
12KB

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