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.

273 lines
9.7KB

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