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.

551 lines
21KB

  1. use std::borrow::Cow::Owned;
  2. use std::collections::HashMap;
  3. use pulldown_cmark as cmark;
  4. use self::cmark::{Parser, Event, Tag, Options, OPTION_ENABLE_TABLES, OPTION_ENABLE_FOOTNOTES};
  5. use regex::Regex;
  6. use slug::slugify;
  7. use syntect::dumps::from_binary;
  8. use syntect::easy::HighlightLines;
  9. use syntect::parsing::SyntaxSet;
  10. use syntect::highlighting::ThemeSet;
  11. use syntect::html::{start_coloured_html_snippet, styles_to_coloured_html, IncludeBackground};
  12. use tera::{Tera, Context};
  13. use config::Config;
  14. use errors::{Result, ResultExt};
  15. // We need to put those in a struct to impl Send and sync
  16. pub struct Setup {
  17. pub syntax_set: SyntaxSet,
  18. pub theme_set: ThemeSet,
  19. }
  20. unsafe impl Send for Setup {}
  21. unsafe impl Sync for Setup {}
  22. lazy_static!{
  23. static ref SHORTCODE_RE: Regex = Regex::new(r#"\{(?:%|\{)\s+([[:alnum:]]+?)\(([[:alnum:]]+?="?.+?"?)\)\s+(?:%|\})\}"#).unwrap();
  24. pub static ref SETUP: Setup = Setup {
  25. syntax_set: {
  26. let mut ps: SyntaxSet = from_binary(include_bytes!("../sublime_syntaxes/newlines.packdump"));
  27. ps.link_syntaxes();
  28. ps
  29. },
  30. theme_set: from_binary(include_bytes!("../sublime_themes/all.themedump"))
  31. };
  32. }
  33. /// A ShortCode that has a body
  34. /// Called by having some content like {% ... %} body {% end %}
  35. /// We need the struct to hold the data while we're processing the markdown
  36. #[derive(Debug)]
  37. struct ShortCode {
  38. name: String,
  39. args: HashMap<String, String>,
  40. body: String,
  41. }
  42. impl ShortCode {
  43. pub fn new(name: &str, args: HashMap<String, String>) -> ShortCode {
  44. ShortCode {
  45. name: name.to_string(),
  46. args: args,
  47. body: String::new(),
  48. }
  49. }
  50. pub fn append(&mut self, text: &str) {
  51. self.body.push_str(text)
  52. }
  53. pub fn render(&self, tera: &Tera) -> Result<String> {
  54. let mut context = Context::new();
  55. for (key, value) in self.args.iter() {
  56. context.add(key, value);
  57. }
  58. context.add("body", &self.body);
  59. let tpl_name = format!("shortcodes/{}.html", self.name);
  60. tera.render(&tpl_name, &context)
  61. .chain_err(|| format!("Failed to render {} shortcode", self.name))
  62. }
  63. }
  64. /// Parse a shortcode without a body
  65. fn parse_shortcode(input: &str) -> (String, HashMap<String, String>) {
  66. let mut args = HashMap::new();
  67. let caps = SHORTCODE_RE.captures(input).unwrap();
  68. // caps[0] is the full match
  69. let name = &caps[1];
  70. let arg_list = &caps[2];
  71. for arg in arg_list.split(',') {
  72. let bits = arg.split('=').collect::<Vec<_>>();
  73. args.insert(bits[0].trim().to_string(), bits[1].replace("\"", ""));
  74. }
  75. (name.to_string(), args)
  76. }
  77. /// Renders a shortcode or return an error
  78. fn render_simple_shortcode(tera: &Tera, name: &str, args: &HashMap<String, String>) -> Result<String> {
  79. let mut context = Context::new();
  80. for (key, value) in args.iter() {
  81. context.add(key, value);
  82. }
  83. let tpl_name = format!("shortcodes/{}.html", name);
  84. tera.render(&tpl_name, &context).chain_err(|| format!("Failed to render {} shortcode", name))
  85. }
  86. pub fn markdown_to_html(content: &str, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config) -> Result<String> {
  87. // We try to be smart about highlighting code as it can be time-consuming
  88. // If the global config disables it, then we do nothing. However,
  89. // if we see a code block in the content, we assume that this page needs
  90. // to be highlighted. It could potentially have false positive if the content
  91. // has ``` in it but that seems kind of unlikely
  92. let should_highlight = if config.highlight_code.unwrap() {
  93. content.contains("```")
  94. } else {
  95. false
  96. };
  97. let highlight_theme = config.highlight_theme.clone().unwrap();
  98. // Set while parsing
  99. let mut error = None;
  100. let mut highlighter: Option<HighlightLines> = None;
  101. let mut shortcode_block = None;
  102. // shortcodes live outside of paragraph so we need to ensure we don't close
  103. // a paragraph that has already been closed
  104. let mut added_shortcode = false;
  105. // Don't transform things that look like shortcodes in code blocks
  106. let mut in_code_block = false;
  107. // If we get text in header, we need to insert the id and a anchor
  108. let mut in_header = false;
  109. // pulldown_cmark can send several text events for a title if there are markdown
  110. // specific characters like `!` in them. We only want to insert the anchor the first time
  111. let mut header_already_inserted = false;
  112. // the rendered html
  113. let mut html = String::new();
  114. let mut anchors: Vec<String> = vec![];
  115. // We might have cases where the slug is already present in our list of anchor
  116. // for example an article could have several titles named Example
  117. // We add a counter after the slug if the slug is already present, which
  118. // means we will have example, example-1, example-2 etc
  119. fn find_anchor(anchors: &Vec<String>, name: String, level: u8) -> String {
  120. if level == 0 && !anchors.contains(&name) {
  121. return name.to_string();
  122. }
  123. let new_anchor = format!("{}-{}", name, level + 1);
  124. if !anchors.contains(&new_anchor) {
  125. return new_anchor;
  126. }
  127. find_anchor(anchors, name, level + 1)
  128. }
  129. let mut opts = Options::empty();
  130. opts.insert(OPTION_ENABLE_TABLES);
  131. opts.insert(OPTION_ENABLE_FOOTNOTES);
  132. {
  133. let parser = Parser::new_ext(content, opts).map(|event| match event {
  134. Event::Text(text) => {
  135. // if we are in the middle of a code block
  136. if let Some(ref mut highlighter) = highlighter {
  137. let highlighted = &highlighter.highlight(&text);
  138. let html = styles_to_coloured_html(highlighted, IncludeBackground::Yes);
  139. return Event::Html(Owned(html));
  140. }
  141. if in_code_block {
  142. return Event::Text(text);
  143. }
  144. // Shortcode without body
  145. if shortcode_block.is_none() && text.starts_with("{{") && text.ends_with("}}") {
  146. if SHORTCODE_RE.is_match(&text) {
  147. let (name, args) = parse_shortcode(&text);
  148. added_shortcode = true;
  149. match render_simple_shortcode(tera, &name, &args) {
  150. Ok(s) => return Event::Html(Owned(format!("</p>{}", s))),
  151. Err(e) => {
  152. error = Some(e);
  153. return Event::Html(Owned("".to_string()));
  154. }
  155. }
  156. }
  157. // non-matching will be returned normally below
  158. }
  159. // Shortcode with a body
  160. if shortcode_block.is_none() && text.starts_with("{%") && text.ends_with("%}") {
  161. if SHORTCODE_RE.is_match(&text) {
  162. let (name, args) = parse_shortcode(&text);
  163. shortcode_block = Some(ShortCode::new(&name, args));
  164. }
  165. // Don't return anything
  166. return Event::Text(Owned("".to_string()));
  167. }
  168. // If we have some text while in a shortcode, it's either the body
  169. // or the end tag
  170. if shortcode_block.is_some() {
  171. if let Some(ref mut shortcode) = shortcode_block {
  172. if text.trim() == "{% end %}" {
  173. added_shortcode = true;
  174. match shortcode.render(tera) {
  175. Ok(s) => return Event::Html(Owned(format!("</p>{}", s))),
  176. Err(e) => {
  177. error = Some(e);
  178. return Event::Html(Owned("".to_string()));
  179. }
  180. }
  181. } else {
  182. shortcode.append(&text);
  183. return Event::Html(Owned("".to_string()));
  184. }
  185. }
  186. }
  187. if in_header {
  188. if header_already_inserted {
  189. return Event::Text(text);
  190. }
  191. let id = find_anchor(&anchors, slugify(&text), 0);
  192. anchors.push(id.clone());
  193. let anchor_link = if config.insert_anchor_links.unwrap() {
  194. let mut context = Context::new();
  195. context.add("id", &id);
  196. tera.render("anchor-link.html", &context).unwrap()
  197. } else {
  198. String::new()
  199. };
  200. header_already_inserted = true;
  201. return Event::Html(Owned(format!(r#"id="{}">{}{}"#, id, anchor_link, text)));
  202. }
  203. // Business as usual
  204. Event::Text(text)
  205. },
  206. Event::Start(Tag::CodeBlock(ref info)) => {
  207. in_code_block = true;
  208. if !should_highlight {
  209. return Event::Html(Owned("<pre><code>".to_owned()));
  210. }
  211. let theme = &SETUP.theme_set.themes[&highlight_theme];
  212. let syntax = info
  213. .split(' ')
  214. .next()
  215. .and_then(|lang| SETUP.syntax_set.find_syntax_by_token(lang))
  216. .unwrap_or_else(|| SETUP.syntax_set.find_syntax_plain_text());
  217. highlighter = Some(HighlightLines::new(syntax, theme));
  218. let snippet = start_coloured_html_snippet(theme);
  219. Event::Html(Owned(snippet))
  220. },
  221. Event::End(Tag::CodeBlock(_)) => {
  222. in_code_block = false;
  223. if !should_highlight{
  224. return Event::Html(Owned("</code></pre>\n".to_owned()))
  225. }
  226. // reset highlight and close the code block
  227. highlighter = None;
  228. Event::Html(Owned("</pre>".to_owned()))
  229. },
  230. // Need to handle relative links
  231. Event::Start(Tag::Link(ref link, ref title)) => {
  232. if link.starts_with("./") {
  233. // First we remove the ./ since that's gutenberg specific
  234. let clean_link = link.replacen("./", "", 1);
  235. // Then we remove any potential anchor
  236. // parts[0] will be the file path and parts[1] the anchor if present
  237. let parts = clean_link.split('#').collect::<Vec<_>>();
  238. match permalinks.get(parts[0]) {
  239. Some(p) => {
  240. let url = if parts.len() > 1 {
  241. format!("{}#{}", p, parts[1])
  242. } else {
  243. p.to_string()
  244. };
  245. return Event::Start(Tag::Link(Owned(url), title.clone()));
  246. },
  247. None => {
  248. error = Some(format!("Relative link {} not found.", link).into());
  249. return Event::Html(Owned("".to_string()));
  250. }
  251. };
  252. }
  253. return Event::Start(Tag::Link(link.clone(), title.clone()));
  254. },
  255. // need to know when we are in a code block to disable shortcodes in them
  256. Event::Start(Tag::Code) => {
  257. in_code_block = true;
  258. event
  259. },
  260. Event::End(Tag::Code) => {
  261. in_code_block = false;
  262. event
  263. },
  264. Event::Start(Tag::Header(num)) => {
  265. in_header = true;
  266. // ugly eh
  267. return Event::Html(Owned(format!("<h{} ", num)));
  268. },
  269. Event::End(Tag::Header(_)) => {
  270. in_header = false;
  271. header_already_inserted = false;
  272. event
  273. },
  274. // If we added shortcodes, don't close a paragraph since there's none
  275. Event::End(Tag::Paragraph) => {
  276. if added_shortcode {
  277. added_shortcode = false;
  278. return Event::Html(Owned("".to_owned()));
  279. }
  280. event
  281. },
  282. // Ignore softbreaks inside shortcodes
  283. Event::SoftBreak => {
  284. if shortcode_block.is_some() {
  285. return Event::Html(Owned("".to_owned()));
  286. }
  287. event
  288. },
  289. _ => {
  290. // println!("event = {:?}", event);
  291. event
  292. },
  293. });
  294. cmark::html::push_html(&mut html, parser);
  295. }
  296. match error {
  297. Some(e) => Err(e),
  298. None => Ok(html.replace("<p></p>", "")),
  299. }
  300. }
  301. #[cfg(test)]
  302. mod tests {
  303. use std::collections::HashMap;
  304. use site::GUTENBERG_TERA;
  305. use tera::Tera;
  306. use config::Config;
  307. use super::{markdown_to_html, parse_shortcode};
  308. #[test]
  309. fn test_parse_simple_shortcode_one_arg() {
  310. let (name, args) = parse_shortcode(r#"{{ youtube(id="w7Ft2ymGmfc") }}"#);
  311. assert_eq!(name, "youtube");
  312. assert_eq!(args["id"], "w7Ft2ymGmfc");
  313. }
  314. #[test]
  315. fn test_parse_simple_shortcode_several_arg() {
  316. let (name, args) = parse_shortcode(r#"{{ youtube(id="w7Ft2ymGmfc", autoplay=true) }}"#);
  317. assert_eq!(name, "youtube");
  318. assert_eq!(args["id"], "w7Ft2ymGmfc");
  319. assert_eq!(args["autoplay"], "true");
  320. }
  321. #[test]
  322. fn test_parse_block_shortcode_several_arg() {
  323. let (name, args) = parse_shortcode(r#"{% youtube(id="w7Ft2ymGmfc", autoplay=true) %}"#);
  324. assert_eq!(name, "youtube");
  325. assert_eq!(args["id"], "w7Ft2ymGmfc");
  326. assert_eq!(args["autoplay"], "true");
  327. }
  328. #[test]
  329. fn test_markdown_to_html_simple() {
  330. let res = markdown_to_html("hello", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  331. assert_eq!(res, "<p>hello</p>\n");
  332. }
  333. #[test]
  334. fn test_markdown_to_html_code_block_highlighting_off() {
  335. let mut config = Config::default();
  336. config.highlight_code = Some(false);
  337. let res = markdown_to_html("```\n$ gutenberg server\n```", &HashMap::new(), &Tera::default(), &config).unwrap();
  338. assert_eq!(
  339. res,
  340. "<pre><code>$ gutenberg server\n</code></pre>\n"
  341. );
  342. }
  343. #[test]
  344. fn test_markdown_to_html_code_block_no_lang() {
  345. let res = markdown_to_html("```\n$ gutenberg server\n$ ping\n```", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  346. assert_eq!(
  347. res,
  348. "<pre style=\"background-color:#2b303b\">\n<span style=\"background-color:#2b303b;color:#c0c5ce;\">$ gutenberg server\n</span><span style=\"background-color:#2b303b;color:#c0c5ce;\">$ ping\n</span></pre>"
  349. );
  350. }
  351. #[test]
  352. fn test_markdown_to_html_code_block_with_lang() {
  353. let res = markdown_to_html("```python\nlist.append(1)\n```", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  354. assert_eq!(
  355. res,
  356. "<pre style=\"background-color:#2b303b\">\n<span style=\"background-color:#2b303b;color:#c0c5ce;\">list</span><span style=\"background-color:#2b303b;color:#c0c5ce;\">.</span><span style=\"background-color:#2b303b;color:#bf616a;\">append</span><span style=\"background-color:#2b303b;color:#c0c5ce;\">(</span><span style=\"background-color:#2b303b;color:#d08770;\">1</span><span style=\"background-color:#2b303b;color:#c0c5ce;\">)</span><span style=\"background-color:#2b303b;color:#c0c5ce;\">\n</span></pre>"
  357. );
  358. }
  359. #[test]
  360. fn test_markdown_to_html_code_block_with_unknown_lang() {
  361. let res = markdown_to_html("```yolo\nlist.append(1)\n```", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  362. // defaults to plain text
  363. assert_eq!(
  364. res,
  365. "<pre style=\"background-color:#2b303b\">\n<span style=\"background-color:#2b303b;color:#c0c5ce;\">list.append(1)\n</span></pre>"
  366. );
  367. }
  368. #[test]
  369. fn test_markdown_to_html_with_shortcode() {
  370. let res = markdown_to_html(r#"
  371. Hello
  372. {{ youtube(id="ub36ffWAqgQ") }}
  373. "#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  374. assert!(res.contains("<p>Hello</p>\n<div >"));
  375. assert!(res.contains(r#"<iframe src="https://www.youtube.com/embed/ub36ffWAqgQ""#));
  376. }
  377. #[test]
  378. fn test_markdown_to_html_with_several_shortcode_in_row() {
  379. let res = markdown_to_html(r#"
  380. Hello
  381. {{ youtube(id="ub36ffWAqgQ") }}
  382. {{ youtube(id="ub36ffWAqgQ", autoplay=true) }}
  383. {{ vimeo(id="210073083") }}
  384. {{ gist(url="https://gist.github.com/Keats/32d26f699dcc13ebd41b") }}
  385. "#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  386. assert!(res.contains("<p>Hello</p>\n<div >"));
  387. assert!(res.contains(r#"<iframe src="https://www.youtube.com/embed/ub36ffWAqgQ""#));
  388. assert!(res.contains(r#"<iframe src="https://www.youtube.com/embed/ub36ffWAqgQ?autoplay=1""#));
  389. assert!(res.contains(r#"//player.vimeo.com/video/210073083""#));
  390. }
  391. #[test]
  392. fn test_markdown_to_html_shortcode_in_code_block() {
  393. let res = markdown_to_html(r#"```{{ youtube(id="w7Ft2ymGmfc") }}```"#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  394. assert_eq!(res, "<p><code>{{ youtube(id=&quot;w7Ft2ymGmfc&quot;) }}</code></p>\n");
  395. }
  396. #[test]
  397. fn test_markdown_to_html_shortcode_with_body() {
  398. let mut tera = Tera::default();
  399. tera.extend(&GUTENBERG_TERA).unwrap();
  400. tera.add_raw_template("shortcodes/quote.html", "<blockquote>{{ body }} - {{ author}}</blockquote>").unwrap();
  401. let res = markdown_to_html(r#"
  402. Hello
  403. {% quote(author="Keats") %}
  404. A quote
  405. {% end %}
  406. "#, &HashMap::new(), &tera, &Config::default()).unwrap();
  407. assert_eq!(res, "<p>Hello\n</p><blockquote>A quote - Keats</blockquote>");
  408. }
  409. #[test]
  410. fn test_markdown_to_html_unknown_shortcode() {
  411. let res = markdown_to_html("{{ hello(flash=true) }}", &HashMap::new(), &Tera::default(), &Config::default());
  412. assert!(res.is_err());
  413. }
  414. #[test]
  415. fn test_markdown_to_html_relative_link_exists() {
  416. let mut permalinks = HashMap::new();
  417. permalinks.insert("pages/about.md".to_string(), "https://vincent.is/about".to_string());
  418. let res = markdown_to_html(
  419. r#"[rel link](./pages/about.md), [abs link](https://vincent.is/about)"#,
  420. &permalinks,
  421. &GUTENBERG_TERA,
  422. &Config::default()
  423. ).unwrap();
  424. assert!(
  425. res.contains(r#"<p><a href="https://vincent.is/about">rel link</a>, <a href="https://vincent.is/about">abs link</a></p>"#)
  426. );
  427. }
  428. #[test]
  429. fn test_markdown_to_html_relative_links_with_anchors() {
  430. let mut permalinks = HashMap::new();
  431. permalinks.insert("pages/about.md".to_string(), "https://vincent.is/about".to_string());
  432. let res = markdown_to_html(
  433. r#"[rel link](./pages/about.md#cv)"#,
  434. &permalinks,
  435. &GUTENBERG_TERA,
  436. &Config::default()
  437. ).unwrap();
  438. assert!(
  439. res.contains(r#"<p><a href="https://vincent.is/about#cv">rel link</a></p>"#)
  440. );
  441. }
  442. #[test]
  443. fn test_markdown_to_html_relative_link_inexistant() {
  444. let res = markdown_to_html("[rel link](./pages/about.md)", &HashMap::new(), &Tera::default(), &Config::default());
  445. assert!(res.is_err());
  446. }
  447. #[test]
  448. fn test_markdown_to_html_add_id_to_headers() {
  449. let res = markdown_to_html(r#"# Hello"#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  450. assert_eq!(res, "<h1 id=\"hello\">Hello</h1>\n");
  451. }
  452. #[test]
  453. fn test_markdown_to_html_add_id_to_headers_same_slug() {
  454. let res = markdown_to_html("# Hello\n# Hello", &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  455. assert_eq!(res, "<h1 id=\"hello\">Hello</h1>\n<h1 id=\"hello-1\">Hello</h1>\n");
  456. }
  457. #[test]
  458. fn test_markdown_to_html_insert_anchor() {
  459. let mut config = Config::default();
  460. config.insert_anchor_links = Some(true);
  461. let res = markdown_to_html("# Hello", &HashMap::new(), &GUTENBERG_TERA, &config).unwrap();
  462. assert_eq!(
  463. res,
  464. "<h1 id=\"hello\"><a class=\"anchor\" href=\"#hello\" aria-label=\"Anchor link for: hello\">🔗</a>\nHello</h1>\n"
  465. );
  466. }
  467. // See https://github.com/Keats/gutenberg/issues/42
  468. #[test]
  469. fn test_markdown_to_html_insert_anchor_with_exclamation_mark() {
  470. let mut config = Config::default();
  471. config.insert_anchor_links = Some(true);
  472. let res = markdown_to_html("# Hello!", &HashMap::new(), &GUTENBERG_TERA, &config).unwrap();
  473. assert_eq!(
  474. res,
  475. "<h1 id=\"hello\"><a class=\"anchor\" href=\"#hello\" aria-label=\"Anchor link for: hello\">🔗</a>\nHello!</h1>\n"
  476. );
  477. }
  478. #[test]
  479. fn test_markdown_to_html_insert_anchor_with_other_special_chars() {
  480. let mut config = Config::default();
  481. config.insert_anchor_links = Some(true);
  482. let res = markdown_to_html("# Hello*_()", &HashMap::new(), &GUTENBERG_TERA, &config).unwrap();
  483. assert_eq!(
  484. res,
  485. "<h1 id=\"hello\"><a class=\"anchor\" href=\"#hello\" aria-label=\"Anchor link for: hello\">🔗</a>\nHello*_()</h1>\n"
  486. );
  487. }
  488. }