1 //! Markdown formatting for rustdoc
3 //! This module implements markdown formatting through the pulldown-cmark
4 //! rust-library. This module exposes all of the
5 //! functionality through a unit-struct, `Markdown`, which has an implementation
6 //! of `fmt::Display`. Example usage:
9 //! #![feature(rustc_private)]
11 //! use rustdoc::html::markdown::{IdMap, Markdown, ErrorCodes};
12 //! use std::cell::RefCell;
14 //! let s = "My *markdown* _text_";
15 //! let mut id_map = IdMap::new();
16 //! let html = format!("{}", Markdown(s, &[], RefCell::new(&mut id_map), ErrorCodes::Yes));
17 //! // ... something using html
20 #![allow(non_camel_case_types)]
22 use rustc_data_structures::fx::FxHashMap;
23 use std::cell::RefCell;
24 use std::collections::VecDeque;
25 use std::default::Default;
26 use std::fmt::{self, Write};
30 use syntax::edition::Edition;
32 use html::toc::TocBuilder;
36 use pulldown_cmark::{html, Event, Tag, Parser};
37 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
39 /// A unit struct which has the `fmt::Display` trait implemented. When
40 /// formatted, this struct will emit the HTML corresponding to the rendered
41 /// version of the contained markdown string.
42 /// The second parameter is a list of link replacements
43 pub struct Markdown<'a>(
44 pub &'a str, pub &'a [(String, String)], pub RefCell<&'a mut IdMap>, pub ErrorCodes);
45 /// A unit struct like `Markdown`, that renders the markdown with a
46 /// table of contents.
47 pub struct MarkdownWithToc<'a>(pub &'a str, pub RefCell<&'a mut IdMap>, pub ErrorCodes);
48 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
49 pub struct MarkdownHtml<'a>(pub &'a str, pub RefCell<&'a mut IdMap>, pub ErrorCodes);
50 /// A unit struct like `Markdown`, that renders only the first paragraph.
51 pub struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [(String, String)]);
53 #[derive(Copy, Clone, PartialEq, Debug)]
60 pub fn from(b: bool) -> Self {
62 true => ErrorCodes::Yes,
63 false => ErrorCodes::No,
67 pub fn as_bool(self) -> bool {
69 ErrorCodes::Yes => true,
70 ErrorCodes::No => false,
75 /// Controls whether a line will be hidden or shown in HTML output.
77 /// All lines are used in documentation tests.
84 fn for_html(self) -> Option<Cow<'a, str>> {
86 Line::Shown(l) => Some(l),
87 Line::Hidden(_) => None,
91 fn for_code(self) -> Cow<'a, str> {
94 Line::Hidden(l) => Cow::Borrowed(l),
99 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
100 // have no easy way of removing a potential single space after the hashes, which
101 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
102 // order to fix it we'd have to iterate to find the first non-# character, and
103 // then reallocate to remove it; which would make us return a String.
104 fn map_line(s: &str) -> Line {
105 let trimmed = s.trim();
106 if trimmed.starts_with("##") {
107 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
108 } else if trimmed.starts_with("# ") {
110 Line::Hidden(&trimmed[2..])
111 } else if trimmed == "#" {
112 // We cannot handle '#text' because it could be #[attr].
115 Line::Shown(Cow::Borrowed(s))
119 /// Convert chars from a title for an id.
121 /// "Hello, world!" -> "hello-world"
122 fn slugify(c: char) -> Option<char> {
123 if c.is_alphanumeric() || c == '-' || c == '_' {
125 Some(c.to_ascii_lowercase())
129 } else if c.is_whitespace() && c.is_ascii() {
136 // Information about the playground if a URL has been specified, containing an
137 // optional crate name and the URL.
138 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
142 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
143 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
145 check_error_codes: ErrorCodes,
148 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
149 fn new(iter: I, error_codes: ErrorCodes) -> Self {
152 check_error_codes: error_codes,
157 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
158 type Item = Event<'a>;
160 fn next(&mut self) -> Option<Self::Item> {
161 let event = self.inner.next();
165 if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
166 let parse_result = LangString::parse(&lang, self.check_error_codes);
167 if !parse_result.rust {
168 return Some(Event::Start(Tag::CodeBlock(lang)));
170 compile_fail = parse_result.compile_fail;
171 ignore = parse_result.ignore;
172 edition = parse_result.edition;
177 let mut origtext = String::new();
178 for event in &mut self.inner {
180 Event::End(Tag::CodeBlock(..)) => break,
181 Event::Text(ref s) => {
182 origtext.push_str(s);
187 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
188 let text = lines.collect::<Vec<Cow<str>>>().join("\n");
189 PLAYGROUND.with(|play| {
190 // insert newline to clearly separate it from the
191 // previous block so we can shorten the html output
192 let mut s = String::from("\n");
193 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
197 let test = origtext.lines()
198 .map(|l| map_line(l).for_code())
199 .collect::<Vec<Cow<str>>>().join("\n");
200 let krate = krate.as_ref().map(|s| &**s);
201 let (test, _) = test::make_test(&test, krate, false,
202 &Default::default());
203 let channel = if test.contains("#![feature(") {
204 "&version=nightly"
209 let edition_string = if let Some(e @ Edition::Edition2018) = edition {
210 format!("&edition={}{}", e,
211 if channel == "&version=nightly" { "" }
212 else { "&version=nightly" })
213 } else if let Some(e) = edition {
214 format!("&edition={}", e)
219 // These characters don't need to be escaped in a URI.
220 // FIXME: use a library function for percent encoding.
221 fn dont_escape(c: u8) -> bool {
222 (b'a' <= c && c <= b'z') ||
223 (b'A' <= c && c <= b'Z') ||
224 (b'0' <= c && c <= b'9') ||
225 c == b'-' || c == b'_' || c == b'.' ||
226 c == b'~' || c == b'!' || c == b'\'' ||
227 c == b'(' || c == b')' || c == b'*'
229 let mut test_escaped = String::new();
230 for b in test.bytes() {
232 test_escaped.push(char::from(b));
234 write!(test_escaped, "%{:02X}", b).unwrap();
238 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
239 url, test_escaped, channel, edition_string
243 let tooltip = if ignore {
244 Some(("This example is not tested".to_owned(), "ignore"))
245 } else if compile_fail {
246 Some(("This example deliberately fails to compile".to_owned(), "compile_fail"))
247 } else if let Some(e) = edition {
248 Some((format!("This code runs with edition {}", e), "edition"))
253 if let Some((s1, s2)) = tooltip {
254 s.push_str(&highlight::render_with_highlighting(
256 Some(&format!("rust-example-rendered{}",
257 if ignore { " ignore" }
258 else if compile_fail { " compile_fail" }
259 else if edition.is_some() { " edition " }
261 playground_button.as_ref().map(String::as_str),
262 Some((s1.as_str(), s2))));
263 Some(Event::Html(s.into()))
265 s.push_str(&highlight::render_with_highlighting(
267 Some(&format!("rust-example-rendered{}",
268 if ignore { " ignore" }
269 else if compile_fail { " compile_fail" }
270 else if edition.is_some() { " edition " }
272 playground_button.as_ref().map(String::as_str),
274 Some(Event::Html(s.into()))
280 /// Make headings links with anchor ids and build up TOC.
281 struct LinkReplacer<'a, 'b, I: Iterator<Item = Event<'a>>> {
283 links: &'b [(String, String)],
286 impl<'a, 'b, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, 'b, I> {
287 fn new(iter: I, links: &'b [(String, String)]) -> Self {
295 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, 'b, I> {
296 type Item = Event<'a>;
298 fn next(&mut self) -> Option<Self::Item> {
299 let event = self.inner.next();
300 if let Some(Event::Start(Tag::Link(dest, text))) = event {
301 if let Some(&(_, ref replace)) = self.links.into_iter().find(|link| &*link.0 == &*dest)
303 Some(Event::Start(Tag::Link(replace.to_owned().into(), text)))
305 Some(Event::Start(Tag::Link(dest, text)))
313 /// Make headings links with anchor ids and build up TOC.
314 struct HeadingLinks<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> {
316 toc: Option<&'b mut TocBuilder>,
317 buf: VecDeque<Event<'a>>,
318 id_map: &'ids mut IdMap,
321 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, 'ids, I> {
322 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
326 buf: VecDeque::new(),
332 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, 'ids, I> {
333 type Item = Event<'a>;
335 fn next(&mut self) -> Option<Self::Item> {
336 if let Some(e) = self.buf.pop_front() {
340 let event = self.inner.next();
341 if let Some(Event::Start(Tag::Header(level))) = event {
342 let mut id = String::new();
343 for event in &mut self.inner {
345 Event::End(Tag::Header(..)) => break,
346 Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
349 self.buf.push_back(event);
351 let id = self.id_map.derive(id);
353 if let Some(ref mut builder) = self.toc {
354 let mut html_header = String::new();
355 html::push_html(&mut html_header, self.buf.iter().cloned());
356 let sec = builder.push(level as u32, html_header, id.clone());
357 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
360 self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
362 let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
366 return Some(Event::InlineHtml(start_tags.into()));
372 /// Extracts just the first paragraph.
373 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
379 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
380 fn new(iter: I) -> Self {
389 fn check_if_allowed_tag(t: &Tag) -> bool {
397 | Tag::BlockQuote => true,
402 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
403 type Item = Event<'a>;
405 fn next(&mut self) -> Option<Self::Item> {
406 if self.started && self.depth == 0 {
412 while let Some(event) = self.inner.next() {
413 let mut is_start = true;
414 let is_allowed_tag = match event {
415 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
418 Event::Start(ref c) => {
420 check_if_allowed_tag(c)
422 Event::End(ref c) => {
425 check_if_allowed_tag(c)
431 return if is_allowed_tag == false {
433 Some(Event::Start(Tag::Paragraph))
435 Some(Event::End(Tag::Paragraph))
445 /// Moves all footnote definitions to the end and add back links to the
447 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
449 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
452 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
453 fn new(iter: I) -> Self {
456 footnotes: FxHashMap::default(),
459 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
460 let new_id = self.footnotes.keys().count() + 1;
461 let key = key.to_owned();
462 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
466 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
467 type Item = Event<'a>;
469 fn next(&mut self) -> Option<Self::Item> {
471 match self.inner.next() {
472 Some(Event::FootnoteReference(ref reference)) => {
473 let entry = self.get_entry(&reference);
474 let reference = format!("<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}\
477 return Some(Event::Html(reference.into()));
479 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
480 let mut content = Vec::new();
481 for event in &mut self.inner {
482 if let Event::End(Tag::FootnoteDefinition(..)) = event {
487 let entry = self.get_entry(&def);
488 (*entry).0 = content;
490 Some(e) => return Some(e),
492 if !self.footnotes.is_empty() {
493 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
494 v.sort_by(|a, b| a.1.cmp(&b.1));
495 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
496 for (mut content, id) in v {
497 write!(ret, "<li id=\"fn{}\">", id).unwrap();
498 let mut is_paragraph = false;
499 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
503 html::push_html(&mut ret, content.into_iter());
505 " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>",
508 ret.push_str("</p>");
510 ret.push_str("</li>");
512 ret.push_str("</ol></div>");
513 return Some(Event::Html(ret.into()));
523 pub struct TestableCodeError(());
525 impl fmt::Display for TestableCodeError {
526 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
527 write!(f, "invalid start of a new code block")
531 pub fn find_testable_code<T: test::Tester>(
534 error_codes: ErrorCodes,
535 ) -> Result<(), TestableCodeError> {
536 let mut parser = Parser::new(doc);
537 let mut prev_offset = 0;
538 let mut nb_lines = 0;
539 let mut register_header = None;
540 'main: while let Some(event) = parser.next() {
542 Event::Start(Tag::CodeBlock(s)) => {
543 let block_info = if s.is_empty() {
544 LangString::all_false()
546 LangString::parse(&*s, error_codes)
548 if !block_info.rust {
551 let mut test_s = String::new();
552 let mut offset = None;
554 let event = parser.next();
555 if let Some(event) = event {
557 Event::End(Tag::CodeBlock(_)) => break,
558 Event::Text(ref s) => {
560 if offset.is_none() {
561 offset = Some(parser.get_offset());
570 if let Some(offset) = offset {
571 let lines = test_s.lines().map(|l| map_line(l).for_code());
572 let text = lines.collect::<Vec<Cow<str>>>().join("\n");
573 nb_lines += doc[prev_offset..offset].lines().count();
574 let line = tests.get_line() + (nb_lines - 1);
575 tests.add_test(text, block_info, line);
576 prev_offset = offset;
578 return Err(TestableCodeError(()));
581 Event::Start(Tag::Header(level)) => {
582 register_header = Some(level as u32);
584 Event::Text(ref s) if register_header.is_some() => {
585 let level = register_header.unwrap();
587 tests.register_header("", level);
589 tests.register_header(s, level);
591 register_header = None;
599 #[derive(Eq, PartialEq, Clone, Debug)]
600 pub struct LangString {
602 pub should_panic: bool,
606 pub test_harness: bool,
607 pub compile_fail: bool,
608 pub error_codes: Vec<String>,
609 pub allow_fail: bool,
610 pub edition: Option<Edition>
614 fn all_false() -> LangString {
616 original: String::new(),
620 rust: true, // NB This used to be `notrust = false`
623 error_codes: Vec::new(),
629 fn parse(string: &str, allow_error_code_check: ErrorCodes) -> LangString {
630 let allow_error_code_check = allow_error_code_check.as_bool();
631 let mut seen_rust_tags = false;
632 let mut seen_other_tags = false;
633 let mut data = LangString::all_false();
635 data.original = string.to_owned();
636 let tokens = string.split(|c: char|
637 !(c == '_' || c == '-' || c.is_alphanumeric())
640 for token in tokens {
644 data.should_panic = true;
645 seen_rust_tags = seen_other_tags == false;
647 "no_run" => { data.no_run = true; seen_rust_tags = !seen_other_tags; }
648 "ignore" => { data.ignore = true; seen_rust_tags = !seen_other_tags; }
649 "allow_fail" => { data.allow_fail = true; seen_rust_tags = !seen_other_tags; }
650 "rust" => { data.rust = true; seen_rust_tags = true; }
652 data.test_harness = true;
653 seen_rust_tags = !seen_other_tags || seen_rust_tags;
656 data.compile_fail = true;
657 seen_rust_tags = !seen_other_tags || seen_rust_tags;
660 x if allow_error_code_check && x.starts_with("edition") => {
661 // allow_error_code_check is true if we're on nightly, which
662 // is needed for edition support
663 data.edition = x[7..].parse::<Edition>().ok();
665 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
666 if x[1..].parse::<u32>().is_ok() {
667 data.error_codes.push(x.to_owned());
668 seen_rust_tags = !seen_other_tags || seen_rust_tags;
670 seen_other_tags = true;
673 _ => { seen_other_tags = true }
677 data.rust &= !seen_other_tags || seen_rust_tags;
683 impl<'a> fmt::Display for Markdown<'a> {
684 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
685 let Markdown(md, links, ref ids, codes) = *self;
686 let mut ids = ids.borrow_mut();
688 // This is actually common enough to special-case
689 if md.is_empty() { return Ok(()) }
690 let mut opts = Options::empty();
691 opts.insert(OPTION_ENABLE_TABLES);
692 opts.insert(OPTION_ENABLE_FOOTNOTES);
694 let replacer = |_: &str, s: &str| {
695 if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
696 Some((replace.clone(), s.to_owned()))
702 let p = Parser::new_with_broken_link_callback(md, opts, Some(&replacer));
704 let mut s = String::with_capacity(md.len() * 3 / 2);
706 let p = HeadingLinks::new(p, None, &mut ids);
707 let p = LinkReplacer::new(p, links);
708 let p = CodeBlocks::new(p, codes);
709 let p = Footnotes::new(p);
710 html::push_html(&mut s, p);
716 impl<'a> fmt::Display for MarkdownWithToc<'a> {
717 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
718 let MarkdownWithToc(md, ref ids, codes) = *self;
719 let mut ids = ids.borrow_mut();
721 let mut opts = Options::empty();
722 opts.insert(OPTION_ENABLE_TABLES);
723 opts.insert(OPTION_ENABLE_FOOTNOTES);
725 let p = Parser::new_ext(md, opts);
727 let mut s = String::with_capacity(md.len() * 3 / 2);
729 let mut toc = TocBuilder::new();
732 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
733 let p = CodeBlocks::new(p, codes);
734 let p = Footnotes::new(p);
735 html::push_html(&mut s, p);
738 write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
744 impl<'a> fmt::Display for MarkdownHtml<'a> {
745 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
746 let MarkdownHtml(md, ref ids, codes) = *self;
747 let mut ids = ids.borrow_mut();
749 // This is actually common enough to special-case
750 if md.is_empty() { return Ok(()) }
751 let mut opts = Options::empty();
752 opts.insert(OPTION_ENABLE_TABLES);
753 opts.insert(OPTION_ENABLE_FOOTNOTES);
755 let p = Parser::new_ext(md, opts);
757 // Treat inline HTML as plain text.
758 let p = p.map(|event| match event {
759 Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
763 let mut s = String::with_capacity(md.len() * 3 / 2);
765 let p = HeadingLinks::new(p, None, &mut ids);
766 let p = CodeBlocks::new(p, codes);
767 let p = Footnotes::new(p);
768 html::push_html(&mut s, p);
774 impl<'a> fmt::Display for MarkdownSummaryLine<'a> {
775 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
776 let MarkdownSummaryLine(md, links) = *self;
777 // This is actually common enough to special-case
778 if md.is_empty() { return Ok(()) }
780 let replacer = |_: &str, s: &str| {
781 if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
782 Some((replace.clone(), s.to_owned()))
788 let p = Parser::new_with_broken_link_callback(md, Options::empty(), Some(&replacer));
790 let mut s = String::new();
792 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
798 pub fn plain_summary_line(md: &str) -> String {
799 plain_summary_line_full(md, false)
802 pub fn plain_summary_line_full(md: &str, limit_length: bool) -> String {
803 struct ParserWrapper<'a> {
809 impl<'a> Iterator for ParserWrapper<'a> {
812 fn next(&mut self) -> Option<String> {
813 let next_event = self.inner.next();
814 if next_event.is_none() {
817 let next_event = next_event.unwrap();
818 let (ret, is_in) = match next_event {
819 Event::Start(Tag::Paragraph) => (None, 1),
820 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
821 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
822 Event::Start(Tag::Header(_)) => (None, 1),
823 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
824 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
827 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
831 self.is_first = false;
838 let mut s = String::with_capacity(md.len() * 3 / 2);
839 let mut p = ParserWrapper {
840 inner: Parser::new(md),
844 while let Some(t) = p.next() {
849 if limit_length && s.chars().count() > 60 {
851 let mut ret = s.split_whitespace()
853 // + 1 for the added character after the word.
854 len += p.chars().count() + 1;
866 pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
871 let mut opts = Options::empty();
872 opts.insert(OPTION_ENABLE_TABLES);
873 opts.insert(OPTION_ENABLE_FOOTNOTES);
875 let mut links = vec![];
876 let shortcut_links = RefCell::new(vec![]);
879 let locate = |s: &str| unsafe {
880 let s_start = s.as_ptr();
881 let s_end = s_start.add(s.len());
882 let md_start = md.as_ptr();
883 let md_end = md_start.add(md.len());
884 if md_start <= s_start && s_end <= md_end {
885 let start = s_start.offset_from(md_start) as usize;
886 let end = s_end.offset_from(md_start) as usize;
893 let push = |_: &str, s: &str| {
894 shortcut_links.borrow_mut().push((s.to_owned(), locate(s)));
897 let p = Parser::new_with_broken_link_callback(md, opts,
900 // There's no need to thread an IdMap through to here because
901 // the IDs generated aren't going to be emitted anywhere.
902 let mut ids = IdMap::new();
903 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
906 if let Event::Start(Tag::Link(dest, _)) = ev {
907 debug!("found link: {}", dest);
908 links.push(match dest {
909 Cow::Borrowed(s) => (s.to_owned(), locate(s)),
910 Cow::Owned(s) => (s, None),
916 let mut shortcut_links = shortcut_links.into_inner();
917 links.extend(shortcut_links.drain(..));
923 crate struct RustCodeBlock {
924 /// The range in the markdown that the code block occupies. Note that this includes the fences
925 /// for fenced code blocks.
926 pub range: Range<usize>,
927 /// The range in the markdown that the code within the code block occupies.
928 pub code: Range<usize>,
930 pub syntax: Option<String>,
933 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
934 /// untagged (and assumed to be rust).
935 crate fn rust_code_blocks(md: &str) -> Vec<RustCodeBlock> {
936 let mut code_blocks = vec![];
942 let mut opts = Options::empty();
943 opts.insert(OPTION_ENABLE_TABLES);
944 opts.insert(OPTION_ENABLE_FOOTNOTES);
945 let mut p = Parser::new_ext(md, opts);
947 let mut code_block_start = 0;
948 let mut code_start = 0;
949 let mut is_fenced = false;
950 let mut previous_offset = 0;
951 let mut in_rust_code_block = false;
952 while let Some(event) = p.next() {
953 let offset = p.get_offset();
956 Event::Start(Tag::CodeBlock(syntax)) => {
957 let lang_string = if syntax.is_empty() {
958 LangString::all_false()
960 LangString::parse(&*syntax, ErrorCodes::Yes)
963 if lang_string.rust {
964 in_rust_code_block = true;
967 code_block_start = match md[previous_offset..offset].find("```") {
970 previous_offset + fence_idx
976 Event::End(Tag::CodeBlock(syntax)) if in_rust_code_block => {
977 in_rust_code_block = false;
979 let code_block_end = if is_fenced {
980 let fence_str = &md[previous_offset..offset]
983 .collect::<String>();
986 .map(|fence_idx| offset - fence_idx)
987 .unwrap_or_else(|| offset)
991 .map(|b| *b == b'\n')
999 let code_end = if is_fenced {
1005 code_blocks.push(RustCodeBlock {
1008 start: code_block_start,
1009 end: code_block_end,
1015 syntax: if !syntax.is_empty() {
1016 Some(syntax.into_owned())
1025 previous_offset = offset;
1031 #[derive(Clone, Default, Debug)]
1033 map: FxHashMap<String, usize>,
1037 pub fn new() -> Self {
1041 pub fn populate<I: IntoIterator<Item=String>>(&mut self, ids: I) {
1043 let _ = self.derive(id);
1047 pub fn reset(&mut self) {
1048 self.map = FxHashMap::default();
1051 pub fn derive(&mut self, candidate: String) -> String {
1052 let id = match self.map.get_mut(&candidate) {
1055 let id = format!("{}-{}", candidate, *a);
1061 self.map.insert(id.clone(), 1);
1068 fn test_unique_id() {
1069 let input = ["foo", "examples", "examples", "method.into_iter","examples",
1070 "method.into_iter", "foo", "main", "search", "methods",
1071 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
1072 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
1073 "method.into_iter-1", "foo-1", "main", "search", "methods",
1074 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
1076 let map = RefCell::new(IdMap::new());
1078 let mut map = map.borrow_mut();
1079 let actual: Vec<String> = input.iter().map(|s| map.derive(s.to_string())).collect();
1080 assert_eq!(&actual[..], expected);
1083 map.borrow_mut().reset();
1089 use super::{ErrorCodes, LangString, Markdown, MarkdownHtml, IdMap};
1090 use super::plain_summary_line;
1091 use std::cell::RefCell;
1092 use syntax::edition::Edition;
1095 fn test_lang_string_parse() {
1097 should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
1098 compile_fail: bool, allow_fail: bool, error_codes: Vec<String>,
1099 edition: Option<Edition>) {
1100 assert_eq!(LangString::parse(s, ErrorCodes::Yes), LangString {
1108 original: s.to_owned(),
1114 fn v() -> Vec<String> {
1118 // ignore-tidy-linelength
1119 // marker | should_panic | no_run | ignore | rust | test_harness
1120 // | compile_fail | allow_fail | error_codes | edition
1121 t("", false, false, false, true, false, false, false, v(), None);
1122 t("rust", false, false, false, true, false, false, false, v(), None);
1123 t("sh", false, false, false, false, false, false, false, v(), None);
1124 t("ignore", false, false, true, true, false, false, false, v(), None);
1125 t("should_panic", true, false, false, true, false, false, false, v(), None);
1126 t("no_run", false, true, false, true, false, false, false, v(), None);
1127 t("test_harness", false, false, false, true, true, false, false, v(), None);
1128 t("compile_fail", false, true, false, true, false, true, false, v(), None);
1129 t("allow_fail", false, false, false, true, false, false, true, v(), None);
1130 t("{.no_run .example}", false, true, false, true, false, false, false, v(), None);
1131 t("{.sh .should_panic}", true, false, false, false, false, false, false, v(), None);
1132 t("{.example .rust}", false, false, false, true, false, false, false, v(), None);
1133 t("{.test_harness .rust}", false, false, false, true, true, false, false, v(), None);
1134 t("text, no_run", false, true, false, false, false, false, false, v(), None);
1135 t("text,no_run", false, true, false, false, false, false, false, v(), None);
1136 t("edition2015", false, false, false, true, false, false, false, v(), Some(Edition::Edition2015));
1137 t("edition2018", false, false, false, true, false, false, false, v(), Some(Edition::Edition2018));
1142 fn t(input: &str, expect: &str) {
1143 let mut map = IdMap::new();
1144 let output = Markdown(input, &[], RefCell::new(&mut map), ErrorCodes::Yes).to_string();
1145 assert_eq!(output, expect, "original: {}", input);
1148 t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
1149 <a href=\"#foo-bar\">Foo bar</a></h1>");
1150 t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
1151 header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
1152 t("### **Foo** *bar* baz!?!& -_qux_-%",
1153 "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
1154 <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
1155 <em>bar</em> baz!?!& -<em>qux</em>-%</a></h3>");
1156 t("#### **Foo?** & \\*bar?!* _`baz`_ ❤ #qux",
1157 "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
1158 <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> & *bar?!* \
1159 <em><code>baz</code></em> ❤ #qux</a></h4>");
1163 fn test_header_ids_multiple_blocks() {
1164 let mut map = IdMap::new();
1165 fn t(map: &mut IdMap, input: &str, expect: &str) {
1166 let output = Markdown(input, &[], RefCell::new(map), ErrorCodes::Yes).to_string();
1167 assert_eq!(output, expect, "original: {}", input);
1170 t(&mut map, "# Example", "<h1 id=\"example\" class=\"section-header\">\
1171 <a href=\"#example\">Example</a></h1>");
1172 t(&mut map, "# Panics", "<h1 id=\"panics\" class=\"section-header\">\
1173 <a href=\"#panics\">Panics</a></h1>");
1174 t(&mut map, "# Example", "<h1 id=\"example-1\" class=\"section-header\">\
1175 <a href=\"#example-1\">Example</a></h1>");
1176 t(&mut map, "# Main", "<h1 id=\"main\" class=\"section-header\">\
1177 <a href=\"#main\">Main</a></h1>");
1178 t(&mut map, "# Example", "<h1 id=\"example-2\" class=\"section-header\">\
1179 <a href=\"#example-2\">Example</a></h1>");
1180 t(&mut map, "# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
1181 <a href=\"#panics-1\">Panics</a></h1>");
1185 fn test_plain_summary_line() {
1186 fn t(input: &str, expect: &str) {
1187 let output = plain_summary_line(input);
1188 assert_eq!(output, expect, "original: {}", input);
1191 t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
1192 t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
1193 t("code `let x = i32;` ...", "code `let x = i32;` ...");
1194 t("type `Type<'static>` ...", "type `Type<'static>` ...");
1195 t("# top header", "top header");
1196 t("## header", "header");
1200 fn test_markdown_html_escape() {
1201 fn t(input: &str, expect: &str) {
1202 let mut idmap = IdMap::new();
1203 let output = MarkdownHtml(input, RefCell::new(&mut idmap), ErrorCodes::Yes).to_string();
1204 assert_eq!(output, expect, "original: {}", input);
1207 t("`Struct<'a, T>`", "<p><code>Struct<'a, T></code></p>\n");
1208 t("Struct<'a, T>", "<p>Struct<'a, T></p>\n");
1209 t("Struct<br>", "<p>Struct<br></p>\n");