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.

494 lines
19KB

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