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.

303 lines
11KB

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