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.

275 lines
10KB

  1. use std::borrow::Cow::{Borrowed, Owned};
  2. use self::cmark::{Event, Options, Parser, Tag};
  3. use pulldown_cmark as cmark;
  4. use slug::slugify;
  5. use syntect::easy::HighlightLines;
  6. use syntect::html::{
  7. start_highlighted_html_snippet, styled_line_to_highlighted_html, IncludeBackground,
  8. };
  9. use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET};
  10. use errors::Result;
  11. use link_checker::check_url;
  12. use utils::site::resolve_internal_link;
  13. use context::RenderContext;
  14. use table_of_contents::{make_table_of_contents, Header, TempHeader};
  15. const CONTINUE_READING: &str = "<p><a name=\"continue-reading\"></a></p>\n";
  16. #[derive(Debug)]
  17. pub struct Rendered {
  18. pub body: String,
  19. pub summary_len: Option<usize>,
  20. pub toc: Vec<Header>,
  21. }
  22. // We might have cases where the slug is already present in our list of anchor
  23. // for example an article could have several titles named Example
  24. // We add a counter after the slug if the slug is already present, which
  25. // means we will have example, example-1, example-2 etc
  26. fn find_anchor(anchors: &[String], name: String, level: u8) -> String {
  27. if level == 0 && !anchors.contains(&name) {
  28. return name;
  29. }
  30. let new_anchor = format!("{}-{}", name, level + 1);
  31. if !anchors.contains(&new_anchor) {
  32. return new_anchor;
  33. }
  34. find_anchor(anchors, name, level + 1)
  35. }
  36. // Colocated asset links refers to the files in the same directory,
  37. // there it should be a filename only
  38. fn is_colocated_asset_link(link: &str) -> bool {
  39. !link.contains('/') // http://, ftp://, ../ etc
  40. && !link.starts_with("mailto:")
  41. }
  42. fn fix_link(link: &str, context: &RenderContext) -> Result<String> {
  43. // A few situations here:
  44. // - it could be a relative link (starting with `./`)
  45. // - it could be a link to a co-located asset
  46. // - it could be a normal link
  47. // - any of those can be in a header or not: if it's in a header
  48. // we need to append to a string
  49. let result = if link.starts_with("./") {
  50. match resolve_internal_link(&link, context.permalinks) {
  51. Ok(url) => url,
  52. Err(_) => {
  53. return Err(format!("Relative link {} not found.", link).into());
  54. }
  55. }
  56. } else if is_colocated_asset_link(&link) {
  57. format!("{}{}", context.current_page_permalink, link)
  58. } else if context.config.check_external_links
  59. && !link.starts_with('#')
  60. && !link.starts_with("mailto:") {
  61. let res = check_url(&link);
  62. if res.is_valid() {
  63. link.to_string()
  64. } else {
  65. return Err(
  66. format!("Link {} is not valid: {}", link, res.message()).into(),
  67. );
  68. }
  69. } else {
  70. link.to_string()
  71. };
  72. Ok(result)
  73. }
  74. fn start_tag(temp_header: &mut TempHeader, tag: &Tag) -> bool {
  75. match tag {
  76. Tag::Emphasis => temp_header.add_html("<em>"),
  77. Tag::Strong => temp_header.add_html("<strong>"),
  78. Tag::Code => temp_header.add_html("<code>"),
  79. // Tag::Link is handled elsewhere
  80. _ => return false,
  81. }
  82. true
  83. }
  84. fn end_tag(temp_header: &mut TempHeader, tag: &Tag) -> bool {
  85. match tag {
  86. Tag::Emphasis => temp_header.add_html("</em>"),
  87. Tag::Strong => temp_header.add_html("</strong>"),
  88. Tag::Code => temp_header.add_html("</code>"),
  89. Tag::Link(_, _) => temp_header.add_html("</a>"),
  90. _ => return false,
  91. }
  92. true
  93. }
  94. /// returns true if event have been processed
  95. fn push_to_temp_header(event: &Event, temp_header: &mut TempHeader) -> bool {
  96. match event {
  97. Event::Start(tag) => start_tag(temp_header, tag),
  98. Event::End(tag) => end_tag(temp_header, tag),
  99. _ => false,
  100. }
  101. }
  102. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Rendered> {
  103. // the rendered html
  104. let mut html = String::with_capacity(content.len());
  105. // Set while parsing
  106. let mut error = None;
  107. let mut background = IncludeBackground::Yes;
  108. let mut highlighter: Option<(HighlightLines, bool)> = None;
  109. // If we get text in header, we need to insert the id and a anchor
  110. let mut in_header = false;
  111. // pulldown_cmark can send several text events for a title if there are markdown
  112. // specific characters like `!` in them. We only want to insert the anchor the first time
  113. let mut header_created = false;
  114. let mut anchors: Vec<String> = vec![];
  115. let mut headers = vec![];
  116. // Defaults to a 0 level so not a real header
  117. // It should be an Option ideally but not worth the hassle to update
  118. let mut temp_header = TempHeader::default();
  119. let mut opts = Options::empty();
  120. let mut has_summary = false;
  121. opts.insert(Options::ENABLE_TABLES);
  122. opts.insert(Options::ENABLE_FOOTNOTES);
  123. {
  124. let parser = Parser::new_ext(content, opts).map(|event| {
  125. // Trivial markup generation
  126. if in_header && push_to_temp_header(&event, &mut temp_header) {
  127. return Event::Html(Borrowed(""));
  128. }
  129. match event {
  130. Event::Text(text) => {
  131. // Header first
  132. if in_header {
  133. if header_created {
  134. temp_header.add_text(&text);
  135. return Event::Html(Borrowed(""));
  136. }
  137. // += as we might have some <code> or other things already there
  138. temp_header.add_text(&text);
  139. header_created = true;
  140. return Event::Html(Borrowed(""));
  141. }
  142. // if we are in the middle of a code block
  143. if let Some((ref mut highlighter, in_extra)) = highlighter {
  144. let highlighted = if in_extra {
  145. if let Some(ref extra) = context.config.extra_syntax_set {
  146. highlighter.highlight(&text, &extra)
  147. } else {
  148. unreachable!("Got a highlighter from extra syntaxes but no extra?");
  149. }
  150. } else {
  151. highlighter.highlight(&text, &SYNTAX_SET)
  152. };
  153. //let highlighted = &highlighter.highlight(&text, ss);
  154. let html = styled_line_to_highlighted_html(&highlighted, background);
  155. return Event::Html(Owned(html));
  156. }
  157. // Business as usual
  158. Event::Text(text)
  159. }
  160. Event::Start(Tag::CodeBlock(ref info)) => {
  161. if !context.config.highlight_code {
  162. return Event::Html(Borrowed("<pre><code>"));
  163. }
  164. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  165. highlighter = Some(get_highlighter(info, &context.config));
  166. // This selects the background color the same way that start_coloured_html_snippet does
  167. let color =
  168. theme.settings.background.unwrap_or(::syntect::highlighting::Color::WHITE);
  169. background = IncludeBackground::IfDifferent(color);
  170. let snippet = start_highlighted_html_snippet(theme);
  171. Event::Html(Owned(snippet.0))
  172. }
  173. Event::End(Tag::CodeBlock(_)) => {
  174. if !context.config.highlight_code {
  175. return Event::Html(Borrowed("</code></pre>\n"));
  176. }
  177. // reset highlight and close the code block
  178. highlighter = None;
  179. Event::Html(Borrowed("</pre>"))
  180. }
  181. Event::Start(Tag::Image(src, title)) => {
  182. if is_colocated_asset_link(&src) {
  183. return Event::Start(Tag::Image(
  184. Owned(format!("{}{}", context.current_page_permalink, src)),
  185. title,
  186. ));
  187. }
  188. Event::Start(Tag::Image(src, title))
  189. }
  190. Event::Start(Tag::Link(link, title)) => {
  191. let fixed_link = match fix_link(&link, context) {
  192. Ok(fixed_link) => fixed_link,
  193. Err(err) => {
  194. error = Some(err);
  195. return Event::Html(Borrowed(""))
  196. }
  197. };
  198. if in_header {
  199. let html = if title.is_empty() {
  200. format!("<a href=\"{}\">", fixed_link)
  201. } else {
  202. format!("<a href=\"{}\" title=\"{}\">", fixed_link, title)
  203. };
  204. temp_header.add_html(&html);
  205. return Event::Html(Borrowed(""));
  206. }
  207. Event::Start(Tag::Link(Owned(fixed_link), title))
  208. }
  209. Event::Start(Tag::Header(num)) => {
  210. in_header = true;
  211. temp_header = TempHeader::new(num);
  212. Event::Html(Borrowed(""))
  213. }
  214. Event::End(Tag::Header(_)) => {
  215. // End of a header, reset all the things and return the header string
  216. let id = find_anchor(&anchors, slugify(&temp_header.title), 0);
  217. anchors.push(id.clone());
  218. temp_header.permalink = format!("{}#{}", context.current_page_permalink, id);
  219. temp_header.id = id;
  220. in_header = false;
  221. header_created = false;
  222. let val = temp_header.to_string(context.tera, context.insert_anchor);
  223. headers.push(temp_header.clone());
  224. temp_header = TempHeader::default();
  225. Event::Html(Owned(val))
  226. }
  227. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  228. has_summary = true;
  229. Event::Html(Borrowed(CONTINUE_READING))
  230. }
  231. _ => event,
  232. }
  233. });
  234. cmark::html::push_html(&mut html, parser);
  235. }
  236. if let Some(e) = error {
  237. return Err(e);
  238. } else {
  239. Ok(Rendered {
  240. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  241. body: html,
  242. toc: make_table_of_contents(&headers),
  243. })
  244. }
  245. }