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.

331 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, Heading};
  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<Heading>,
  23. pub internal_links_with_anchors: Vec<(String, String)>,
  24. pub external_links: Vec<String>,
  25. }
  26. // tracks a heading in a slice of pulldown-cmark events
  27. #[derive(Debug)]
  28. struct HeadingRef {
  29. start_idx: usize,
  30. end_idx: usize,
  31. level: u32,
  32. id: Option<String>,
  33. }
  34. impl HeadingRef {
  35. fn new(start: usize, level: u32) -> HeadingRef {
  36. HeadingRef { start_idx: start, end_idx: 0, level, id: None }
  37. }
  38. }
  39. // We might have cases where the slug is already present in our list of anchor
  40. // for example an article could have several titles named Example
  41. // We add a counter after the slug if the slug is already present, which
  42. // means we will have example, example-1, example-2 etc
  43. fn find_anchor(anchors: &[String], name: String, level: u8) -> String {
  44. if level == 0 && !anchors.contains(&name) {
  45. return name;
  46. }
  47. let new_anchor = format!("{}-{}", name, level + 1);
  48. if !anchors.contains(&new_anchor) {
  49. return new_anchor;
  50. }
  51. find_anchor(anchors, name, level + 1)
  52. }
  53. // Colocated asset links refers to the files in the same directory,
  54. // there it should be a filename only
  55. fn is_colocated_asset_link(link: &str) -> bool {
  56. !link.contains('/') // http://, ftp://, ../ etc
  57. && !link.starts_with("mailto:")
  58. }
  59. fn fix_link(
  60. link_type: LinkType,
  61. link: &str,
  62. context: &RenderContext,
  63. internal_links_with_anchors: &mut Vec<(String, String)>,
  64. external_links: &mut Vec<String>,
  65. ) -> Result<String> {
  66. if link_type == LinkType::Email {
  67. return Ok(link.to_string());
  68. }
  69. // TODO: remove me in a few versions when people have upgraded
  70. if link.starts_with("./") && link.contains(".md") {
  71. println!("It looks like the link `{}` is using the previous syntax for internal links: start with @/ instead", link);
  72. }
  73. // A few situations here:
  74. // - it could be a relative link (starting with `@/`)
  75. // - it could be a link to a co-located asset
  76. // - it could be a normal link
  77. let result = if link.starts_with("@/") {
  78. match resolve_internal_link(&link, context.permalinks) {
  79. Ok(resolved) => {
  80. if resolved.anchor.is_some() {
  81. internal_links_with_anchors
  82. .push((resolved.md_path.unwrap(), resolved.anchor.unwrap()));
  83. }
  84. resolved.permalink
  85. }
  86. Err(_) => {
  87. return Err(format!("Relative link {} not found.", link).into());
  88. }
  89. }
  90. } else if is_colocated_asset_link(&link) {
  91. format!("{}{}", context.current_page_permalink, link)
  92. } else {
  93. if !link.starts_with('#') && !link.starts_with("mailto:") {
  94. external_links.push(link.to_owned());
  95. }
  96. link.to_string()
  97. };
  98. Ok(result)
  99. }
  100. /// get only text in a slice of events
  101. fn get_text(parser_slice: &[Event]) -> String {
  102. let mut title = String::new();
  103. for event in parser_slice.iter() {
  104. match event {
  105. Event::Text(text) | Event::Code(text) => title += text,
  106. _ => continue,
  107. }
  108. }
  109. title
  110. }
  111. fn get_heading_refs(events: &[Event]) -> Vec<HeadingRef> {
  112. let mut heading_refs = vec![];
  113. for (i, event) in events.iter().enumerate() {
  114. match event {
  115. Event::Start(Tag::Heading(level)) => {
  116. heading_refs.push(HeadingRef::new(i, *level));
  117. }
  118. Event::End(Tag::Heading(_)) => {
  119. let msg = "Heading end before start?";
  120. heading_refs.last_mut().expect(msg).end_idx = i;
  121. }
  122. _ => (),
  123. }
  124. }
  125. heading_refs
  126. }
  127. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Rendered> {
  128. // the rendered html
  129. let mut html = String::with_capacity(content.len());
  130. // Set while parsing
  131. let mut error = None;
  132. let mut background = IncludeBackground::Yes;
  133. let mut highlighter: Option<(HighlightLines, bool)> = None;
  134. let mut inserted_anchors: Vec<String> = vec![];
  135. let mut headings: Vec<Heading> = vec![];
  136. let mut internal_links_with_anchors = Vec::new();
  137. let mut external_links = Vec::new();
  138. let mut opts = Options::empty();
  139. let mut has_summary = false;
  140. opts.insert(Options::ENABLE_TABLES);
  141. opts.insert(Options::ENABLE_FOOTNOTES);
  142. {
  143. let mut events = Parser::new_ext(content, opts)
  144. .map(|event| {
  145. match event {
  146. Event::Text(text) => {
  147. // if we are in the middle of a code block
  148. if let Some((ref mut highlighter, in_extra)) = highlighter {
  149. let highlighted = if in_extra {
  150. if let Some(ref extra) = context.config.extra_syntax_set {
  151. highlighter.highlight(&text, &extra)
  152. } else {
  153. unreachable!(
  154. "Got a highlighter from extra syntaxes but no extra?"
  155. );
  156. }
  157. } else {
  158. highlighter.highlight(&text, &SYNTAX_SET)
  159. };
  160. //let highlighted = &highlighter.highlight(&text, ss);
  161. let html = styled_line_to_highlighted_html(&highlighted, background);
  162. return Event::Html(html.into());
  163. }
  164. // Business as usual
  165. Event::Text(text)
  166. }
  167. Event::Start(Tag::CodeBlock(ref info)) => {
  168. if !context.config.highlight_code {
  169. return Event::Html("<pre><code>".into());
  170. }
  171. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  172. highlighter = Some(get_highlighter(info, &context.config));
  173. // This selects the background color the same way that start_coloured_html_snippet does
  174. let color = theme
  175. .settings
  176. .background
  177. .unwrap_or(::syntect::highlighting::Color::WHITE);
  178. background = IncludeBackground::IfDifferent(color);
  179. let snippet = start_highlighted_html_snippet(theme);
  180. Event::Html(snippet.0.into())
  181. }
  182. Event::End(Tag::CodeBlock(_)) => {
  183. if !context.config.highlight_code {
  184. return Event::Html("</code></pre>\n".into());
  185. }
  186. // reset highlight and close the code block
  187. highlighter = None;
  188. Event::Html("</pre>".into())
  189. }
  190. Event::Start(Tag::Image(link_type, src, title)) => {
  191. if is_colocated_asset_link(&src) {
  192. let link = format!("{}{}", context.current_page_permalink, &*src);
  193. return Event::Start(Tag::Image(link_type, link.into(), title));
  194. }
  195. Event::Start(Tag::Image(link_type, src, title))
  196. }
  197. Event::Start(Tag::Link(link_type, link, title)) => {
  198. let fixed_link = match fix_link(
  199. link_type,
  200. &link,
  201. context,
  202. &mut internal_links_with_anchors,
  203. &mut external_links,
  204. ) {
  205. Ok(fixed_link) => fixed_link,
  206. Err(err) => {
  207. error = Some(err);
  208. return Event::Html("".into());
  209. }
  210. };
  211. Event::Start(Tag::Link(link_type, fixed_link.into(), title))
  212. }
  213. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  214. has_summary = true;
  215. Event::Html(CONTINUE_READING.into())
  216. }
  217. _ => event,
  218. }
  219. })
  220. .collect::<Vec<_>>(); // We need to collect the events to make a second pass
  221. let mut heading_refs = get_heading_refs(&events);
  222. let mut anchors_to_insert = vec![];
  223. // First heading pass: look for a manually-specified IDs, e.g. `# Heading text {#hash}`
  224. // (This is a separate first pass so that auto IDs can avoid collisions with manual IDs.)
  225. for heading_ref in heading_refs.iter_mut() {
  226. let end_idx = heading_ref.end_idx;
  227. if let Event::Text(ref mut text) = events[end_idx - 1] {
  228. if text.as_bytes().last() == Some(&b'}') {
  229. if let Some(mut i) = text.find("{#") {
  230. let id = text[i + 2..text.len() - 1].to_owned();
  231. inserted_anchors.push(id.clone());
  232. while i > 0 && text.as_bytes()[i - 1] == b' ' {
  233. i -= 1;
  234. }
  235. heading_ref.id = Some(id);
  236. *text = text[..i].to_owned().into();
  237. }
  238. }
  239. }
  240. }
  241. // Second heading pass: auto-generate remaining IDs, and emit HTML
  242. for heading_ref in heading_refs {
  243. let start_idx = heading_ref.start_idx;
  244. let end_idx = heading_ref.end_idx;
  245. let title = get_text(&events[start_idx + 1..end_idx]);
  246. let id =
  247. heading_ref.id.unwrap_or_else(|| find_anchor(&inserted_anchors, slugify(&title), 0));
  248. inserted_anchors.push(id.clone());
  249. // insert `id` to the tag
  250. let html = format!("<h{lvl} id=\"{id}\">", lvl = heading_ref.level, id = id);
  251. events[start_idx] = Event::Html(html.into());
  252. // generate anchors and places to insert them
  253. if context.insert_anchor != InsertAnchor::None {
  254. let anchor_idx = match context.insert_anchor {
  255. InsertAnchor::Left => start_idx + 1,
  256. InsertAnchor::Right => end_idx,
  257. InsertAnchor::None => 0, // Not important
  258. };
  259. let mut c = tera::Context::new();
  260. c.insert("id", &id);
  261. let anchor_link = utils::templates::render_template(
  262. &ANCHOR_LINK_TEMPLATE,
  263. context.tera,
  264. c,
  265. &None,
  266. )
  267. .map_err(|e| Error::chain("Failed to render anchor link template", e))?;
  268. anchors_to_insert.push((anchor_idx, Event::Html(anchor_link.into())));
  269. }
  270. // record heading to make table of contents
  271. let permalink = format!("{}#{}", context.current_page_permalink, id);
  272. let h = Heading { level: heading_ref.level, id, permalink, title, children: Vec::new() };
  273. headings.push(h);
  274. }
  275. if context.insert_anchor != InsertAnchor::None {
  276. events.insert_many(anchors_to_insert);
  277. }
  278. cmark::html::push_html(&mut html, events.into_iter());
  279. }
  280. if let Some(e) = error {
  281. Err(e)
  282. } else {
  283. Ok(Rendered {
  284. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  285. body: html,
  286. toc: make_table_of_contents(headings),
  287. internal_links_with_anchors,
  288. external_links,
  289. })
  290. }
  291. }