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.

393 lines
14KB

  1. use lazy_static::lazy_static;
  2. use pulldown_cmark as cmark;
  3. use regex::Regex;
  4. use syntect::easy::HighlightLines;
  5. use syntect::html::{
  6. start_highlighted_html_snippet, styled_line_to_highlighted_html, IncludeBackground,
  7. };
  8. use crate::context::RenderContext;
  9. use crate::table_of_contents::{make_table_of_contents, Heading};
  10. use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET};
  11. use errors::{Error, Result};
  12. use front_matter::InsertAnchor;
  13. use utils::site::resolve_internal_link;
  14. use utils::vec::InsertMany;
  15. use utils::slugs::maybe_slugify_anchors;
  16. use self::cmark::{Event, LinkType, Options, Parser, Tag};
  17. const CONTINUE_READING: &str =
  18. "<p id=\"zola-continue-reading\"><a name=\"continue-reading\"></a></p>\n";
  19. const ANCHOR_LINK_TEMPLATE: &str = "anchor-link.html";
  20. #[derive(Debug)]
  21. pub struct Rendered {
  22. pub body: String,
  23. pub summary_len: Option<usize>,
  24. pub toc: Vec<Heading>,
  25. pub internal_links_with_anchors: Vec<(String, String)>,
  26. pub external_links: Vec<String>,
  27. }
  28. // tracks a heading in a slice of pulldown-cmark events
  29. #[derive(Debug)]
  30. struct HeadingRef {
  31. start_idx: usize,
  32. end_idx: usize,
  33. level: u32,
  34. id: Option<String>,
  35. }
  36. impl HeadingRef {
  37. fn new(start: usize, level: u32) -> HeadingRef {
  38. HeadingRef { start_idx: start, end_idx: 0, level, id: None }
  39. }
  40. }
  41. // We might have cases where the slug is already present in our list of anchor
  42. // for example an article could have several titles named Example
  43. // We add a counter after the slug if the slug is already present, which
  44. // means we will have example, example-1, example-2 etc
  45. fn find_anchor(anchors: &[String], name: String, level: u8) -> String {
  46. if level == 0 && !anchors.contains(&name) {
  47. return name;
  48. }
  49. let new_anchor = format!("{}-{}", name, level + 1);
  50. if !anchors.contains(&new_anchor) {
  51. return new_anchor;
  52. }
  53. find_anchor(anchors, name, level + 1)
  54. }
  55. // Returns whether the given string starts with a schema.
  56. //
  57. // Although there exists [a list of registered URI schemes][uri-schemes], a link may use arbitrary,
  58. // private schemes. This function checks if the given string starts with something that just looks
  59. // like a scheme, i.e., a case-insensitive identifier followed by a colon.
  60. //
  61. // [uri-schemes]: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  62. fn starts_with_schema(s: &str) -> bool {
  63. lazy_static! {
  64. static ref PATTERN: Regex = Regex::new(r"^[0-9A-Za-z\-]+:").unwrap();
  65. }
  66. PATTERN.is_match(s)
  67. }
  68. // Colocated asset links refers to the files in the same directory,
  69. // there it should be a filename only
  70. fn is_colocated_asset_link(link: &str) -> bool {
  71. !link.contains('/') // http://, ftp://, ../ etc
  72. && !starts_with_schema(link)
  73. }
  74. // Returns whether a link starts with an HTTP(s) scheme.
  75. fn is_external_link(link: &str) -> bool {
  76. link.starts_with("http:") || link.starts_with("https:")
  77. }
  78. fn fix_link(
  79. link_type: LinkType,
  80. link: &str,
  81. context: &RenderContext,
  82. internal_links_with_anchors: &mut Vec<(String, String)>,
  83. external_links: &mut Vec<String>,
  84. ) -> Result<String> {
  85. if link_type == LinkType::Email {
  86. return Ok(link.to_string());
  87. }
  88. // TODO: remove me in a few versions when people have upgraded
  89. if link.starts_with("./") && link.contains(".md") {
  90. println!("It looks like the link `{}` is using the previous syntax for internal links: start with @/ instead", link);
  91. }
  92. // A few situations here:
  93. // - it could be a relative link (starting with `@/`)
  94. // - it could be a link to a co-located asset
  95. // - it could be a normal link
  96. let result = if link.starts_with("@/") {
  97. match resolve_internal_link(&link, context.permalinks) {
  98. Ok(resolved) => {
  99. if resolved.anchor.is_some() {
  100. internal_links_with_anchors
  101. .push((resolved.md_path.unwrap(), resolved.anchor.unwrap()));
  102. }
  103. resolved.permalink
  104. }
  105. Err(_) => {
  106. return Err(format!("Relative link {} not found.", link).into());
  107. }
  108. }
  109. } else if is_colocated_asset_link(&link) {
  110. format!("{}{}", context.current_page_permalink, link)
  111. } else {
  112. if is_external_link(link) {
  113. external_links.push(link.to_owned());
  114. }
  115. link.to_string()
  116. };
  117. Ok(result)
  118. }
  119. /// get only text in a slice of events
  120. fn get_text(parser_slice: &[Event]) -> String {
  121. let mut title = String::new();
  122. for event in parser_slice.iter() {
  123. match event {
  124. Event::Text(text) | Event::Code(text) => title += text,
  125. _ => continue,
  126. }
  127. }
  128. title
  129. }
  130. fn get_heading_refs(events: &[Event]) -> Vec<HeadingRef> {
  131. let mut heading_refs = vec![];
  132. for (i, event) in events.iter().enumerate() {
  133. match event {
  134. Event::Start(Tag::Heading(level)) => {
  135. heading_refs.push(HeadingRef::new(i, *level));
  136. }
  137. Event::End(Tag::Heading(_)) => {
  138. let msg = "Heading end before start?";
  139. heading_refs.last_mut().expect(msg).end_idx = i;
  140. }
  141. _ => (),
  142. }
  143. }
  144. heading_refs
  145. }
  146. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Rendered> {
  147. // the rendered html
  148. let mut html = String::with_capacity(content.len());
  149. // Set while parsing
  150. let mut error = None;
  151. let mut background = IncludeBackground::Yes;
  152. let mut highlighter: Option<(HighlightLines, bool)> = None;
  153. let mut inserted_anchors: Vec<String> = vec![];
  154. let mut headings: Vec<Heading> = vec![];
  155. let mut internal_links_with_anchors = Vec::new();
  156. let mut external_links = Vec::new();
  157. let mut opts = Options::empty();
  158. let mut has_summary = false;
  159. opts.insert(Options::ENABLE_TABLES);
  160. opts.insert(Options::ENABLE_FOOTNOTES);
  161. {
  162. let mut events = Parser::new_ext(content, opts)
  163. .map(|event| {
  164. match event {
  165. Event::Text(text) => {
  166. // if we are in the middle of a code block
  167. if let Some((ref mut highlighter, in_extra)) = highlighter {
  168. let highlighted = if in_extra {
  169. if let Some(ref extra) = context.config.extra_syntax_set {
  170. highlighter.highlight(&text, &extra)
  171. } else {
  172. unreachable!(
  173. "Got a highlighter from extra syntaxes but no extra?"
  174. );
  175. }
  176. } else {
  177. highlighter.highlight(&text, &SYNTAX_SET)
  178. };
  179. //let highlighted = &highlighter.highlight(&text, ss);
  180. let html = styled_line_to_highlighted_html(&highlighted, background);
  181. return Event::Html(html.into());
  182. }
  183. // Business as usual
  184. Event::Text(text)
  185. }
  186. Event::Start(Tag::CodeBlock(ref info)) => {
  187. if !context.config.highlight_code {
  188. return Event::Html("<pre><code>".into());
  189. }
  190. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  191. highlighter = Some(get_highlighter(info, &context.config));
  192. // This selects the background color the same way that start_coloured_html_snippet does
  193. let color = theme
  194. .settings
  195. .background
  196. .unwrap_or(::syntect::highlighting::Color::WHITE);
  197. background = IncludeBackground::IfDifferent(color);
  198. let snippet = start_highlighted_html_snippet(theme);
  199. Event::Html(snippet.0.into())
  200. }
  201. Event::End(Tag::CodeBlock(_)) => {
  202. if !context.config.highlight_code {
  203. return Event::Html("</code></pre>\n".into());
  204. }
  205. // reset highlight and close the code block
  206. highlighter = None;
  207. Event::Html("</pre>".into())
  208. }
  209. Event::Start(Tag::Image(link_type, src, title)) => {
  210. if is_colocated_asset_link(&src) {
  211. let link = format!("{}{}", context.current_page_permalink, &*src);
  212. return Event::Start(Tag::Image(link_type, link.into(), title));
  213. }
  214. Event::Start(Tag::Image(link_type, src, title))
  215. }
  216. Event::Start(Tag::Link(link_type, link, title)) => {
  217. let fixed_link = match fix_link(
  218. link_type,
  219. &link,
  220. context,
  221. &mut internal_links_with_anchors,
  222. &mut external_links,
  223. ) {
  224. Ok(fixed_link) => fixed_link,
  225. Err(err) => {
  226. error = Some(err);
  227. return Event::Html("".into());
  228. }
  229. };
  230. Event::Start(Tag::Link(link_type, fixed_link.into(), title))
  231. }
  232. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  233. has_summary = true;
  234. Event::Html(CONTINUE_READING.into())
  235. }
  236. _ => event,
  237. }
  238. })
  239. .collect::<Vec<_>>(); // We need to collect the events to make a second pass
  240. let mut heading_refs = get_heading_refs(&events);
  241. let mut anchors_to_insert = vec![];
  242. // First heading pass: look for a manually-specified IDs, e.g. `# Heading text {#hash}`
  243. // (This is a separate first pass so that auto IDs can avoid collisions with manual IDs.)
  244. for heading_ref in heading_refs.iter_mut() {
  245. let end_idx = heading_ref.end_idx;
  246. if let Event::Text(ref mut text) = events[end_idx - 1] {
  247. if text.as_bytes().last() == Some(&b'}') {
  248. if let Some(mut i) = text.find("{#") {
  249. let id = text[i + 2..text.len() - 1].to_owned();
  250. inserted_anchors.push(id.clone());
  251. while i > 0 && text.as_bytes()[i - 1] == b' ' {
  252. i -= 1;
  253. }
  254. heading_ref.id = Some(id);
  255. *text = text[..i].to_owned().into();
  256. }
  257. }
  258. }
  259. }
  260. // Second heading pass: auto-generate remaining IDs, and emit HTML
  261. for heading_ref in heading_refs {
  262. let start_idx = heading_ref.start_idx;
  263. let end_idx = heading_ref.end_idx;
  264. let title = get_text(&events[start_idx + 1..end_idx]);
  265. let id = heading_ref
  266. .id
  267. .unwrap_or_else(|| find_anchor(&inserted_anchors, maybe_slugify_anchors(&title, context.config.slugify_paths), 0));
  268. inserted_anchors.push(id.clone());
  269. // insert `id` to the tag
  270. let html = format!("<h{lvl} id=\"{id}\">", lvl = heading_ref.level, id = id);
  271. events[start_idx] = Event::Html(html.into());
  272. // generate anchors and places to insert them
  273. if context.insert_anchor != InsertAnchor::None {
  274. let anchor_idx = match context.insert_anchor {
  275. InsertAnchor::Left => start_idx + 1,
  276. InsertAnchor::Right => end_idx,
  277. InsertAnchor::None => 0, // Not important
  278. };
  279. let mut c = tera::Context::new();
  280. c.insert("id", &id);
  281. let anchor_link = utils::templates::render_template(
  282. &ANCHOR_LINK_TEMPLATE,
  283. context.tera,
  284. c,
  285. &None,
  286. )
  287. .map_err(|e| Error::chain("Failed to render anchor link template", e))?;
  288. anchors_to_insert.push((anchor_idx, Event::Html(anchor_link.into())));
  289. }
  290. // record heading to make table of contents
  291. let permalink = format!("{}#{}", context.current_page_permalink, id);
  292. let h =
  293. Heading { level: heading_ref.level, id, permalink, title, children: Vec::new() };
  294. headings.push(h);
  295. }
  296. if context.insert_anchor != InsertAnchor::None {
  297. events.insert_many(anchors_to_insert);
  298. }
  299. cmark::html::push_html(&mut html, events.into_iter());
  300. }
  301. if let Some(e) = error {
  302. Err(e)
  303. } else {
  304. Ok(Rendered {
  305. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  306. body: html,
  307. toc: make_table_of_contents(headings),
  308. internal_links_with_anchors,
  309. external_links,
  310. })
  311. }
  312. }
  313. #[cfg(test)]
  314. mod tests {
  315. use super::*;
  316. #[test]
  317. fn test_starts_with_schema() {
  318. // registered
  319. assert!(starts_with_schema("https://example.com/"));
  320. assert!(starts_with_schema("ftp://example.com/"));
  321. assert!(starts_with_schema("mailto:user@example.com"));
  322. assert!(starts_with_schema("xmpp:node@example.com"));
  323. assert!(starts_with_schema("tel:18008675309"));
  324. assert!(starts_with_schema("sms:18008675309"));
  325. assert!(starts_with_schema("h323:user@example.com"));
  326. // arbitrary
  327. assert!(starts_with_schema("zola:post?content=hi"));
  328. // case-insensitive
  329. assert!(starts_with_schema("MailTo:user@example.com"));
  330. assert!(starts_with_schema("MAILTO:user@example.com"));
  331. }
  332. #[test]
  333. fn test_is_external_link() {
  334. assert!(is_external_link("http://example.com/"));
  335. assert!(is_external_link("https://example.com/"));
  336. assert!(is_external_link("https://example.com/index.html#introduction"));
  337. assert!(!is_external_link("mailto:user@example.com"));
  338. assert!(!is_external_link("tel:18008675309"));
  339. assert!(!is_external_link("#introduction"));
  340. assert!(!is_external_link("http.jpg"))
  341. }
  342. }