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.

509 lines
20KB

  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. // the rendered html
  110. let mut html = String::new();
  111. let mut anchors: Vec<String> = vec![];
  112. // We might have cases where the slug is already present in our list of anchor
  113. // for example an article could have several titles named Example
  114. // We add a counter after the slug if the slug is already present, which
  115. // means we will have example, example-1, example-2 etc
  116. fn find_anchor(anchors: &Vec<String>, name: String, level: u8) -> String {
  117. if level == 0 && !anchors.contains(&name) {
  118. return name.to_string();
  119. }
  120. let new_anchor = format!("{}-{}", name, level + 1);
  121. if !anchors.contains(&new_anchor) {
  122. return new_anchor;
  123. }
  124. find_anchor(anchors, name, level + 1)
  125. }
  126. let mut opts = Options::empty();
  127. opts.insert(OPTION_ENABLE_TABLES);
  128. opts.insert(OPTION_ENABLE_FOOTNOTES);
  129. {
  130. let parser = Parser::new_ext(content, opts).map(|event| match event {
  131. Event::Text(text) => {
  132. // if we are in the middle of a code block
  133. if let Some(ref mut highlighter) = highlighter {
  134. let highlighted = &highlighter.highlight(&text);
  135. let html = styles_to_coloured_html(highlighted, IncludeBackground::Yes);
  136. return Event::Html(Owned(html));
  137. }
  138. if in_code_block {
  139. return Event::Text(text);
  140. }
  141. // Shortcode without body
  142. if shortcode_block.is_none() && text.starts_with("{{") && text.ends_with("}}") {
  143. if SHORTCODE_RE.is_match(&text) {
  144. let (name, args) = parse_shortcode(&text);
  145. added_shortcode = true;
  146. match render_simple_shortcode(tera, &name, &args) {
  147. Ok(s) => return Event::Html(Owned(format!("</p>{}", s))),
  148. Err(e) => {
  149. error = Some(e);
  150. return Event::Html(Owned("".to_string()));
  151. }
  152. }
  153. }
  154. // non-matching will be returned normally below
  155. }
  156. // Shortcode with a body
  157. if shortcode_block.is_none() && text.starts_with("{%") && text.ends_with("%}") {
  158. if SHORTCODE_RE.is_match(&text) {
  159. let (name, args) = parse_shortcode(&text);
  160. shortcode_block = Some(ShortCode::new(&name, args));
  161. }
  162. // Don't return anything
  163. return Event::Text(Owned("".to_string()));
  164. }
  165. // If we have some text while in a shortcode, it's either the body
  166. // or the end tag
  167. if shortcode_block.is_some() {
  168. if let Some(ref mut shortcode) = shortcode_block {
  169. if text.trim() == "{% end %}" {
  170. added_shortcode = true;
  171. match shortcode.render(tera) {
  172. Ok(s) => return Event::Html(Owned(format!("</p>{}", s))),
  173. Err(e) => {
  174. error = Some(e);
  175. return Event::Html(Owned("".to_string()));
  176. }
  177. }
  178. } else {
  179. shortcode.append(&text);
  180. return Event::Html(Owned("".to_string()));
  181. }
  182. }
  183. }
  184. if in_header {
  185. let id = find_anchor(&anchors, slugify(&text), 0);
  186. anchors.push(id.clone());
  187. let anchor_link = if config.insert_anchor_links.unwrap() {
  188. let mut context = Context::new();
  189. context.add("id", &id);
  190. tera.render("anchor-link.html", &context).unwrap()
  191. } else {
  192. String::new()
  193. };
  194. return Event::Html(Owned(format!(r#"id="{}">{}{}"#, id, anchor_link, text)));
  195. }
  196. // Business as usual
  197. Event::Text(text)
  198. },
  199. Event::Start(Tag::CodeBlock(ref info)) => {
  200. in_code_block = true;
  201. if !should_highlight {
  202. return Event::Html(Owned("<pre><code>".to_owned()));
  203. }
  204. let theme = &SETUP.theme_set.themes[&highlight_theme];
  205. let syntax = info
  206. .split(' ')
  207. .next()
  208. .and_then(|lang| SETUP.syntax_set.find_syntax_by_token(lang))
  209. .unwrap_or_else(|| SETUP.syntax_set.find_syntax_plain_text());
  210. highlighter = Some(HighlightLines::new(syntax, theme));
  211. let snippet = start_coloured_html_snippet(theme);
  212. Event::Html(Owned(snippet))
  213. },
  214. Event::End(Tag::CodeBlock(_)) => {
  215. in_code_block = false;
  216. if !should_highlight{
  217. return Event::Html(Owned("</code></pre>\n".to_owned()))
  218. }
  219. // reset highlight and close the code block
  220. highlighter = None;
  221. Event::Html(Owned("</pre>".to_owned()))
  222. },
  223. // Need to handle relative links
  224. Event::Start(Tag::Link(ref link, ref title)) => {
  225. if link.starts_with("./") {
  226. // First we remove the ./ since that's gutenberg specific
  227. let clean_link = link.replacen("./", "", 1);
  228. // Then we remove any potential anchor
  229. // parts[0] will be the file path and parts[1] the anchor if present
  230. let parts = clean_link.split('#').collect::<Vec<_>>();
  231. match permalinks.get(parts[0]) {
  232. Some(p) => {
  233. let url = if parts.len() > 1 {
  234. format!("{}#{}", p, parts[1])
  235. } else {
  236. p.to_string()
  237. };
  238. return Event::Start(Tag::Link(Owned(url), title.clone()));
  239. },
  240. None => {
  241. error = Some(format!("Relative link {} not found.", link).into());
  242. return Event::Html(Owned("".to_string()));
  243. }
  244. };
  245. }
  246. return Event::Start(Tag::Link(link.clone(), title.clone()));
  247. },
  248. // need to know when we are in a code block to disable shortcodes in them
  249. Event::Start(Tag::Code) => {
  250. in_code_block = true;
  251. event
  252. },
  253. Event::End(Tag::Code) => {
  254. in_code_block = false;
  255. event
  256. },
  257. Event::Start(Tag::Header(num)) => {
  258. in_header = true;
  259. // ugly eh
  260. return Event::Html(Owned(format!("<h{} ", num)));
  261. },
  262. Event::End(Tag::Header(_)) => {
  263. in_header = false;
  264. event
  265. },
  266. // If we added shortcodes, don't close a paragraph since there's none
  267. Event::End(Tag::Paragraph) => {
  268. if added_shortcode {
  269. added_shortcode = false;
  270. return Event::Html(Owned("".to_owned()));
  271. }
  272. event
  273. },
  274. // Ignore softbreaks inside shortcodes
  275. Event::SoftBreak => {
  276. if shortcode_block.is_some() {
  277. return Event::Html(Owned("".to_owned()));
  278. }
  279. event
  280. },
  281. _ => {
  282. // println!("event = {:?}", event);
  283. event
  284. },
  285. });
  286. cmark::html::push_html(&mut html, parser);
  287. }
  288. match error {
  289. Some(e) => Err(e),
  290. None => Ok(html.replace("<p></p>", "")),
  291. }
  292. }
  293. #[cfg(test)]
  294. mod tests {
  295. use std::collections::HashMap;
  296. use site::GUTENBERG_TERA;
  297. use tera::Tera;
  298. use config::Config;
  299. use super::{markdown_to_html, parse_shortcode};
  300. #[test]
  301. fn test_parse_simple_shortcode_one_arg() {
  302. let (name, args) = parse_shortcode(r#"{{ youtube(id="w7Ft2ymGmfc") }}"#);
  303. assert_eq!(name, "youtube");
  304. assert_eq!(args["id"], "w7Ft2ymGmfc");
  305. }
  306. #[test]
  307. fn test_parse_simple_shortcode_several_arg() {
  308. let (name, args) = parse_shortcode(r#"{{ youtube(id="w7Ft2ymGmfc", autoplay=true) }}"#);
  309. assert_eq!(name, "youtube");
  310. assert_eq!(args["id"], "w7Ft2ymGmfc");
  311. assert_eq!(args["autoplay"], "true");
  312. }
  313. #[test]
  314. fn test_parse_block_shortcode_several_arg() {
  315. let (name, args) = parse_shortcode(r#"{% youtube(id="w7Ft2ymGmfc", autoplay=true) %}"#);
  316. assert_eq!(name, "youtube");
  317. assert_eq!(args["id"], "w7Ft2ymGmfc");
  318. assert_eq!(args["autoplay"], "true");
  319. }
  320. #[test]
  321. fn test_markdown_to_html_simple() {
  322. let res = markdown_to_html("hello", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  323. assert_eq!(res, "<p>hello</p>\n");
  324. }
  325. #[test]
  326. fn test_markdown_to_html_code_block_highlighting_off() {
  327. let mut config = Config::default();
  328. config.highlight_code = Some(false);
  329. let res = markdown_to_html("```\n$ gutenberg server\n```", &HashMap::new(), &Tera::default(), &config).unwrap();
  330. assert_eq!(
  331. res,
  332. "<pre><code>$ gutenberg server\n</code></pre>\n"
  333. );
  334. }
  335. #[test]
  336. fn test_markdown_to_html_code_block_no_lang() {
  337. let res = markdown_to_html("```\n$ gutenberg server\n$ ping\n```", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  338. assert_eq!(
  339. res,
  340. "<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>"
  341. );
  342. }
  343. #[test]
  344. fn test_markdown_to_html_code_block_with_lang() {
  345. let res = markdown_to_html("```python\nlist.append(1)\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;\">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>"
  349. );
  350. }
  351. #[test]
  352. fn test_markdown_to_html_code_block_with_unknown_lang() {
  353. let res = markdown_to_html("```yolo\nlist.append(1)\n```", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  354. // defaults to plain text
  355. assert_eq!(
  356. res,
  357. "<pre style=\"background-color:#2b303b\">\n<span style=\"background-color:#2b303b;color:#c0c5ce;\">list.append(1)\n</span></pre>"
  358. );
  359. }
  360. #[test]
  361. fn test_markdown_to_html_with_shortcode() {
  362. let res = markdown_to_html(r#"
  363. Hello
  364. {{ youtube(id="ub36ffWAqgQ") }}
  365. "#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  366. assert!(res.contains("<p>Hello</p>\n<div >"));
  367. assert!(res.contains(r#"<iframe src="https://www.youtube.com/embed/ub36ffWAqgQ""#));
  368. }
  369. #[test]
  370. fn test_markdown_to_html_with_several_shortcode_in_row() {
  371. let res = markdown_to_html(r#"
  372. Hello
  373. {{ youtube(id="ub36ffWAqgQ") }}
  374. {{ youtube(id="ub36ffWAqgQ", autoplay=true) }}
  375. {{ vimeo(id="210073083") }}
  376. {{ gist(url="https://gist.github.com/Keats/32d26f699dcc13ebd41b") }}
  377. "#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  378. assert!(res.contains("<p>Hello</p>\n<div >"));
  379. assert!(res.contains(r#"<iframe src="https://www.youtube.com/embed/ub36ffWAqgQ""#));
  380. assert!(res.contains(r#"<iframe src="https://www.youtube.com/embed/ub36ffWAqgQ?autoplay=1""#));
  381. assert!(res.contains(r#"//player.vimeo.com/video/210073083""#));
  382. }
  383. #[test]
  384. fn test_markdown_to_html_shortcode_in_code_block() {
  385. let res = markdown_to_html(r#"```{{ youtube(id="w7Ft2ymGmfc") }}```"#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  386. assert_eq!(res, "<p><code>{{ youtube(id=&quot;w7Ft2ymGmfc&quot;) }}</code></p>\n");
  387. }
  388. #[test]
  389. fn test_markdown_to_html_shortcode_with_body() {
  390. let mut tera = Tera::default();
  391. tera.extend(&GUTENBERG_TERA).unwrap();
  392. tera.add_raw_template("shortcodes/quote.html", "<blockquote>{{ body }} - {{ author}}</blockquote>").unwrap();
  393. let res = markdown_to_html(r#"
  394. Hello
  395. {% quote(author="Keats") %}
  396. A quote
  397. {% end %}
  398. "#, &HashMap::new(), &tera, &Config::default()).unwrap();
  399. assert_eq!(res, "<p>Hello\n</p><blockquote>A quote - Keats</blockquote>");
  400. }
  401. #[test]
  402. fn test_markdown_to_html_unknown_shortcode() {
  403. let res = markdown_to_html("{{ hello(flash=true) }}", &HashMap::new(), &Tera::default(), &Config::default());
  404. assert!(res.is_err());
  405. }
  406. #[test]
  407. fn test_markdown_to_html_relative_link_exists() {
  408. let mut permalinks = HashMap::new();
  409. permalinks.insert("pages/about.md".to_string(), "https://vincent.is/about".to_string());
  410. let res = markdown_to_html(
  411. r#"[rel link](./pages/about.md), [abs link](https://vincent.is/about)"#,
  412. &permalinks,
  413. &GUTENBERG_TERA,
  414. &Config::default()
  415. ).unwrap();
  416. assert!(
  417. res.contains(r#"<p><a href="https://vincent.is/about">rel link</a>, <a href="https://vincent.is/about">abs link</a></p>"#)
  418. );
  419. }
  420. #[test]
  421. fn test_markdown_to_html_relative_links_with_anchors() {
  422. let mut permalinks = HashMap::new();
  423. permalinks.insert("pages/about.md".to_string(), "https://vincent.is/about".to_string());
  424. let res = markdown_to_html(
  425. r#"[rel link](./pages/about.md#cv)"#,
  426. &permalinks,
  427. &GUTENBERG_TERA,
  428. &Config::default()
  429. ).unwrap();
  430. assert!(
  431. res.contains(r#"<p><a href="https://vincent.is/about#cv">rel link</a></p>"#)
  432. );
  433. }
  434. #[test]
  435. fn test_markdown_to_html_relative_link_inexistant() {
  436. let res = markdown_to_html("[rel link](./pages/about.md)", &HashMap::new(), &Tera::default(), &Config::default());
  437. assert!(res.is_err());
  438. }
  439. #[test]
  440. fn test_markdown_to_html_add_id_to_headers() {
  441. let res = markdown_to_html(r#"# Hello"#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  442. assert_eq!(res, "<h1 id=\"hello\">Hello</h1>\n");
  443. }
  444. #[test]
  445. fn test_markdown_to_html_add_id_to_headers_same_slug() {
  446. let res = markdown_to_html("# Hello\n# Hello", &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  447. assert_eq!(res, "<h1 id=\"hello\">Hello</h1>\n<h1 id=\"hello-1\">Hello</h1>\n");
  448. }
  449. }