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.

308 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 link_checker::check_url;
  12. use table_of_contents::{make_table_of_contents, Header};
  13. use utils::site::resolve_internal_link;
  14. use utils::vec::InsertMany;
  15. use self::cmark::{Event, LinkType, Options, Parser, Tag};
  16. const CONTINUE_READING: &str =
  17. "<p id=\"zola-continue-reading\"><a name=\"continue-reading\"></a></p>\n";
  18. const ANCHOR_LINK_TEMPLATE: &str = "anchor-link.html";
  19. #[derive(Debug)]
  20. pub struct Rendered {
  21. pub body: String,
  22. pub summary_len: Option<usize>,
  23. pub toc: Vec<Header>,
  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) -> 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 if context.config.check_external_links
  76. && !link.starts_with('#')
  77. && !link.starts_with("mailto:")
  78. {
  79. let res = check_url(&link);
  80. if res.is_valid() {
  81. link.to_string()
  82. } else {
  83. return Err(format!("Link {} is not valid: {}", link, res.message()).into());
  84. }
  85. } else {
  86. link.to_string()
  87. };
  88. Ok(result)
  89. }
  90. /// get only text in a slice of events
  91. fn get_text(parser_slice: &[Event]) -> String {
  92. let mut title = String::new();
  93. for event in parser_slice.iter() {
  94. if let Event::Text(text) = event {
  95. title += text;
  96. }
  97. }
  98. title
  99. }
  100. fn get_header_refs(events: &[Event]) -> Vec<HeaderRef> {
  101. let mut header_refs = vec![];
  102. for (i, event) in events.iter().enumerate() {
  103. match event {
  104. Event::Start(Tag::Header(level)) => {
  105. header_refs.push(HeaderRef::new(i, *level));
  106. }
  107. Event::End(Tag::Header(_)) => {
  108. let msg = "Header end before start?";
  109. header_refs.last_mut().expect(msg).end_idx = i;
  110. }
  111. _ => (),
  112. }
  113. }
  114. header_refs
  115. }
  116. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Rendered> {
  117. // the rendered html
  118. let mut html = String::with_capacity(content.len());
  119. // Set while parsing
  120. let mut error = None;
  121. let mut background = IncludeBackground::Yes;
  122. let mut highlighter: Option<(HighlightLines, bool)> = None;
  123. let mut inserted_anchors: Vec<String> = vec![];
  124. let mut headers: Vec<Header> = vec![];
  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 = match fix_link(link_type, &link, context) {
  186. Ok(fixed_link) => fixed_link,
  187. Err(err) => {
  188. error = Some(err);
  189. return Event::Html("".into());
  190. }
  191. };
  192. Event::Start(Tag::Link(link_type, fixed_link.into(), title))
  193. }
  194. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  195. has_summary = true;
  196. Event::Html(CONTINUE_READING.into())
  197. }
  198. _ => event,
  199. }
  200. })
  201. .collect::<Vec<_>>(); // We need to collect the events to make a second pass
  202. let mut header_refs = get_header_refs(&events);
  203. let mut anchors_to_insert = vec![];
  204. // First header pass: look for a manually-specified IDs, e.g. `# Heading text {#hash}`
  205. // (This is a separate first pass so that auto IDs can avoid collisions with manual IDs.)
  206. for header_ref in header_refs.iter_mut() {
  207. let end_idx = header_ref.end_idx;
  208. if let Event::Text(ref mut text) = events[end_idx - 1] {
  209. if text.as_bytes().last() == Some(&b'}') {
  210. if let Some(mut i) = text.find("{#") {
  211. let id = text[i + 2..text.len() - 1].to_owned();
  212. inserted_anchors.push(id.clone());
  213. while i > 0 && text.as_bytes()[i - 1] == b' ' {
  214. i -= 1;
  215. }
  216. header_ref.id = Some(id);
  217. *text = text[..i].to_owned().into();
  218. }
  219. }
  220. }
  221. }
  222. // Second header pass: auto-generate remaining IDs, and emit HTML
  223. for header_ref in header_refs {
  224. let start_idx = header_ref.start_idx;
  225. let end_idx = header_ref.end_idx;
  226. let title = get_text(&events[start_idx + 1..end_idx]);
  227. let id = header_ref.id.unwrap_or_else(
  228. || find_anchor(&inserted_anchors, slugify(&title), 0));
  229. inserted_anchors.push(id.clone());
  230. // insert `id` to the tag
  231. let html = format!("<h{lvl} id=\"{id}\">", lvl = header_ref.level, id = id);
  232. events[start_idx] = Event::Html(html.into());
  233. // generate anchors and places to insert them
  234. if context.insert_anchor != InsertAnchor::None {
  235. let anchor_idx = match context.insert_anchor {
  236. InsertAnchor::Left => start_idx + 1,
  237. InsertAnchor::Right => end_idx,
  238. InsertAnchor::None => 0, // Not important
  239. };
  240. let mut c = tera::Context::new();
  241. c.insert("id", &id);
  242. let anchor_link = utils::templates::render_template(
  243. &ANCHOR_LINK_TEMPLATE,
  244. context.tera,
  245. c,
  246. &None,
  247. )
  248. .map_err(|e| Error::chain("Failed to render anchor link template", e))?;
  249. anchors_to_insert.push((anchor_idx, Event::Html(anchor_link.into())));
  250. }
  251. // record header to make table of contents
  252. let permalink = format!("{}#{}", context.current_page_permalink, id);
  253. let h = Header { level: header_ref.level, id, permalink, title, children: Vec::new() };
  254. headers.push(h);
  255. }
  256. if context.insert_anchor != InsertAnchor::None {
  257. events.insert_many(anchors_to_insert);
  258. }
  259. cmark::html::push_html(&mut html, events.into_iter());
  260. }
  261. if let Some(e) = error {
  262. return Err(e);
  263. } else {
  264. Ok(Rendered {
  265. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  266. body: html,
  267. toc: make_table_of_contents(headers),
  268. })
  269. }
  270. }