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.

373 lines
14KB

  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 syntect::dumps::from_binary;
  7. use syntect::easy::HighlightLines;
  8. use syntect::parsing::SyntaxSet;
  9. use syntect::highlighting::ThemeSet;
  10. use syntect::html::{start_coloured_html_snippet, styles_to_coloured_html, IncludeBackground};
  11. use tera::{Tera, Context};
  12. use config::Config;
  13. use errors::{Result, ResultExt};
  14. // We need to put those in a struct to impl Send and sync
  15. pub struct Setup {
  16. syntax_set: SyntaxSet,
  17. pub theme_set: ThemeSet,
  18. }
  19. unsafe impl Send for Setup {}
  20. unsafe impl Sync for Setup {}
  21. lazy_static!{
  22. static ref SHORTCODE_RE: Regex = Regex::new(r#"\{(?:%|\{)\s+([[:alnum:]]+?)\(([[:alnum:]]+?="?.+?"?)\)\s+(?:%|\})\}"#).unwrap();
  23. pub static ref SETUP: Setup = Setup {
  24. syntax_set: SyntaxSet::load_defaults_newlines(),
  25. theme_set: from_binary(include_bytes!("../sublime_themes/all.themedump"))
  26. };
  27. }
  28. /// A ShortCode that has a body
  29. /// Called by having some content like {% ... %} body {% end %}
  30. /// We need the struct to hold the data while we're processing the markdown
  31. #[derive(Debug)]
  32. struct ShortCode {
  33. name: String,
  34. args: HashMap<String, String>,
  35. body: String,
  36. }
  37. impl ShortCode {
  38. pub fn new(name: &str, args: HashMap<String, String>) -> ShortCode {
  39. ShortCode {
  40. name: name.to_string(),
  41. args: args,
  42. body: String::new(),
  43. }
  44. }
  45. pub fn append(&mut self, text: &str) {
  46. self.body.push_str(text)
  47. }
  48. pub fn render(&self, tera: &Tera) -> Result<String> {
  49. let mut context = Context::new();
  50. for (key, value) in self.args.iter() {
  51. context.add(key, value);
  52. }
  53. context.add("body", &self.body);
  54. let tpl_name = format!("shortcodes/{}.html", self.name);
  55. tera.render(&tpl_name, &context)
  56. .chain_err(|| format!("Failed to render {} shortcode", self.name))
  57. }
  58. }
  59. /// Parse a shortcode without a body
  60. fn parse_shortcode(input: &str) -> (String, HashMap<String, String>) {
  61. let mut args = HashMap::new();
  62. let caps = SHORTCODE_RE.captures(input).unwrap();
  63. // caps[0] is the full match
  64. let name = &caps[1];
  65. let arg_list = &caps[2];
  66. for arg in arg_list.split(',') {
  67. let bits = arg.split('=').collect::<Vec<_>>();
  68. args.insert(bits[0].trim().to_string(), bits[1].replace("\"", ""));
  69. }
  70. (name.to_string(), args)
  71. }
  72. /// Renders a shortcode or return an error
  73. fn render_simple_shortcode(tera: &Tera, name: &str, args: &HashMap<String, String>) -> Result<String> {
  74. let mut context = Context::new();
  75. for (key, value) in args.iter() {
  76. context.add(key, value);
  77. }
  78. let tpl_name = format!("shortcodes/{}.html", name);
  79. tera.render(&tpl_name, &context).chain_err(|| format!("Failed to render {} shortcode", name))
  80. }
  81. pub fn markdown_to_html(content: &str, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config) -> Result<String> {
  82. // We try to be smart about highlighting code as it can be time-consuming
  83. // If the global config disables it, then we do nothing. However,
  84. // if we see a code block in the content, we assume that this page needs
  85. // to be highlighted. It could potentially have false positive if the content
  86. // has ``` in it but that seems kind of unlikely
  87. let should_highlight = if config.highlight_code.unwrap() {
  88. content.contains("```")
  89. } else {
  90. false
  91. };
  92. let highlight_theme = config.highlight_theme.clone().unwrap();
  93. // Set while parsing
  94. let mut error = None;
  95. let mut highlighter: Option<HighlightLines> = None;
  96. let mut shortcode_block = None;
  97. // shortcodes live outside of paragraph so we need to ensure we don't close
  98. // a paragraph that has already been closed
  99. let mut added_shortcode = false;
  100. // Don't transform things that look like shortcodes in code blocks
  101. let mut in_code_block = false;
  102. // the rendered html
  103. let mut html = String::new();
  104. {
  105. let parser = Parser::new(content).map(|event| match event {
  106. Event::Text(text) => {
  107. // if we are in the middle of a code block
  108. if let Some(ref mut highlighter) = highlighter {
  109. let highlighted = &highlighter.highlight(&text);
  110. let html = styles_to_coloured_html(highlighted, IncludeBackground::Yes);
  111. return Event::Html(Owned(html));
  112. }
  113. if in_code_block {
  114. return Event::Text(text);
  115. }
  116. // Shortcode without body
  117. if shortcode_block.is_none() && text.starts_with("{{") && text.ends_with("}}") {
  118. if SHORTCODE_RE.is_match(&text) {
  119. let (name, args) = parse_shortcode(&text);
  120. added_shortcode = true;
  121. match render_simple_shortcode(tera, &name, &args) {
  122. Ok(s) => return Event::Html(Owned(format!("</p>{}", s))),
  123. Err(e) => {
  124. error = Some(e);
  125. return Event::Html(Owned("".to_string()));
  126. }
  127. }
  128. }
  129. // non-matching will be returned normally below
  130. }
  131. // Shortcode with a body
  132. if shortcode_block.is_none() && text.starts_with("{%") && text.ends_with("%}") {
  133. if SHORTCODE_RE.is_match(&text) {
  134. let (name, args) = parse_shortcode(&text);
  135. shortcode_block = Some(ShortCode::new(&name, args));
  136. }
  137. // Don't return anything
  138. return Event::Text(Owned("".to_string()));
  139. }
  140. // If we have some text while in a shortcode, it's either the body
  141. // or the end tag
  142. if shortcode_block.is_some() {
  143. if let Some(ref mut shortcode) = shortcode_block {
  144. if text.trim() == "{% end %}" {
  145. added_shortcode = true;
  146. match shortcode.render(tera) {
  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. } else {
  154. shortcode.append(&text);
  155. return Event::Html(Owned("".to_string()));
  156. }
  157. }
  158. }
  159. // Business as usual
  160. Event::Text(text)
  161. },
  162. Event::Start(Tag::CodeBlock(ref info)) => {
  163. in_code_block = true;
  164. if !should_highlight {
  165. return Event::Html(Owned("<pre><code>".to_owned()));
  166. }
  167. let theme = &SETUP.theme_set.themes[&highlight_theme];
  168. let syntax = info
  169. .split(' ')
  170. .next()
  171. .and_then(|lang| SETUP.syntax_set.find_syntax_by_token(lang))
  172. .unwrap_or_else(|| SETUP.syntax_set.find_syntax_plain_text());
  173. highlighter = Some(HighlightLines::new(syntax, theme));
  174. let snippet = start_coloured_html_snippet(theme);
  175. Event::Html(Owned(snippet))
  176. },
  177. Event::End(Tag::CodeBlock(_)) => {
  178. in_code_block = false;
  179. if !should_highlight{
  180. return Event::Html(Owned("</code></pre>\n".to_owned()))
  181. }
  182. // reset highlight and close the code block
  183. highlighter = None;
  184. Event::Html(Owned("</pre>".to_owned()))
  185. },
  186. Event::Start(Tag::Code) => {
  187. in_code_block = true;
  188. event
  189. },
  190. Event::End(Tag::Code) => {
  191. in_code_block = false;
  192. event
  193. },
  194. Event::End(Tag::Paragraph) => {
  195. if added_shortcode {
  196. added_shortcode = false;
  197. return Event::Html(Owned("".to_owned()));
  198. }
  199. event
  200. },
  201. Event::SoftBreak => {
  202. if shortcode_block.is_some() {
  203. return Event::Html(Owned("".to_owned()));
  204. }
  205. event
  206. },
  207. _ => {
  208. // println!("event = {:?}", event);
  209. event
  210. },
  211. });
  212. cmark::html::push_html(&mut html, parser);
  213. }
  214. match error {
  215. Some(e) => Err(e),
  216. None => Ok(html.replace("<p></p>", "")),
  217. }
  218. }
  219. #[cfg(test)]
  220. mod tests {
  221. use std::collections::HashMap;
  222. use site::GUTENBERG_TERA;
  223. use tera::Tera;
  224. use config::Config;
  225. use super::{markdown_to_html, parse_shortcode};
  226. #[test]
  227. fn test_parse_simple_shortcode_one_arg() {
  228. let (name, args) = parse_shortcode(r#"{{ youtube(id="w7Ft2ymGmfc") }}"#);
  229. assert_eq!(name, "youtube");
  230. assert_eq!(args["id"], "w7Ft2ymGmfc");
  231. }
  232. #[test]
  233. fn test_parse_simple_shortcode_several_arg() {
  234. let (name, args) = parse_shortcode(r#"{{ youtube(id="w7Ft2ymGmfc", autoplay=true) }}"#);
  235. assert_eq!(name, "youtube");
  236. assert_eq!(args["id"], "w7Ft2ymGmfc");
  237. assert_eq!(args["autoplay"], "true");
  238. }
  239. #[test]
  240. fn test_parse_block_shortcode_several_arg() {
  241. let (name, args) = parse_shortcode(r#"{% youtube(id="w7Ft2ymGmfc", autoplay=true) %}"#);
  242. assert_eq!(name, "youtube");
  243. assert_eq!(args["id"], "w7Ft2ymGmfc");
  244. assert_eq!(args["autoplay"], "true");
  245. }
  246. #[test]
  247. fn test_markdown_to_html_simple() {
  248. let res = markdown_to_html("# hello", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  249. assert_eq!(res, "<h1>hello</h1>\n");
  250. }
  251. #[test]
  252. fn test_markdown_to_html_code_block_highlighting_off() {
  253. let mut config = Config::default();
  254. config.highlight_code = Some(false);
  255. let res = markdown_to_html("```\n$ gutenberg server\n```", &HashMap::new(), &Tera::default(), &config).unwrap();
  256. assert_eq!(
  257. res,
  258. "<pre><code>$ gutenberg server\n</code></pre>\n"
  259. );
  260. }
  261. #[test]
  262. fn test_markdown_to_html_code_block_no_lang() {
  263. let res = markdown_to_html("```\n$ gutenberg server\n$ ping\n```", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  264. assert_eq!(
  265. res,
  266. "<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>"
  267. );
  268. }
  269. #[test]
  270. fn test_markdown_to_html_code_block_with_lang() {
  271. let res = markdown_to_html("```python\nlist.append(1)\n```", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  272. assert_eq!(
  273. res,
  274. "<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>"
  275. );
  276. }
  277. #[test]
  278. fn test_markdown_to_html_code_block_with_unknown_lang() {
  279. let res = markdown_to_html("```yolo\nlist.append(1)\n```", &HashMap::new(), &Tera::default(), &Config::default()).unwrap();
  280. // defaults to plain text
  281. assert_eq!(
  282. res,
  283. "<pre style=\"background-color:#2b303b\">\n<span style=\"background-color:#2b303b;color:#c0c5ce;\">list.append(1)\n</span></pre>"
  284. );
  285. }
  286. #[test]
  287. fn test_markdown_to_html_with_shortcode() {
  288. let res = markdown_to_html(r#"
  289. Hello
  290. {{ youtube(id="ub36ffWAqgQ") }}
  291. "#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  292. assert!(res.contains("<p>Hello</p>\n<div >"));
  293. assert!(res.contains(r#"<iframe src="https://www.youtube.com/embed/ub36ffWAqgQ""#));
  294. }
  295. #[test]
  296. fn test_markdown_to_html_with_several_shortcode_in_row() {
  297. let res = markdown_to_html(r#"
  298. Hello
  299. {{ youtube(id="ub36ffWAqgQ") }}
  300. {{ youtube(id="ub36ffWAqgQ", autoplay=true) }}
  301. {{ vimeo(id="210073083") }}
  302. {{ gist(url="https://gist.github.com/Keats/32d26f699dcc13ebd41b") }}
  303. "#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  304. assert!(res.contains("<p>Hello</p>\n<div >"));
  305. assert!(res.contains(r#"<iframe src="https://www.youtube.com/embed/ub36ffWAqgQ""#));
  306. assert!(res.contains(r#"<iframe src="https://www.youtube.com/embed/ub36ffWAqgQ?autoplay=1""#));
  307. assert!(res.contains(r#"//player.vimeo.com/video/210073083""#));
  308. }
  309. #[test]
  310. fn test_markdown_to_html_shortcode_in_code_block() {
  311. let res = markdown_to_html(r#"```{{ youtube(id="w7Ft2ymGmfc") }}```"#, &HashMap::new(), &GUTENBERG_TERA, &Config::default()).unwrap();
  312. assert_eq!(res, "<p><code>{{ youtube(id=&quot;w7Ft2ymGmfc&quot;) }}</code></p>\n");
  313. }
  314. #[test]
  315. fn test_markdown_to_html_shortcode_with_body() {
  316. let mut tera = Tera::default();
  317. tera.extend(&GUTENBERG_TERA).unwrap();
  318. tera.add_raw_template("shortcodes/quote.html", "<blockquote>{{ body }} - {{ author}}</blockquote>").unwrap();
  319. let res = markdown_to_html(r#"
  320. Hello
  321. {% quote(author="Keats") %}
  322. A quote
  323. {% end %}
  324. "#, &HashMap::new(), &tera, &Config::default()).unwrap();
  325. assert_eq!(res, "<p>Hello\n</p><blockquote>A quote - Keats</blockquote>");
  326. }
  327. }