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 15KB

5 years ago
5 years ago
7 years ago
5 years ago
5 years ago
Allow manual specification of header IDs (#685) Justification for this feature is added in the docs. Precedent for the precise syntax: Hugo. Hugo puts this syntax behind a preference named headerIds, and automatic header ID generation behind a preference named autoHeaderIds, with both enabled by default. I have not implemented a switch to disable this. My suggestion for a workaround for the improbable case of desiring a literal “{#…}” at the end of a header is to replace `}` with `&#125;`. The algorithm I have used is not identical to [that which Hugo uses][0], because Hugo’s looks to work at the source level, whereas here we work at the pulldown-cmark event level, which is generally more sane, but potentially limiting for extremely esoteric IDs. Practical differences in implementation from Hugo (based purely on reading [blackfriday’s implementation][0], not actually trying it): - I believe Hugo would treat `# Foo {#*bar*}` as a heading with text “Foo” and ID `*bar*`, since it is working at the source level; whereas this code turns it into a heading with HTML `Foo {#<em>bar</em>}`, as it works at the pulldown-cmark event level and doesn’t go out of its way to make that work (I’m not familiar with pulldown-cmark, but I get the impression that you could make it work Hugo’s way on this point). The difference should be negligible: only *very* esoteric hashes would include magic Markdown characters. - Hugo will automatically generate an ID for `{#}`, whereas what I’ve coded here will yield a blank ID instead (which feels more correct to me—`None` versus `Some("")`, and all that). In practice the results should be identical. Fixes #433. [0]: https://github.com/russross/blackfriday/blob/a477dd1646916742841ed20379f941cfa6c5bb6f/block.go#L218-L234
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
Allow manual specification of header IDs (#685) Justification for this feature is added in the docs. Precedent for the precise syntax: Hugo. Hugo puts this syntax behind a preference named headerIds, and automatic header ID generation behind a preference named autoHeaderIds, with both enabled by default. I have not implemented a switch to disable this. My suggestion for a workaround for the improbable case of desiring a literal “{#…}” at the end of a header is to replace `}` with `&#125;`. The algorithm I have used is not identical to [that which Hugo uses][0], because Hugo’s looks to work at the source level, whereas here we work at the pulldown-cmark event level, which is generally more sane, but potentially limiting for extremely esoteric IDs. Practical differences in implementation from Hugo (based purely on reading [blackfriday’s implementation][0], not actually trying it): - I believe Hugo would treat `# Foo {#*bar*}` as a heading with text “Foo” and ID `*bar*`, since it is working at the source level; whereas this code turns it into a heading with HTML `Foo {#<em>bar</em>}`, as it works at the pulldown-cmark event level and doesn’t go out of its way to make that work (I’m not familiar with pulldown-cmark, but I get the impression that you could make it work Hugo’s way on this point). The difference should be negligible: only *very* esoteric hashes would include magic Markdown characters. - Hugo will automatically generate an ID for `{#}`, whereas what I’ve coded here will yield a blank ID instead (which feels more correct to me—`None` versus `Some("")`, and all that). In practice the results should be identical. Fixes #433. [0]: https://github.com/russross/blackfriday/blob/a477dd1646916742841ed20379f941cfa6c5bb6f/block.go#L218-L234
5 years ago
Allow manual specification of header IDs (#685) Justification for this feature is added in the docs. Precedent for the precise syntax: Hugo. Hugo puts this syntax behind a preference named headerIds, and automatic header ID generation behind a preference named autoHeaderIds, with both enabled by default. I have not implemented a switch to disable this. My suggestion for a workaround for the improbable case of desiring a literal “{#…}” at the end of a header is to replace `}` with `&#125;`. The algorithm I have used is not identical to [that which Hugo uses][0], because Hugo’s looks to work at the source level, whereas here we work at the pulldown-cmark event level, which is generally more sane, but potentially limiting for extremely esoteric IDs. Practical differences in implementation from Hugo (based purely on reading [blackfriday’s implementation][0], not actually trying it): - I believe Hugo would treat `# Foo {#*bar*}` as a heading with text “Foo” and ID `*bar*`, since it is working at the source level; whereas this code turns it into a heading with HTML `Foo {#<em>bar</em>}`, as it works at the pulldown-cmark event level and doesn’t go out of its way to make that work (I’m not familiar with pulldown-cmark, but I get the impression that you could make it work Hugo’s way on this point). The difference should be negligible: only *very* esoteric hashes would include magic Markdown characters. - Hugo will automatically generate an ID for `{#}`, whereas what I’ve coded here will yield a blank ID instead (which feels more correct to me—`None` versus `Some("")`, and all that). In practice the results should be identical. Fixes #433. [0]: https://github.com/russross/blackfriday/blob/a477dd1646916742841ed20379f941cfa6c5bb6f/block.go#L218-L234
5 years ago
Allow manual specification of header IDs (#685) Justification for this feature is added in the docs. Precedent for the precise syntax: Hugo. Hugo puts this syntax behind a preference named headerIds, and automatic header ID generation behind a preference named autoHeaderIds, with both enabled by default. I have not implemented a switch to disable this. My suggestion for a workaround for the improbable case of desiring a literal “{#…}” at the end of a header is to replace `}` with `&#125;`. The algorithm I have used is not identical to [that which Hugo uses][0], because Hugo’s looks to work at the source level, whereas here we work at the pulldown-cmark event level, which is generally more sane, but potentially limiting for extremely esoteric IDs. Practical differences in implementation from Hugo (based purely on reading [blackfriday’s implementation][0], not actually trying it): - I believe Hugo would treat `# Foo {#*bar*}` as a heading with text “Foo” and ID `*bar*`, since it is working at the source level; whereas this code turns it into a heading with HTML `Foo {#<em>bar</em>}`, as it works at the pulldown-cmark event level and doesn’t go out of its way to make that work (I’m not familiar with pulldown-cmark, but I get the impression that you could make it work Hugo’s way on this point). The difference should be negligible: only *very* esoteric hashes would include magic Markdown characters. - Hugo will automatically generate an ID for `{#}`, whereas what I’ve coded here will yield a blank ID instead (which feels more correct to me—`None` versus `Some("")`, and all that). In practice the results should be identical. Fixes #433. [0]: https://github.com/russross/blackfriday/blob/a477dd1646916742841ed20379f941cfa6c5bb6f/block.go#L218-L234
5 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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::slugify_anchors;
  15. use utils::vec::InsertMany;
  16. use self::cmark::{Event, LinkType, Options, Parser, Tag};
  17. const CONTINUE_READING: &str = "<span id=\"continue-reading\"></span>";
  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<Heading>,
  24. pub internal_links_with_anchors: Vec<(String, String)>,
  25. pub external_links: Vec<String>,
  26. }
  27. // tracks a heading in a slice of pulldown-cmark events
  28. #[derive(Debug)]
  29. struct HeadingRef {
  30. start_idx: usize,
  31. end_idx: usize,
  32. level: u32,
  33. id: Option<String>,
  34. }
  35. impl HeadingRef {
  36. fn new(start: usize, level: u32) -> HeadingRef {
  37. HeadingRef { start_idx: start, end_idx: 0, level, id: None }
  38. }
  39. }
  40. // We might have cases where the slug is already present in our list of anchor
  41. // for example an article could have several titles named Example
  42. // We add a counter after the slug if the slug is already present, which
  43. // means we will have example, example-1, example-2 etc
  44. fn find_anchor(anchors: &[String], name: String, level: u8) -> String {
  45. if level == 0 && !anchors.contains(&name) {
  46. return name;
  47. }
  48. let new_anchor = format!("{}-{}", name, level + 1);
  49. if !anchors.contains(&new_anchor) {
  50. return new_anchor;
  51. }
  52. find_anchor(anchors, name, level + 1)
  53. }
  54. // Returns whether the given string starts with a schema.
  55. //
  56. // Although there exists [a list of registered URI schemes][uri-schemes], a link may use arbitrary,
  57. // private schemes. This function checks if the given string starts with something that just looks
  58. // like a scheme, i.e., a case-insensitive identifier followed by a colon.
  59. //
  60. // [uri-schemes]: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  61. fn starts_with_schema(s: &str) -> bool {
  62. lazy_static! {
  63. static ref PATTERN: Regex = Regex::new(r"^[0-9A-Za-z\-]+:").unwrap();
  64. }
  65. PATTERN.is_match(s)
  66. }
  67. // Colocated asset links refers to the files in the same directory,
  68. // there it should be a filename only
  69. fn is_colocated_asset_link(link: &str) -> bool {
  70. !link.contains('/') // http://, ftp://, ../ etc
  71. && !starts_with_schema(link)
  72. }
  73. // Returns whether a link starts with an HTTP(s) scheme.
  74. fn is_external_link(link: &str) -> bool {
  75. link.starts_with("http:") || link.starts_with("https:")
  76. }
  77. fn fix_link(
  78. link_type: LinkType,
  79. link: &str,
  80. context: &RenderContext,
  81. internal_links_with_anchors: &mut Vec<(String, String)>,
  82. external_links: &mut Vec<String>,
  83. ) -> Result<String> {
  84. if link_type == LinkType::Email {
  85. return Ok(link.to_string());
  86. }
  87. // TODO: remove me in a few versions when people have upgraded
  88. if link.starts_with("./") && link.contains(".md") {
  89. println!("It looks like the link `{}` is using the previous syntax for internal links: start with @/ instead", link);
  90. }
  91. // A few situations here:
  92. // - it could be a relative link (starting with `@/`)
  93. // - it could be a link to a co-located asset
  94. // - it could be a normal link
  95. let result = if link.starts_with("@/") {
  96. match resolve_internal_link(&link, context.permalinks) {
  97. Ok(resolved) => {
  98. if resolved.anchor.is_some() {
  99. internal_links_with_anchors
  100. .push((resolved.md_path.unwrap(), resolved.anchor.unwrap()));
  101. }
  102. resolved.permalink
  103. }
  104. Err(_) => {
  105. return Err(format!("Relative link {} not found.", link).into());
  106. }
  107. }
  108. } else if is_colocated_asset_link(&link) {
  109. format!("{}{}", context.current_page_permalink, link)
  110. } else {
  111. if is_external_link(link) {
  112. external_links.push(link.to_owned());
  113. }
  114. link.to_string()
  115. };
  116. Ok(result)
  117. }
  118. /// get only text in a slice of events
  119. fn get_text(parser_slice: &[Event]) -> String {
  120. let mut title = String::new();
  121. for event in parser_slice.iter() {
  122. match event {
  123. Event::Text(text) | Event::Code(text) => title += text,
  124. _ => continue,
  125. }
  126. }
  127. title
  128. }
  129. fn get_heading_refs(events: &[Event]) -> Vec<HeadingRef> {
  130. let mut heading_refs = vec![];
  131. for (i, event) in events.iter().enumerate() {
  132. match event {
  133. Event::Start(Tag::Heading(level)) => {
  134. heading_refs.push(HeadingRef::new(i, *level));
  135. }
  136. Event::End(Tag::Heading(_)) => {
  137. let msg = "Heading end before start?";
  138. heading_refs.last_mut().expect(msg).end_idx = i;
  139. }
  140. _ => (),
  141. }
  142. }
  143. heading_refs
  144. }
  145. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Rendered> {
  146. // the rendered html
  147. let mut html = String::with_capacity(content.len());
  148. // Set while parsing
  149. let mut error = None;
  150. let mut background = IncludeBackground::Yes;
  151. let mut highlighter: Option<(HighlightLines, bool)> = None;
  152. let mut inserted_anchors: Vec<String> = vec![];
  153. let mut headings: Vec<Heading> = vec![];
  154. let mut internal_links_with_anchors = Vec::new();
  155. let mut external_links = Vec::new();
  156. let mut opts = Options::empty();
  157. let mut has_summary = false;
  158. opts.insert(Options::ENABLE_TABLES);
  159. opts.insert(Options::ENABLE_FOOTNOTES);
  160. opts.insert(Options::ENABLE_STRIKETHROUGH);
  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)) if link.is_empty() => {
  217. error = Some(Error::msg("There is a link that is missing a URL"));
  218. Event::Start(Tag::Link(link_type, "#".into(), title))
  219. }
  220. Event::Start(Tag::Link(link_type, link, title)) => {
  221. let fixed_link = match fix_link(
  222. link_type,
  223. &link,
  224. context,
  225. &mut internal_links_with_anchors,
  226. &mut external_links,
  227. ) {
  228. Ok(fixed_link) => fixed_link,
  229. Err(err) => {
  230. error = Some(err);
  231. return Event::Html("".into());
  232. }
  233. };
  234. Event::Start(Tag::Link(link_type, fixed_link.into(), title))
  235. }
  236. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  237. has_summary = true;
  238. Event::Html(CONTINUE_READING.into())
  239. }
  240. _ => event,
  241. }
  242. })
  243. .collect::<Vec<_>>(); // We need to collect the events to make a second pass
  244. let mut heading_refs = get_heading_refs(&events);
  245. let mut anchors_to_insert = vec![];
  246. // First heading pass: look for a manually-specified IDs, e.g. `# Heading text {#hash}`
  247. // (This is a separate first pass so that auto IDs can avoid collisions with manual IDs.)
  248. for heading_ref in heading_refs.iter_mut() {
  249. let end_idx = heading_ref.end_idx;
  250. if let Event::Text(ref mut text) = events[end_idx - 1] {
  251. if text.as_bytes().last() == Some(&b'}') {
  252. if let Some(mut i) = text.find("{#") {
  253. let id = text[i + 2..text.len() - 1].to_owned();
  254. inserted_anchors.push(id.clone());
  255. while i > 0 && text.as_bytes()[i - 1] == b' ' {
  256. i -= 1;
  257. }
  258. heading_ref.id = Some(id);
  259. *text = text[..i].to_owned().into();
  260. }
  261. }
  262. }
  263. }
  264. // Second heading pass: auto-generate remaining IDs, and emit HTML
  265. for heading_ref in heading_refs {
  266. let start_idx = heading_ref.start_idx;
  267. let end_idx = heading_ref.end_idx;
  268. let title = get_text(&events[start_idx + 1..end_idx]);
  269. let id = heading_ref.id.unwrap_or_else(|| {
  270. find_anchor(
  271. &inserted_anchors,
  272. slugify_anchors(&title, context.config.slugify.anchors),
  273. 0,
  274. )
  275. });
  276. inserted_anchors.push(id.clone());
  277. // insert `id` to the tag
  278. let html = format!("<h{lvl} id=\"{id}\">", lvl = heading_ref.level, id = id);
  279. events[start_idx] = Event::Html(html.into());
  280. // generate anchors and places to insert them
  281. if context.insert_anchor != InsertAnchor::None {
  282. let anchor_idx = match context.insert_anchor {
  283. InsertAnchor::Left => start_idx + 1,
  284. InsertAnchor::Right => end_idx,
  285. InsertAnchor::None => 0, // Not important
  286. };
  287. let mut c = tera::Context::new();
  288. c.insert("id", &id);
  289. let anchor_link = utils::templates::render_template(
  290. &ANCHOR_LINK_TEMPLATE,
  291. context.tera,
  292. c,
  293. &None,
  294. )
  295. .map_err(|e| Error::chain("Failed to render anchor link template", e))?;
  296. anchors_to_insert.push((anchor_idx, Event::Html(anchor_link.into())));
  297. }
  298. // record heading to make table of contents
  299. let permalink = format!("{}#{}", context.current_page_permalink, id);
  300. let h =
  301. Heading { level: heading_ref.level, id, permalink, title, children: Vec::new() };
  302. headings.push(h);
  303. }
  304. if context.insert_anchor != InsertAnchor::None {
  305. events.insert_many(anchors_to_insert);
  306. }
  307. cmark::html::push_html(&mut html, events.into_iter());
  308. }
  309. if let Some(e) = error {
  310. Err(e)
  311. } else {
  312. Ok(Rendered {
  313. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  314. body: html,
  315. toc: make_table_of_contents(headings),
  316. internal_links_with_anchors,
  317. external_links,
  318. })
  319. }
  320. }
  321. #[cfg(test)]
  322. mod tests {
  323. use super::*;
  324. #[test]
  325. fn test_starts_with_schema() {
  326. // registered
  327. assert!(starts_with_schema("https://example.com/"));
  328. assert!(starts_with_schema("ftp://example.com/"));
  329. assert!(starts_with_schema("mailto:user@example.com"));
  330. assert!(starts_with_schema("xmpp:node@example.com"));
  331. assert!(starts_with_schema("tel:18008675309"));
  332. assert!(starts_with_schema("sms:18008675309"));
  333. assert!(starts_with_schema("h323:user@example.com"));
  334. // arbitrary
  335. assert!(starts_with_schema("zola:post?content=hi"));
  336. // case-insensitive
  337. assert!(starts_with_schema("MailTo:user@example.com"));
  338. assert!(starts_with_schema("MAILTO:user@example.com"));
  339. }
  340. #[test]
  341. fn test_is_external_link() {
  342. assert!(is_external_link("http://example.com/"));
  343. assert!(is_external_link("https://example.com/"));
  344. assert!(is_external_link("https://example.com/index.html#introduction"));
  345. assert!(!is_external_link("mailto:user@example.com"));
  346. assert!(!is_external_link("tel:18008675309"));
  347. assert!(!is_external_link("#introduction"));
  348. assert!(!is_external_link("http.jpg"))
  349. }
  350. }