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.

277 lines
9.9KB

  1. use std::borrow::Cow::{Borrowed, Owned};
  2. use pulldown_cmark as cmark;
  3. use slug::slugify;
  4. use syntect::easy::HighlightLines;
  5. use syntect::html::{
  6. IncludeBackground, start_highlighted_html_snippet, styled_line_to_highlighted_html,
  7. };
  8. use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET};
  9. use context::RenderContext;
  10. use errors::{Error, Result};
  11. use front_matter::InsertAnchor;
  12. use link_checker::check_url;
  13. use table_of_contents::{Header, make_table_of_contents, TempHeader};
  14. use utils::site::resolve_internal_link;
  15. use utils::vec::InsertMany;
  16. use self::cmark::{Event, Options, Parser, Tag};
  17. const CONTINUE_READING: &str = "<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. }
  32. impl HeaderRef {
  33. fn new(start: usize, level: i32) -> HeaderRef {
  34. HeaderRef { start_idx: start, end_idx: 0, level }
  35. }
  36. }
  37. // We might have cases where the slug is already present in our list of anchor
  38. // for example an article could have several titles named Example
  39. // We add a counter after the slug if the slug is already present, which
  40. // means we will have example, example-1, example-2 etc
  41. fn find_anchor(anchors: &[String], name: String, level: u8) -> String {
  42. if level == 0 && !anchors.contains(&name) {
  43. return name;
  44. }
  45. let new_anchor = format!("{}-{}", name, level + 1);
  46. if !anchors.contains(&new_anchor) {
  47. return new_anchor;
  48. }
  49. find_anchor(anchors, name, level + 1)
  50. }
  51. // Colocated asset links refers to the files in the same directory,
  52. // there it should be a filename only
  53. fn is_colocated_asset_link(link: &str) -> bool {
  54. !link.contains('/') // http://, ftp://, ../ etc
  55. && !link.starts_with("mailto:")
  56. }
  57. fn fix_link(link: &str, context: &RenderContext) -> Result<String> {
  58. // A few situations here:
  59. // - it could be a relative link (starting with `./`)
  60. // - it could be a link to a co-located asset
  61. // - it could be a normal link
  62. let result = if link.starts_with("./") {
  63. match resolve_internal_link(&link, context.permalinks) {
  64. Ok(url) => url,
  65. Err(_) => {
  66. return Err(format!("Relative link {} not found.", link).into());
  67. }
  68. }
  69. } else if is_colocated_asset_link(&link) {
  70. format!("{}{}", context.current_page_permalink, link)
  71. } else if context.config.check_external_links
  72. && !link.starts_with('#')
  73. && !link.starts_with("mailto:")
  74. {
  75. let res = check_url(&link);
  76. if res.is_valid() {
  77. link.to_string()
  78. } else {
  79. return Err(
  80. format!("Link {} is not valid: {}", link, res.message()).into(),
  81. );
  82. }
  83. } else {
  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. if let Event::Text(text) = event {
  93. title += text;
  94. }
  95. }
  96. title
  97. }
  98. fn get_header_refs(events: &[Event]) -> Vec<HeaderRef> {
  99. let mut header_refs = vec![];
  100. for (i, event) in events.iter().enumerate() {
  101. match event {
  102. Event::Start(Tag::Header(level)) => {
  103. header_refs.push(HeaderRef::new(i, *level));
  104. }
  105. Event::End(Tag::Header(_)) => {
  106. let msg = "Header end before start?";
  107. header_refs.last_mut().expect(msg).end_idx = i;
  108. }
  109. _ => (),
  110. }
  111. }
  112. header_refs
  113. }
  114. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Rendered> {
  115. // the rendered html
  116. let mut html = String::with_capacity(content.len());
  117. // Set while parsing
  118. let mut error = None;
  119. let mut background = IncludeBackground::Yes;
  120. let mut highlighter: Option<(HighlightLines, bool)> = None;
  121. let mut inserted_anchors: Vec<String> = vec![];
  122. let mut headers: Vec<TempHeader> = vec![];
  123. let mut opts = Options::empty();
  124. let mut has_summary = false;
  125. opts.insert(Options::ENABLE_TABLES);
  126. opts.insert(Options::ENABLE_FOOTNOTES);
  127. {
  128. let mut events = Parser::new_ext(content, opts).map(|event| {
  129. match event {
  130. Event::Text(text) => {
  131. // if we are in the middle of a code block
  132. if let Some((ref mut highlighter, in_extra)) = highlighter {
  133. let highlighted = if in_extra {
  134. if let Some(ref extra) = context.config.extra_syntax_set {
  135. highlighter.highlight(&text, &extra)
  136. } else {
  137. unreachable!("Got a highlighter from extra syntaxes but no extra?");
  138. }
  139. } else {
  140. highlighter.highlight(&text, &SYNTAX_SET)
  141. };
  142. //let highlighted = &highlighter.highlight(&text, ss);
  143. let html = styled_line_to_highlighted_html(&highlighted, background);
  144. return Event::Html(Owned(html));
  145. }
  146. // Business as usual
  147. Event::Text(text)
  148. }
  149. Event::Start(Tag::CodeBlock(ref info)) => {
  150. if !context.config.highlight_code {
  151. return Event::Html(Borrowed("<pre><code>"));
  152. }
  153. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  154. highlighter = Some(get_highlighter(info, &context.config));
  155. // This selects the background color the same way that start_coloured_html_snippet does
  156. let color =
  157. theme.settings.background.unwrap_or(::syntect::highlighting::Color::WHITE);
  158. background = IncludeBackground::IfDifferent(color);
  159. let snippet = start_highlighted_html_snippet(theme);
  160. Event::Html(Owned(snippet.0))
  161. }
  162. Event::End(Tag::CodeBlock(_)) => {
  163. if !context.config.highlight_code {
  164. return Event::Html(Borrowed("</code></pre>\n"));
  165. }
  166. // reset highlight and close the code block
  167. highlighter = None;
  168. Event::Html(Borrowed("</pre>"))
  169. }
  170. Event::Start(Tag::Image(src, title)) => {
  171. if is_colocated_asset_link(&src) {
  172. return Event::Start(Tag::Image(
  173. Owned(format!("{}{}", context.current_page_permalink, src)),
  174. title,
  175. ));
  176. }
  177. Event::Start(Tag::Image(src, title))
  178. }
  179. Event::Start(Tag::Link(link, title)) => {
  180. let fixed_link = match fix_link(&link, context) {
  181. Ok(fixed_link) => fixed_link,
  182. Err(err) => {
  183. error = Some(err);
  184. return Event::Html(Borrowed(""))
  185. }
  186. };
  187. Event::Start(Tag::Link(Owned(fixed_link), title))
  188. }
  189. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  190. has_summary = true;
  191. Event::Html(Borrowed(CONTINUE_READING))
  192. }
  193. _ => event,
  194. }
  195. }).collect::<Vec<_>>(); // We need to collect the events to make a second pass
  196. let header_refs = get_header_refs(&events);
  197. let mut anchors_to_insert = vec![];
  198. for header_ref in header_refs {
  199. let start_idx = header_ref.start_idx;
  200. let end_idx = header_ref.end_idx;
  201. let title = get_text(&events[start_idx + 1 .. end_idx]);
  202. let id = find_anchor(&inserted_anchors, slugify(&title), 0);
  203. inserted_anchors.push(id.clone());
  204. // insert `id` to the tag
  205. let html = format!("<h{lvl} id=\"{id}\">", lvl = header_ref.level, id = id);
  206. events[start_idx] = Event::Html(Owned(html));
  207. // generate anchors and places to insert them
  208. if context.insert_anchor != InsertAnchor::None {
  209. let anchor_idx = match context.insert_anchor {
  210. InsertAnchor::Left => start_idx + 1,
  211. InsertAnchor::Right => end_idx,
  212. InsertAnchor::None => 0, // Not important
  213. };
  214. let mut c = tera::Context::new();
  215. c.insert("id", &id);
  216. let anchor_link = utils::templates::render_template(&ANCHOR_LINK_TEMPLATE, context.tera, c, &None)
  217. .map_err(|e| Error::chain("Failed to render anchor link template", e))?;
  218. anchors_to_insert.push((anchor_idx, Event::Html(Owned(anchor_link))));
  219. }
  220. // record header to make table of contents
  221. let permalink = format!("{}#{}", context.current_page_permalink, id);
  222. let temp_header = TempHeader { level: header_ref.level, id, permalink, title };
  223. headers.push(temp_header);
  224. }
  225. if context.insert_anchor != InsertAnchor::None {
  226. events.insert_many(anchors_to_insert);
  227. }
  228. cmark::html::push_html(&mut html, events.into_iter());
  229. }
  230. if let Some(e) = error {
  231. return Err(e);
  232. } else {
  233. Ok(Rendered {
  234. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  235. body: html,
  236. toc: make_table_of_contents(&headers),
  237. })
  238. }
  239. }