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.

261 lines
9.9KB

  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. /// returns true if event have been processed
  75. fn push_to_temp_header(event: &Event, temp_header: &mut TempHeader) -> bool {
  76. match event {
  77. Event::End(Tag::Link(_, _)) => {
  78. temp_header.add_html("</a>");
  79. }
  80. Event::Start(Tag::Code) => {
  81. temp_header.add_html("<code>");
  82. }
  83. Event::End(Tag::Code) => {
  84. temp_header.add_html("</code>");
  85. }
  86. _ => return false,
  87. }
  88. true
  89. }
  90. pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Rendered> {
  91. // the rendered html
  92. let mut html = String::with_capacity(content.len());
  93. // Set while parsing
  94. let mut error = None;
  95. let mut background = IncludeBackground::Yes;
  96. let mut highlighter: Option<(HighlightLines, bool)> = None;
  97. // If we get text in header, we need to insert the id and a anchor
  98. let mut in_header = false;
  99. // pulldown_cmark can send several text events for a title if there are markdown
  100. // specific characters like `!` in them. We only want to insert the anchor the first time
  101. let mut header_created = false;
  102. let mut anchors: Vec<String> = vec![];
  103. let mut headers = vec![];
  104. // Defaults to a 0 level so not a real header
  105. // It should be an Option ideally but not worth the hassle to update
  106. let mut temp_header = TempHeader::default();
  107. let mut opts = Options::empty();
  108. let mut has_summary = false;
  109. opts.insert(Options::ENABLE_TABLES);
  110. opts.insert(Options::ENABLE_FOOTNOTES);
  111. {
  112. let parser = Parser::new_ext(content, opts).map(|event| {
  113. // Header first
  114. if in_header && push_to_temp_header(&event, &mut temp_header) {
  115. return Event::Html(Borrowed(""));
  116. }
  117. match event {
  118. Event::Text(text) => {
  119. // Header first
  120. if in_header {
  121. if header_created {
  122. temp_header.add_text(&text);
  123. return Event::Html(Borrowed(""));
  124. }
  125. // += as we might have some <code> or other things already there
  126. temp_header.add_text(&text);
  127. header_created = true;
  128. return Event::Html(Borrowed(""));
  129. }
  130. // if we are in the middle of a code block
  131. if let Some((ref mut highlighter, in_extra)) = highlighter {
  132. let highlighted = if in_extra {
  133. if let Some(ref extra) = context.config.extra_syntax_set {
  134. highlighter.highlight(&text, &extra)
  135. } else {
  136. unreachable!("Got a highlighter from extra syntaxes but no extra?");
  137. }
  138. } else {
  139. highlighter.highlight(&text, &SYNTAX_SET)
  140. };
  141. //let highlighted = &highlighter.highlight(&text, ss);
  142. let html = styled_line_to_highlighted_html(&highlighted, background);
  143. return Event::Html(Owned(html));
  144. }
  145. // Business as usual
  146. Event::Text(text)
  147. }
  148. Event::Start(Tag::CodeBlock(ref info)) => {
  149. if !context.config.highlight_code {
  150. return Event::Html(Borrowed("<pre><code>"));
  151. }
  152. let theme = &THEME_SET.themes[&context.config.highlight_theme];
  153. highlighter = Some(get_highlighter(info, &context.config));
  154. // This selects the background color the same way that start_coloured_html_snippet does
  155. let color =
  156. theme.settings.background.unwrap_or(::syntect::highlighting::Color::WHITE);
  157. background = IncludeBackground::IfDifferent(color);
  158. let snippet = start_highlighted_html_snippet(theme);
  159. Event::Html(Owned(snippet.0))
  160. }
  161. Event::End(Tag::CodeBlock(_)) => {
  162. if !context.config.highlight_code {
  163. return Event::Html(Borrowed("</code></pre>\n"));
  164. }
  165. // reset highlight and close the code block
  166. highlighter = None;
  167. Event::Html(Borrowed("</pre>"))
  168. }
  169. Event::Start(Tag::Image(src, title)) => {
  170. if is_colocated_asset_link(&src) {
  171. return Event::Start(Tag::Image(
  172. Owned(format!("{}{}", context.current_page_permalink, src)),
  173. title,
  174. ));
  175. }
  176. Event::Start(Tag::Image(src, title))
  177. }
  178. Event::Start(Tag::Link(link, title)) => {
  179. let fixed_link = match fix_link(&link, context) {
  180. Ok(fixed_link) => fixed_link,
  181. Err(err) => {
  182. error = Some(err);
  183. return Event::Html(Borrowed(""))
  184. }
  185. };
  186. if in_header {
  187. let html = if title.is_empty() {
  188. format!("<a href=\"{}\">", fixed_link)
  189. } else {
  190. format!("<a href=\"{}\" title=\"{}\">", fixed_link, title)
  191. };
  192. temp_header.add_html(&html);
  193. return Event::Html(Borrowed(""));
  194. }
  195. Event::Start(Tag::Link(Owned(fixed_link), title))
  196. }
  197. Event::Start(Tag::Header(num)) => {
  198. in_header = true;
  199. temp_header = TempHeader::new(num);
  200. Event::Html(Borrowed(""))
  201. }
  202. Event::End(Tag::Header(_)) => {
  203. // End of a header, reset all the things and return the header string
  204. let id = find_anchor(&anchors, slugify(&temp_header.title), 0);
  205. anchors.push(id.clone());
  206. temp_header.permalink = format!("{}#{}", context.current_page_permalink, id);
  207. temp_header.id = id;
  208. in_header = false;
  209. header_created = false;
  210. let val = temp_header.to_string(context.tera, context.insert_anchor);
  211. headers.push(temp_header.clone());
  212. temp_header = TempHeader::default();
  213. Event::Html(Owned(val))
  214. }
  215. Event::Html(ref markup) if markup.contains("<!-- more -->") => {
  216. has_summary = true;
  217. Event::Html(Borrowed(CONTINUE_READING))
  218. }
  219. _ => event,
  220. }
  221. });
  222. cmark::html::push_html(&mut html, parser);
  223. }
  224. if let Some(e) = error {
  225. return Err(e);
  226. } else {
  227. Ok(Rendered {
  228. summary_len: if has_summary { html.find(CONTINUE_READING) } else { None },
  229. body: html,
  230. toc: make_table_of_contents(&headers),
  231. })
  232. }
  233. }