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.

markdown.rs 10KB

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