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

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. use std::borrow::Cow::Owned;
  2. use pulldown_cmark as cmark;
  3. use self::cmark::{Parser, Event, Tag, Options, OPTION_ENABLE_TABLES, OPTION_ENABLE_FOOTNOTES};
  4. use slug::slugify;
  5. use syntect::easy::HighlightLines;
  6. use syntect::html::{start_coloured_html_snippet, styles_to_coloured_html, IncludeBackground};
  7. use errors::Result;
  8. use utils::site::resolve_internal_link;
  9. use highlighting::{get_highlighter, THEME_SET};
  10. use link_checker::check_url;
  11. use table_of_contents::{TempHeader, Header, make_table_of_contents};
  12. use context::RenderContext;
  13. // We might have cases where the slug is already present in our list of anchor
  14. // for example an article could have several titles named Example
  15. // We add a counter after the slug if the slug is already present, which
  16. // means we will have example, example-1, example-2 etc
  17. fn find_anchor(anchors: &[String], name: String, level: u8) -> String {
  18. if level == 0 && !anchors.contains(&name) {
  19. return name.to_string();
  20. }
  21. let new_anchor = format!("{}-{}", name, level + 1);
  22. if !anchors.contains(&new_anchor) {
  23. return new_anchor;
  24. }
  25. find_anchor(anchors, name, level + 1)
  26. }
  27. fn is_colocated_asset_link(link: &str) -> bool {
  28. !link.contains("/") // http://, ftp://, ../ etc
  29. && !link.starts_with("mailto:")
  30. }
  31. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<(String, Vec<Header>)> {
  32. // the rendered html
  33. let mut html = String::with_capacity(content.len());
  34. // Set while parsing
  35. let mut error = None;
  36. let mut highlighter: Option<HighlightLines> = None;
  37. // If we get text in header, we need to insert the id and a anchor
  38. let mut in_header = false;
  39. // pulldown_cmark can send several text events for a title if there are markdown
  40. // specific characters like `!` in them. We only want to insert the anchor the first time
  41. let mut header_created = false;
  42. let mut anchors: Vec<String> = vec![];
  43. let mut headers = vec![];
  44. // Defaults to a 0 level so not a real header
  45. // It should be an Option ideally but not worth the hassle to update
  46. let mut temp_header = TempHeader::default();
  47. let mut opts = Options::empty();
  48. opts.insert(OPTION_ENABLE_TABLES);
  49. opts.insert(OPTION_ENABLE_FOOTNOTES);
  50. {
  51. let parser = Parser::new_ext(content, opts).map(|event| {
  52. match event {
  53. Event::Text(text) => {
  54. // Header first
  55. if in_header {
  56. if header_created {
  57. temp_header.push(&text);
  58. return Event::Html(Owned(String::new()));
  59. }
  60. let id = find_anchor(&anchors, slugify(&text), 0);
  61. anchors.push(id.clone());
  62. // update the header and add it to the list
  63. temp_header.permalink = format!("{}#{}", context.current_page_permalink, id);
  64. temp_header.id = id;
  65. // += as we might have some <code> or other things already there
  66. temp_header.title += &text;
  67. header_created = true;
  68. return Event::Html(Owned(String::new()));
  69. }
  70. // if we are in the middle of a code block
  71. if let Some(ref mut highlighter) = highlighter {
  72. let highlighted = &highlighter.highlight(&text);
  73. let html = styles_to_coloured_html(highlighted, IncludeBackground::Yes);
  74. return Event::Html(Owned(html));
  75. }
  76. // Business as usual
  77. Event::Text(text)
  78. }
  79. Event::Start(Tag::CodeBlock(ref info)) => {
  80. if !context.config.highlight_code {
  81. return Event::Html(Owned("<pre><code>".to_string()));
  82. }
  83. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  84. highlighter = Some(get_highlighter(&theme, info));
  85. let snippet = start_coloured_html_snippet(theme);
  86. Event::Html(Owned(snippet))
  87. }
  88. Event::End(Tag::CodeBlock(_)) => {
  89. if !context.config.highlight_code {
  90. return Event::Html(Owned("</code></pre>\n".to_string()));
  91. }
  92. // reset highlight and close the code block
  93. highlighter = None;
  94. Event::Html(Owned("</pre>".to_string()))
  95. }
  96. Event::Start(Tag::Image(src, title)) => {
  97. if is_colocated_asset_link(&src) {
  98. return Event::Start(
  99. Tag::Image(
  100. Owned(format!("{}{}", context.current_page_permalink, src)),
  101. title,
  102. )
  103. );
  104. }
  105. Event::Start(Tag::Image(src, title))
  106. }
  107. Event::Start(Tag::Link(link, title)) => {
  108. // A few situations here:
  109. // - it could be a relative link (starting with `./`)
  110. // - it could be a link to a co-located asset
  111. // - it could be a normal link
  112. // - any of those can be in a header or not: if it's in a header
  113. // we need to append to a string
  114. let fixed_link = if link.starts_with("./") {
  115. match resolve_internal_link(&link, context.permalinks) {
  116. Ok(url) => url,
  117. Err(_) => {
  118. error = Some(format!("Relative link {} not found.", link).into());
  119. return Event::Html(Owned(String::new()));
  120. }
  121. }
  122. } else if is_colocated_asset_link(&link) {
  123. format!("{}{}", context.current_page_permalink, link)
  124. } else {
  125. if context.config.check_external_links && !link.starts_with('#') {
  126. let res = check_url(&link);
  127. if res.is_valid() {
  128. link.to_string()
  129. } else {
  130. error = Some(
  131. format!("Link {} is not valid: {}", link, res.message()).into()
  132. );
  133. String::new()
  134. }
  135. } else {
  136. link.to_string()
  137. }
  138. };
  139. if in_header {
  140. let html = if title.is_empty() {
  141. format!("<a href=\"{}\">", fixed_link)
  142. } else {
  143. format!("<a href=\"{}\" title=\"{}\">", fixed_link, title)
  144. };
  145. temp_header.push(&html);
  146. return Event::Html(Owned(String::new()));
  147. }
  148. Event::Start(Tag::Link(Owned(fixed_link), title))
  149. }
  150. Event::End(Tag::Link(_, _)) => {
  151. if in_header {
  152. temp_header.push("</a>");
  153. return Event::Html(Owned(String::new()));
  154. }
  155. event
  156. }
  157. Event::Start(Tag::Code) => {
  158. if in_header {
  159. temp_header.push("<code>");
  160. return Event::Html(Owned(String::new()));
  161. }
  162. event
  163. }
  164. Event::End(Tag::Code) => {
  165. if in_header {
  166. temp_header.push("</code>");
  167. return Event::Html(Owned(String::new()));
  168. }
  169. event
  170. }
  171. Event::Start(Tag::Header(num)) => {
  172. in_header = true;
  173. temp_header = TempHeader::new(num);
  174. Event::Html(Owned(String::new()))
  175. }
  176. Event::End(Tag::Header(_)) => {
  177. // End of a header, reset all the things and return the stringified
  178. // version of the header
  179. in_header = false;
  180. header_created = false;
  181. let val = temp_header.to_string(context.tera, context.insert_anchor);
  182. headers.push(temp_header.clone());
  183. temp_header = TempHeader::default();
  184. Event::Html(Owned(val))
  185. }
  186. _ => event,
  187. }
  188. });
  189. cmark::html::push_html(&mut html, parser);
  190. }
  191. match error {
  192. Some(e) => Err(e),
  193. None => Ok((
  194. html.replace("<p></p>", "").replace("</p></p>", "</p>"),
  195. make_table_of_contents(&headers)
  196. )),
  197. }
  198. }