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.

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