1 //! Markdown formatting for rustdoc.
3 //! This module implements markdown formatting through the pulldown-cmark library.
6 //! #![feature(rustc_private)]
8 //! extern crate rustc_span;
10 //! use rustc_span::edition::Edition;
11 //! use rustdoc::html::markdown::{IdMap, Markdown, ErrorCodes};
13 //! let s = "My *markdown* _text_";
14 //! let mut id_map = IdMap::new();
15 //! let md = Markdown(s, &[], &mut id_map, ErrorCodes::Yes, Edition::Edition2015, &None);
16 //! let html = md.into_string();
17 //! // ... something using html
20 #![allow(non_camel_case_types)]
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_hir::def_id::DefId;
25 use rustc_middle::ty::TyCtxt;
26 use rustc_session::lint;
27 use rustc_span::edition::Edition;
30 use std::collections::VecDeque;
31 use std::default::Default;
36 use crate::clean::RenderedLink;
38 use crate::html::highlight;
39 use crate::html::toc::TocBuilder;
41 use pulldown_cmark::{html, BrokenLink, CodeBlockKind, CowStr, Event, Options, Parser, Tag};
46 fn opts() -> Options {
47 Options::ENABLE_TABLES | Options::ENABLE_FOOTNOTES | Options::ENABLE_STRIKETHROUGH
50 /// When `to_string` is called, this struct will emit the HTML corresponding to
51 /// the rendered version of the contained markdown string.
52 pub struct Markdown<'a>(
54 /// A list of link replacements.
55 pub &'a [RenderedLink],
56 /// The current list of used header IDs.
58 /// Whether to allow the use of explicit error codes in doctest lang strings.
60 /// Default edition to use when parsing doctests (to add a `fn main`).
62 pub &'a Option<Playground>,
64 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
65 pub struct MarkdownWithToc<'a>(
70 pub &'a Option<Playground>,
72 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
73 pub struct MarkdownHtml<'a>(
78 pub &'a Option<Playground>,
80 /// A tuple struct like `Markdown` that renders only the first paragraph.
81 pub struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
83 #[derive(Copy, Clone, PartialEq, Debug)]
90 pub fn from(b: bool) -> Self {
92 true => ErrorCodes::Yes,
93 false => ErrorCodes::No,
97 pub fn as_bool(self) -> bool {
99 ErrorCodes::Yes => true,
100 ErrorCodes::No => false,
105 /// Controls whether a line will be hidden or shown in HTML output.
107 /// All lines are used in documentation tests.
114 fn for_html(self) -> Option<Cow<'a, str>> {
116 Line::Shown(l) => Some(l),
117 Line::Hidden(_) => None,
121 fn for_code(self) -> Cow<'a, str> {
124 Line::Hidden(l) => Cow::Borrowed(l),
129 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
130 // have no easy way of removing a potential single space after the hashes, which
131 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
132 // order to fix it we'd have to iterate to find the first non-# character, and
133 // then reallocate to remove it; which would make us return a String.
134 fn map_line(s: &str) -> Line<'_> {
135 let trimmed = s.trim();
136 if trimmed.starts_with("##") {
137 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
138 } else if trimmed.starts_with("# ") {
140 Line::Hidden(&trimmed[2..])
141 } else if trimmed == "#" {
142 // We cannot handle '#text' because it could be #[attr].
145 Line::Shown(Cow::Borrowed(s))
149 /// Convert chars from a title for an id.
151 /// "Hello, world!" -> "hello-world"
152 fn slugify(c: char) -> Option<char> {
153 if c.is_alphanumeric() || c == '-' || c == '_' {
154 if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
155 } else if c.is_whitespace() && c.is_ascii() {
162 #[derive(Clone, Debug)]
163 pub struct Playground {
164 pub crate_name: Option<String>,
168 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
169 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
171 check_error_codes: ErrorCodes,
173 // Information about the playground if a URL has been specified, containing an
174 // optional crate name and the URL.
175 playground: &'p Option<Playground>,
178 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
181 error_codes: ErrorCodes,
183 playground: &'p Option<Playground>,
185 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
189 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
190 type Item = Event<'a>;
192 fn next(&mut self) -> Option<Self::Item> {
193 let event = self.inner.next();
198 if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
199 let parse_result = match kind {
200 CodeBlockKind::Fenced(ref lang) => {
201 LangString::parse_without_check(&lang, self.check_error_codes, false)
203 CodeBlockKind::Indented => LangString::all_false(),
205 if !parse_result.rust {
206 return Some(Event::Start(Tag::CodeBlock(kind)));
208 compile_fail = parse_result.compile_fail;
209 should_panic = parse_result.should_panic;
210 ignore = parse_result.ignore;
211 edition = parse_result.edition;
216 let explicit_edition = edition.is_some();
217 let edition = edition.unwrap_or(self.edition);
219 let mut origtext = String::new();
220 for event in &mut self.inner {
222 Event::End(Tag::CodeBlock(..)) => break,
223 Event::Text(ref s) => {
224 origtext.push_str(s);
229 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
230 let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
231 // insert newline to clearly separate it from the
232 // previous block so we can shorten the html output
233 let mut s = String::from("\n");
234 let playground_button = self.playground.as_ref().and_then(|playground| {
235 let krate = &playground.crate_name;
236 let url = &playground.url;
242 .map(|l| map_line(l).for_code())
243 .collect::<Vec<Cow<'_, str>>>()
245 let krate = krate.as_ref().map(|s| &**s);
246 let (test, _) = doctest::make_test(&test, krate, false, &Default::default(), edition);
247 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
249 let edition_string = format!("&edition={}", edition);
251 // These characters don't need to be escaped in a URI.
252 // FIXME: use a library function for percent encoding.
253 fn dont_escape(c: u8) -> bool {
254 (b'a' <= c && c <= b'z')
255 || (b'A' <= c && c <= b'Z')
256 || (b'0' <= c && c <= b'9')
267 let mut test_escaped = String::new();
268 for b in test.bytes() {
270 test_escaped.push(char::from(b));
272 write!(test_escaped, "%{:02X}", b).unwrap();
276 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
277 url, test_escaped, channel, edition_string
281 let tooltip = if ignore != Ignore::None {
282 Some(("This example is not tested".to_owned(), "ignore"))
283 } else if compile_fail {
284 Some(("This example deliberately fails to compile".to_owned(), "compile_fail"))
285 } else if should_panic {
286 Some(("This example panics".to_owned(), "should_panic"))
287 } else if explicit_edition {
288 Some((format!("This code runs with edition {}", edition), "edition"))
293 if let Some((s1, s2)) = tooltip {
294 s.push_str(&highlight::render_with_highlighting(
297 "rust-example-rendered{}",
298 if ignore != Ignore::None {
300 } else if compile_fail {
302 } else if should_panic {
304 } else if explicit_edition {
310 playground_button.as_deref(),
311 Some((s1.as_str(), s2)),
313 Some(Event::Html(s.into()))
315 s.push_str(&highlight::render_with_highlighting(
318 "rust-example-rendered{}",
319 if ignore != Ignore::None {
321 } else if compile_fail {
323 } else if should_panic {
325 } else if explicit_edition {
331 playground_button.as_deref(),
334 Some(Event::Html(s.into()))
339 /// Make headings links with anchor IDs and build up TOC.
340 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
342 links: &'a [RenderedLink],
343 shortcut_link: Option<&'a RenderedLink>,
346 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
347 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
348 LinkReplacer { inner: iter, links, shortcut_link: None }
352 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
353 type Item = Event<'a>;
355 fn next(&mut self) -> Option<Self::Item> {
356 use pulldown_cmark::LinkType;
358 let mut event = self.inner.next();
360 // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
362 // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
363 // Remove any disambiguator.
364 Some(Event::Start(Tag::Link(
365 // [fn@f] or [fn@f][]
366 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
370 debug!("saw start of shortcut link to {} with title {}", dest, title);
371 // If this is a shortcut link, it was resolved by the broken_link_callback.
372 // So the URL will already be updated properly.
373 let link = self.links.iter().find(|&link| *link.href == **dest);
374 // Since this is an external iterator, we can't replace the inner text just yet.
375 // Store that we saw a link so we know to replace it later.
376 if let Some(link) = link {
377 trace!("it matched");
378 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
379 self.shortcut_link = Some(link);
382 // Now that we're done with the shortcut link, don't replace any more text.
383 Some(Event::End(Tag::Link(
384 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
388 debug!("saw end of shortcut link to {}", dest);
389 if self.links.iter().find(|&link| *link.href == **dest).is_some() {
390 assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
391 self.shortcut_link = None;
394 // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
396 Some(Event::Code(text)) => {
397 trace!("saw code {}", text);
398 if let Some(link) = self.shortcut_link {
399 trace!("original text was {}", link.original_text);
400 // NOTE: this only replaces if the code block is the *entire* text.
401 // If only part of the link has code highlighting, the disambiguator will not be removed.
403 // This is a limitation from `collect_intra_doc_links`: it passes a full link,
404 // and does not distinguish at all between code blocks.
405 // So we could never be sure we weren't replacing too much:
406 // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
408 // NOTE: &[1..len() - 1] is to strip the backticks
409 if **text == link.original_text[1..link.original_text.len() - 1] {
410 debug!("replacing {} with {}", text, link.new_text);
411 *text = CowStr::Borrowed(&link.new_text);
415 // Replace plain text in links, but only in the middle of a shortcut link.
417 Some(Event::Text(text)) => {
418 trace!("saw text {}", text);
419 if let Some(link) = self.shortcut_link {
420 trace!("original text was {}", link.original_text);
421 // NOTE: same limitations as `Event::Code`
422 if **text == *link.original_text {
423 debug!("replacing {} with {}", text, link.new_text);
424 *text = CowStr::Borrowed(&link.new_text);
428 // If this is a link, but not a shortcut link,
429 // replace the URL, since the broken_link_callback was not called.
430 Some(Event::Start(Tag::Link(_, dest, _))) => {
431 if let Some(link) = self.links.iter().find(|&link| *link.original_text == **dest) {
432 *dest = CowStr::Borrowed(link.href.as_ref());
435 // Anything else couldn't have been a valid Rust path, so no need to replace the text.
439 // Yield the modified event
444 /// Make headings links with anchor IDs and build up TOC.
445 struct HeadingLinks<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> {
447 toc: Option<&'b mut TocBuilder>,
448 buf: VecDeque<Event<'a>>,
449 id_map: &'ids mut IdMap,
452 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, 'ids, I> {
453 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
454 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
458 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, 'ids, I> {
459 type Item = Event<'a>;
461 fn next(&mut self) -> Option<Self::Item> {
462 if let Some(e) = self.buf.pop_front() {
466 let event = self.inner.next();
467 if let Some(Event::Start(Tag::Heading(level))) = event {
468 let mut id = String::new();
469 for event in &mut self.inner {
471 Event::End(Tag::Heading(..)) => break,
472 Event::Text(text) | Event::Code(text) => {
473 id.extend(text.chars().filter_map(slugify));
478 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
479 event => self.buf.push_back(event),
482 let id = self.id_map.derive(id);
484 if let Some(ref mut builder) = self.toc {
485 let mut html_header = String::new();
486 html::push_html(&mut html_header, self.buf.iter().cloned());
487 let sec = builder.push(level as u32, html_header, id.clone());
488 self.buf.push_front(Event::Html(format!("{} ", sec).into()));
491 self.buf.push_back(Event::Html(format!("</a></h{}>", level).into()));
493 let start_tags = format!(
494 "<h{level} id=\"{id}\" class=\"section-header\">\
499 return Some(Event::Html(start_tags.into()));
505 /// Extracts just the first paragraph.
506 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
512 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
513 fn new(iter: I) -> Self {
514 SummaryLine { inner: iter, started: false, depth: 0 }
518 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
525 | Tag::BlockQuote => true,
530 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
531 type Item = Event<'a>;
533 fn next(&mut self) -> Option<Self::Item> {
534 if self.started && self.depth == 0 {
540 if let Some(event) = self.inner.next() {
541 let mut is_start = true;
542 let is_allowed_tag = match event {
543 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
546 Event::Start(ref c) => {
548 check_if_allowed_tag(c)
550 Event::End(ref c) => {
553 check_if_allowed_tag(c)
557 return if !is_allowed_tag {
559 Some(Event::Start(Tag::Paragraph))
561 Some(Event::End(Tag::Paragraph))
571 /// Moves all footnote definitions to the end and add back links to the
573 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
575 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
578 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
579 fn new(iter: I) -> Self {
580 Footnotes { inner: iter, footnotes: FxHashMap::default() }
582 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
583 let new_id = self.footnotes.keys().count() + 1;
584 let key = key.to_owned();
585 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
589 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
590 type Item = Event<'a>;
592 fn next(&mut self) -> Option<Self::Item> {
594 match self.inner.next() {
595 Some(Event::FootnoteReference(ref reference)) => {
596 let entry = self.get_entry(&reference);
597 let reference = format!(
598 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
601 return Some(Event::Html(reference.into()));
603 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
604 let mut content = Vec::new();
605 for event in &mut self.inner {
606 if let Event::End(Tag::FootnoteDefinition(..)) = event {
611 let entry = self.get_entry(&def);
612 (*entry).0 = content;
614 Some(e) => return Some(e),
616 if !self.footnotes.is_empty() {
617 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
618 v.sort_by(|a, b| a.1.cmp(&b.1));
619 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
620 for (mut content, id) in v {
621 write!(ret, "<li id=\"fn{}\">", id).unwrap();
622 let mut is_paragraph = false;
623 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
627 html::push_html(&mut ret, content.into_iter());
628 write!(ret, " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
631 ret.push_str("</p>");
633 ret.push_str("</li>");
635 ret.push_str("</ol></div>");
636 return Some(Event::Html(ret.into()));
646 pub fn find_testable_code<T: doctest::Tester>(
649 error_codes: ErrorCodes,
650 enable_per_target_ignores: bool,
651 extra_info: Option<&ExtraInfo<'_, '_>>,
653 let mut parser = Parser::new(doc).into_offset_iter();
654 let mut prev_offset = 0;
655 let mut nb_lines = 0;
656 let mut register_header = None;
657 while let Some((event, offset)) = parser.next() {
659 Event::Start(Tag::CodeBlock(kind)) => {
660 let block_info = match kind {
661 CodeBlockKind::Fenced(ref lang) => {
663 LangString::all_false()
668 enable_per_target_ignores,
673 CodeBlockKind::Indented => LangString::all_false(),
675 if !block_info.rust {
679 let mut test_s = String::new();
681 while let Some((Event::Text(s), _)) = parser.next() {
686 .map(|l| map_line(l).for_code())
687 .collect::<Vec<Cow<'_, str>>>()
690 nb_lines += doc[prev_offset..offset.start].lines().count();
691 let line = tests.get_line() + nb_lines + 1;
692 tests.add_test(text, block_info, line);
693 prev_offset = offset.start;
695 Event::Start(Tag::Heading(level)) => {
696 register_header = Some(level as u32);
698 Event::Text(ref s) if register_header.is_some() => {
699 let level = register_header.unwrap();
701 tests.register_header("", level);
703 tests.register_header(s, level);
705 register_header = None;
712 pub struct ExtraInfo<'a, 'b> {
713 hir_id: Option<HirId>,
714 item_did: Option<DefId>,
719 impl<'a, 'b> ExtraInfo<'a, 'b> {
720 pub fn new(tcx: &'a TyCtxt<'b>, hir_id: HirId, sp: Span) -> ExtraInfo<'a, 'b> {
721 ExtraInfo { hir_id: Some(hir_id), item_did: None, sp, tcx }
724 pub fn new_did(tcx: &'a TyCtxt<'b>, did: DefId, sp: Span) -> ExtraInfo<'a, 'b> {
725 ExtraInfo { hir_id: None, item_did: Some(did), sp, tcx }
728 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
729 let hir_id = match (self.hir_id, self.item_did) {
731 (None, Some(item_did)) => {
732 match item_did.as_local() {
733 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
735 // If non-local, no need to check anything.
740 (None, None) => return,
742 self.tcx.struct_span_lint_hir(
743 lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES,
747 let mut diag = lint.build(msg);
755 #[derive(Eq, PartialEq, Clone, Debug)]
756 pub struct LangString {
758 pub should_panic: bool,
762 pub test_harness: bool,
763 pub compile_fail: bool,
764 pub error_codes: Vec<String>,
765 pub allow_fail: bool,
766 pub edition: Option<Edition>,
769 #[derive(Eq, PartialEq, Clone, Debug)]
777 fn all_false() -> LangString {
779 original: String::new(),
782 ignore: Ignore::None,
783 rust: true, // NB This used to be `notrust = false`
786 error_codes: Vec::new(),
792 fn parse_without_check(
794 allow_error_code_check: ErrorCodes,
795 enable_per_target_ignores: bool,
797 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
802 allow_error_code_check: ErrorCodes,
803 enable_per_target_ignores: bool,
804 extra: Option<&ExtraInfo<'_, '_>>,
806 let allow_error_code_check = allow_error_code_check.as_bool();
807 let mut seen_rust_tags = false;
808 let mut seen_other_tags = false;
809 let mut data = LangString::all_false();
810 let mut ignores = vec![];
812 data.original = string.to_owned();
813 let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
815 for token in tokens {
819 data.should_panic = true;
820 seen_rust_tags = !seen_other_tags;
824 seen_rust_tags = !seen_other_tags;
827 data.ignore = Ignore::All;
828 seen_rust_tags = !seen_other_tags;
830 x if x.starts_with("ignore-") => {
831 if enable_per_target_ignores {
832 ignores.push(x.trim_start_matches("ignore-").to_owned());
833 seen_rust_tags = !seen_other_tags;
837 data.allow_fail = true;
838 seen_rust_tags = !seen_other_tags;
842 seen_rust_tags = true;
845 data.test_harness = true;
846 seen_rust_tags = !seen_other_tags || seen_rust_tags;
849 data.compile_fail = true;
850 seen_rust_tags = !seen_other_tags || seen_rust_tags;
853 x if x.starts_with("edition") => {
854 data.edition = x[7..].parse::<Edition>().ok();
856 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
857 if x[1..].parse::<u32>().is_ok() {
858 data.error_codes.push(x.to_owned());
859 seen_rust_tags = !seen_other_tags || seen_rust_tags;
861 seen_other_tags = true;
864 x if extra.is_some() => {
865 let s = x.to_lowercase();
866 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
869 "the code block will either not be tested if not marked as a rust one \
870 or won't fail if it compiles successfully",
872 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
875 "the code block will either not be tested if not marked as a rust one \
876 or won't fail if it doesn't panic when running",
878 } else if s == "no-run" || s == "no_run" || s == "norun" {
881 "the code block will either not be tested if not marked as a rust one \
882 or will be run (which you might not want)",
884 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
887 "the code block will either not be tested if not marked as a rust one \
888 or will be run (which you might not want)",
890 } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
893 "the code block will either not be tested if not marked as a rust one \
894 or the code will be wrapped inside a main function",
899 Some((flag, help)) => {
900 if let Some(ref extra) = extra {
901 extra.error_invalid_codeblock_attr(
902 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
909 seen_other_tags = true;
911 _ => seen_other_tags = true,
914 // ignore-foo overrides ignore
915 if !ignores.is_empty() {
916 data.ignore = Ignore::Some(ignores);
919 data.rust &= !seen_other_tags || seen_rust_tags;
926 pub fn into_string(self) -> String {
927 let Markdown(md, links, mut ids, codes, edition, playground) = self;
929 // This is actually common enough to special-case
931 return String::new();
933 let mut replacer = |broken_link: BrokenLink<'_>| {
935 links.iter().find(|link| &*link.original_text == broken_link.reference)
937 Some((link.href.as_str().into(), link.new_text.as_str().into()))
943 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
945 let mut s = String::with_capacity(md.len() * 3 / 2);
947 let p = HeadingLinks::new(p, None, &mut ids);
948 let p = LinkReplacer::new(p, links);
949 let p = CodeBlocks::new(p, codes, edition, playground);
950 let p = Footnotes::new(p);
951 html::push_html(&mut s, p);
957 impl MarkdownWithToc<'_> {
958 pub fn into_string(self) -> String {
959 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
961 let p = Parser::new_ext(md, opts());
963 let mut s = String::with_capacity(md.len() * 3 / 2);
965 let mut toc = TocBuilder::new();
968 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
969 let p = CodeBlocks::new(p, codes, edition, playground);
970 let p = Footnotes::new(p);
971 html::push_html(&mut s, p);
974 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
978 impl MarkdownHtml<'_> {
979 pub fn into_string(self) -> String {
980 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
982 // This is actually common enough to special-case
984 return String::new();
986 let p = Parser::new_ext(md, opts());
988 // Treat inline HTML as plain text.
989 let p = p.map(|event| match event {
990 Event::Html(text) => Event::Text(text),
994 let mut s = String::with_capacity(md.len() * 3 / 2);
996 let p = HeadingLinks::new(p, None, &mut ids);
997 let p = CodeBlocks::new(p, codes, edition, playground);
998 let p = Footnotes::new(p);
999 html::push_html(&mut s, p);
1005 impl MarkdownSummaryLine<'_> {
1006 pub fn into_string(self) -> String {
1007 let MarkdownSummaryLine(md, links) = self;
1008 // This is actually common enough to special-case
1010 return String::new();
1013 let mut replacer = |broken_link: BrokenLink<'_>| {
1015 links.iter().find(|link| &*link.original_text == broken_link.reference)
1017 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1023 let p = Parser::new_with_broken_link_callback(
1025 Options::ENABLE_STRIKETHROUGH,
1026 Some(&mut replacer),
1029 let mut s = String::new();
1031 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1037 /// Renders the first paragraph of the provided markdown as plain text.
1039 /// - Headings, links, and formatting are stripped.
1040 /// - Inline code is rendered as-is, surrounded by backticks.
1041 /// - HTML and code blocks are ignored.
1042 pub fn plain_text_summary(md: &str) -> String {
1044 return String::new();
1047 let mut s = String::with_capacity(md.len() * 3 / 2);
1049 for event in Parser::new_ext(md, Options::ENABLE_STRIKETHROUGH) {
1051 Event::Text(text) => s.push_str(text),
1052 Event::Code(code) => {
1057 Event::HardBreak | Event::SoftBreak => s.push(' '),
1058 Event::Start(Tag::CodeBlock(..)) => break,
1059 Event::End(Tag::Paragraph) => break,
1067 pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
1072 let mut links = vec![];
1073 let mut shortcut_links = vec![];
1076 let locate = |s: &str| unsafe {
1077 let s_start = s.as_ptr();
1078 let s_end = s_start.add(s.len());
1079 let md_start = md.as_ptr();
1080 let md_end = md_start.add(md.len());
1081 if md_start <= s_start && s_end <= md_end {
1082 let start = s_start.offset_from(md_start) as usize;
1083 let end = s_end.offset_from(md_start) as usize;
1090 let mut push = |link: BrokenLink<'_>| {
1091 // FIXME: use `link.span` instead of `locate`
1092 // (doing it now includes the `[]` as well as the text)
1093 shortcut_links.push((link.reference.to_owned(), locate(link.reference)));
1096 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut push));
1098 // There's no need to thread an IdMap through to here because
1099 // the IDs generated aren't going to be emitted anywhere.
1100 let mut ids = IdMap::new();
1101 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1104 if let Event::Start(Tag::Link(_, dest, _)) = ev {
1105 debug!("found link: {}", dest);
1106 links.push(match dest {
1107 CowStr::Borrowed(s) => (s.to_owned(), locate(s)),
1108 s @ (CowStr::Boxed(..) | CowStr::Inlined(..)) => (s.into_string(), None),
1114 links.append(&mut shortcut_links);
1120 crate struct RustCodeBlock {
1121 /// The range in the markdown that the code block occupies. Note that this includes the fences
1122 /// for fenced code blocks.
1123 pub range: Range<usize>,
1124 /// The range in the markdown that the code within the code block occupies.
1125 pub code: Range<usize>,
1126 pub is_fenced: bool,
1127 pub syntax: Option<String>,
1130 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1131 /// untagged (and assumed to be rust).
1132 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustCodeBlock> {
1133 let mut code_blocks = vec![];
1139 let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1141 while let Some((event, offset)) = p.next() {
1142 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1143 let (syntax, code_start, code_end, range, is_fenced) = match syntax {
1144 CodeBlockKind::Fenced(syntax) => {
1145 let syntax = syntax.as_ref();
1146 let lang_string = if syntax.is_empty() {
1147 LangString::all_false()
1149 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1151 if !lang_string.rust {
1154 let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1155 let (code_start, mut code_end) = match p.next() {
1156 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1157 Some((_, sub_offset)) => {
1158 let code = Range { start: sub_offset.start, end: sub_offset.start };
1159 code_blocks.push(RustCodeBlock {
1168 let code = Range { start: offset.end, end: offset.end };
1169 code_blocks.push(RustCodeBlock {
1178 while let Some((Event::Text(_), offset)) = p.next() {
1179 code_end = offset.end;
1181 (syntax, code_start, code_end, offset, true)
1183 CodeBlockKind::Indented => {
1184 // The ending of the offset goes too far sometime so we reduce it by one in
1186 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1191 Range { start: offset.start, end: offset.end - 1 },
1195 (None, offset.start, offset.end, offset, false)
1200 code_blocks.push(RustCodeBlock {
1203 code: Range { start: code_start, end: code_end },
1212 #[derive(Clone, Default, Debug)]
1214 map: FxHashMap<String, usize>,
1217 fn init_id_map() -> FxHashMap<String, usize> {
1218 let mut map = FxHashMap::default();
1219 // This is the list of IDs used by rustdoc templates.
1220 map.insert("mainThemeStyle".to_owned(), 1);
1221 map.insert("themeStyle".to_owned(), 1);
1222 map.insert("theme-picker".to_owned(), 1);
1223 map.insert("theme-choices".to_owned(), 1);
1224 map.insert("settings-menu".to_owned(), 1);
1225 map.insert("main".to_owned(), 1);
1226 map.insert("search".to_owned(), 1);
1227 map.insert("crate-search".to_owned(), 1);
1228 map.insert("render-detail".to_owned(), 1);
1229 map.insert("toggle-all-docs".to_owned(), 1);
1230 map.insert("all-types".to_owned(), 1);
1231 // This is the list of IDs used by rustdoc sections.
1232 map.insert("fields".to_owned(), 1);
1233 map.insert("variants".to_owned(), 1);
1234 map.insert("implementors-list".to_owned(), 1);
1235 map.insert("synthetic-implementors-list".to_owned(), 1);
1236 map.insert("implementations".to_owned(), 1);
1237 map.insert("trait-implementations".to_owned(), 1);
1238 map.insert("synthetic-implementations".to_owned(), 1);
1239 map.insert("blanket-implementations".to_owned(), 1);
1240 map.insert("deref-methods".to_owned(), 1);
1245 pub fn new() -> Self {
1246 IdMap { map: init_id_map() }
1249 pub fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1251 let _ = self.derive(id);
1255 pub fn reset(&mut self) {
1256 self.map = init_id_map();
1259 pub fn derive(&mut self, candidate: String) -> String {
1260 let id = match self.map.get_mut(&candidate) {
1263 let id = format!("{}-{}", candidate, *a);
1269 self.map.insert(id.clone(), 1);