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.

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