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.

402 lines
15KB

  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::slugs::maybe_slugify_anchors;
  15. use utils::vec::InsertMany;
  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. opts.insert(Options::ENABLE_STRIKETHROUGH);
  162. {
  163. let mut events = Parser::new_ext(content, opts)
  164. .map(|event| {
  165. match event {
  166. Event::Text(text) => {
  167. // if we are in the middle of a code block
  168. if let Some((ref mut highlighter, in_extra)) = highlighter {
  169. let highlighted = if in_extra {
  170. if let Some(ref extra) = context.config.extra_syntax_set {
  171. highlighter.highlight(&text, &extra)
  172. } else {
  173. unreachable!(
  174. "Got a highlighter from extra syntaxes but no extra?"
  175. );
  176. }
  177. } else {
  178. highlighter.highlight(&text, &SYNTAX_SET)
  179. };
  180. //let highlighted = &highlighter.highlight(&text, ss);
  181. let html = styled_line_to_highlighted_html(&highlighted, background);
  182. return Event::Html(html.into());
  183. }
  184. // Business as usual
  185. Event::Text(text)
  186. }
  187. Event::Start(Tag::CodeBlock(ref info)) => {
  188. if !context.config.highlight_code {
  189. return Event::Html("<pre><code>".into());
  190. }
  191. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  192. highlighter = Some(get_highlighter(info, &context.config));
  193. // This selects the background color the same way that start_coloured_html_snippet does
  194. let color = theme
  195. .settings
  196. .background
  197. .unwrap_or(::syntect::highlighting::Color::WHITE);
  198. background = IncludeBackground::IfDifferent(color);
  199. let snippet = start_highlighted_html_snippet(theme);
  200. Event::Html(snippet.0.into())
  201. }
  202. Event::End(Tag::CodeBlock(_)) => {
  203. if !context.config.highlight_code {
  204. return Event::Html("</code></pre>\n".into());
  205. }
  206. // reset highlight and close the code block
  207. highlighter = None;
  208. Event::Html("</pre>".into())
  209. }
  210. Event::Start(Tag::Image(link_type, src, title)) => {
  211. if is_colocated_asset_link(&src) {
  212. let link = format!("{}{}", context.current_page_permalink, &*src);
  213. return Event::Start(Tag::Image(link_type, link.into(), title));
  214. }
  215. Event::Start(Tag::Image(link_type, src, title))
  216. }
  217. Event::Start(Tag::Link(link_type, link, title)) if link.is_empty() => {
  218. error = Some(Error::msg("There is a link that is missing a URL"));
  219. Event::Start(Tag::Link(link_type, "#".into(), title))
  220. }
  221. Event::Start(Tag::Link(link_type, link, title)) => {
  222. let fixed_link = match fix_link(
  223. link_type,
  224. &link,
  225. context,
  226. &mut internal_links_with_anchors,
  227. &mut external_links,
  228. ) {
  229. Ok(fixed_link) => fixed_link,
  230. Err(err) => {
  231. error = Some(err);
  232. return Event::Html("".into());
  233. }
  234. };
  235. Event::Start(Tag::Link(link_type, fixed_link.into(), title))
  236. }
  237. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  238. has_summary = true;
  239. Event::Html(CONTINUE_READING.into())
  240. }
  241. _ => event,
  242. }
  243. })
  244. .collect::<Vec<_>>(); // We need to collect the events to make a second pass
  245. let mut heading_refs = get_heading_refs(&events);
  246. let mut anchors_to_insert = vec![];
  247. // First heading pass: look for a manually-specified IDs, e.g. `# Heading text {#hash}`
  248. // (This is a separate first pass so that auto IDs can avoid collisions with manual IDs.)
  249. for heading_ref in heading_refs.iter_mut() {
  250. let end_idx = heading_ref.end_idx;
  251. if let Event::Text(ref mut text) = events[end_idx - 1] {
  252. if text.as_bytes().last() == Some(&b'}') {
  253. if let Some(mut i) = text.find("{#") {
  254. let id = text[i + 2..text.len() - 1].to_owned();
  255. inserted_anchors.push(id.clone());
  256. while i > 0 && text.as_bytes()[i - 1] == b' ' {
  257. i -= 1;
  258. }
  259. heading_ref.id = Some(id);
  260. *text = text[..i].to_owned().into();
  261. }
  262. }
  263. }
  264. }
  265. // Second heading pass: auto-generate remaining IDs, and emit HTML
  266. for heading_ref in heading_refs {
  267. let start_idx = heading_ref.start_idx;
  268. let end_idx = heading_ref.end_idx;
  269. let title = get_text(&events[start_idx + 1..end_idx]);
  270. let id = heading_ref.id.unwrap_or_else(|| {
  271. find_anchor(
  272. &inserted_anchors,
  273. maybe_slugify_anchors(&title, context.config.slugify_paths),
  274. 0,
  275. )
  276. });
  277. inserted_anchors.push(id.clone());
  278. // insert `id` to the tag
  279. let html = format!("<h{lvl} id=\"{id}\">", lvl = heading_ref.level, id = id);
  280. events[start_idx] = Event::Html(html.into());
  281. // generate anchors and places to insert them
  282. if context.insert_anchor != InsertAnchor::None {
  283. let anchor_idx = match context.insert_anchor {
  284. InsertAnchor::Left => start_idx + 1,
  285. InsertAnchor::Right => end_idx,
  286. InsertAnchor::None => 0, // Not important
  287. };
  288. let mut c = tera::Context::new();
  289. c.insert("id", &id);
  290. let anchor_link = utils::templates::render_template(
  291. &ANCHOR_LINK_TEMPLATE,
  292. context.tera,
  293. c,
  294. &None,
  295. )
  296. .map_err(|e| Error::chain("Failed to render anchor link template", e))?;
  297. anchors_to_insert.push((anchor_idx, Event::Html(anchor_link.into())));
  298. }
  299. // record heading to make table of contents
  300. let permalink = format!("{}#{}", context.current_page_permalink, id);
  301. let h =
  302. Heading { level: heading_ref.level, id, permalink, title, children: Vec::new() };
  303. headings.push(h);
  304. }
  305. if context.insert_anchor != InsertAnchor::None {
  306. events.insert_many(anchors_to_insert);
  307. }
  308. cmark::html::push_html(&mut html, events.into_iter());
  309. }
  310. if let Some(e) = error {
  311. Err(e)
  312. } else {
  313. Ok(Rendered {
  314. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  315. body: html,
  316. toc: make_table_of_contents(headings),
  317. internal_links_with_anchors,
  318. external_links,
  319. })
  320. }
  321. }
  322. #[cfg(test)]
  323. mod tests {
  324. use super::*;
  325. #[test]
  326. fn test_starts_with_schema() {
  327. // registered
  328. assert!(starts_with_schema("https://example.com/"));
  329. assert!(starts_with_schema("ftp://example.com/"));
  330. assert!(starts_with_schema("mailto:user@example.com"));
  331. assert!(starts_with_schema("xmpp:node@example.com"));
  332. assert!(starts_with_schema("tel:18008675309"));
  333. assert!(starts_with_schema("sms:18008675309"));
  334. assert!(starts_with_schema("h323:user@example.com"));
  335. // arbitrary
  336. assert!(starts_with_schema("zola:post?content=hi"));
  337. // case-insensitive
  338. assert!(starts_with_schema("MailTo:user@example.com"));
  339. assert!(starts_with_schema("MAILTO:user@example.com"));
  340. }
  341. #[test]
  342. fn test_is_external_link() {
  343. assert!(is_external_link("http://example.com/"));
  344. assert!(is_external_link("https://example.com/"));
  345. assert!(is_external_link("https://example.com/index.html#introduction"));
  346. assert!(!is_external_link("mailto:user@example.com"));
  347. assert!(!is_external_link("tel:18008675309"));
  348. assert!(!is_external_link("#introduction"));
  349. assert!(!is_external_link("http.jpg"))
  350. }
  351. }