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 use rustc_data_structures::fx::FxHashMap;
21 use rustc_hir::def_id::DefId;
23 use rustc_middle::ty::TyCtxt;
24 use rustc_session::lint;
25 use rustc_span::edition::Edition;
28 use std::collections::VecDeque;
29 use std::default::Default;
34 use crate::clean::RenderedLink;
36 use crate::html::highlight;
37 use crate::html::toc::TocBuilder;
39 use pulldown_cmark::{html, BrokenLink, CodeBlockKind, CowStr, Event, Options, Parser, Tag};
44 /// Options for rendering Markdown in the main body of documentation.
45 pub(crate) fn opts() -> Options {
46 Options::ENABLE_TABLES | Options::ENABLE_FOOTNOTES | Options::ENABLE_STRIKETHROUGH
49 /// A subset of [`opts()`] used for rendering summaries.
50 pub(crate) fn summary_opts() -> Options {
51 Options::ENABLE_STRIKETHROUGH
54 /// When `to_string` is called, this struct will emit the HTML corresponding to
55 /// the rendered version of the contained markdown string.
56 pub struct Markdown<'a>(
58 /// A list of link replacements.
59 pub &'a [RenderedLink],
60 /// The current list of used header IDs.
62 /// Whether to allow the use of explicit error codes in doctest lang strings.
64 /// Default edition to use when parsing doctests (to add a `fn main`).
66 pub &'a Option<Playground>,
68 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
69 crate struct MarkdownWithToc<'a>(
74 crate &'a Option<Playground>,
76 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
77 crate struct MarkdownHtml<'a>(
82 crate &'a Option<Playground>,
84 /// A tuple struct like `Markdown` that renders only the first paragraph.
85 crate struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
87 #[derive(Copy, Clone, PartialEq, Debug)]
94 crate fn from(b: bool) -> Self {
96 true => ErrorCodes::Yes,
97 false => ErrorCodes::No,
101 crate fn as_bool(self) -> bool {
103 ErrorCodes::Yes => true,
104 ErrorCodes::No => false,
109 /// Controls whether a line will be hidden or shown in HTML output.
111 /// All lines are used in documentation tests.
118 fn for_html(self) -> Option<Cow<'a, str>> {
120 Line::Shown(l) => Some(l),
121 Line::Hidden(_) => None,
125 fn for_code(self) -> Cow<'a, str> {
128 Line::Hidden(l) => Cow::Borrowed(l),
133 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
134 // have no easy way of removing a potential single space after the hashes, which
135 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
136 // order to fix it we'd have to iterate to find the first non-# character, and
137 // then reallocate to remove it; which would make us return a String.
138 fn map_line(s: &str) -> Line<'_> {
139 let trimmed = s.trim();
140 if trimmed.starts_with("##") {
141 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
142 } else if let Some(stripped) = trimmed.strip_prefix("# ") {
144 Line::Hidden(&stripped)
145 } else if trimmed == "#" {
146 // We cannot handle '#text' because it could be #[attr].
149 Line::Shown(Cow::Borrowed(s))
153 /// Convert chars from a title for an id.
155 /// "Hello, world!" -> "hello-world"
156 fn slugify(c: char) -> Option<char> {
157 if c.is_alphanumeric() || c == '-' || c == '_' {
158 if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
159 } else if c.is_whitespace() && c.is_ascii() {
166 #[derive(Clone, Debug)]
167 pub struct Playground {
168 pub crate_name: Option<String>,
172 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
173 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
175 check_error_codes: ErrorCodes,
177 // Information about the playground if a URL has been specified, containing an
178 // optional crate name and the URL.
179 playground: &'p Option<Playground>,
182 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
185 error_codes: ErrorCodes,
187 playground: &'p Option<Playground>,
189 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
193 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
194 type Item = Event<'a>;
196 fn next(&mut self) -> Option<Self::Item> {
197 let event = self.inner.next();
202 if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
203 let parse_result = match kind {
204 CodeBlockKind::Fenced(ref lang) => {
205 LangString::parse_without_check(&lang, self.check_error_codes, false)
207 CodeBlockKind::Indented => Default::default(),
209 if !parse_result.rust {
210 return Some(Event::Start(Tag::CodeBlock(kind)));
212 compile_fail = parse_result.compile_fail;
213 should_panic = parse_result.should_panic;
214 ignore = parse_result.ignore;
215 edition = parse_result.edition;
220 let explicit_edition = edition.is_some();
221 let edition = edition.unwrap_or(self.edition);
223 let mut origtext = String::new();
224 for event in &mut self.inner {
226 Event::End(Tag::CodeBlock(..)) => break,
227 Event::Text(ref s) => {
228 origtext.push_str(s);
233 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
234 let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
235 // insert newline to clearly separate it from the
236 // previous block so we can shorten the html output
237 let mut s = String::from("\n");
238 let playground_button = self.playground.as_ref().and_then(|playground| {
239 let krate = &playground.crate_name;
240 let url = &playground.url;
246 .map(|l| map_line(l).for_code())
247 .collect::<Vec<Cow<'_, str>>>()
249 let krate = krate.as_ref().map(|s| &**s);
251 doctest::make_test(&test, krate, false, &Default::default(), edition);
252 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
254 let edition_string = format!("&edition={}", edition);
256 // These characters don't need to be escaped in a URI.
257 // FIXME: use a library function for percent encoding.
258 fn dont_escape(c: u8) -> bool {
259 (b'a' <= c && c <= b'z')
260 || (b'A' <= c && c <= b'Z')
261 || (b'0' <= c && c <= b'9')
272 let mut test_escaped = String::new();
273 for b in test.bytes() {
275 test_escaped.push(char::from(b));
277 write!(test_escaped, "%{:02X}", b).unwrap();
281 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
282 url, test_escaped, channel, edition_string
286 let tooltip = if ignore != Ignore::None {
287 Some(("This example is not tested".to_owned(), "ignore"))
288 } else if compile_fail {
289 Some(("This example deliberately fails to compile".to_owned(), "compile_fail"))
290 } else if should_panic {
291 Some(("This example panics".to_owned(), "should_panic"))
292 } else if explicit_edition {
293 Some((format!("This code runs with edition {}", edition), "edition"))
298 if let Some((s1, s2)) = tooltip {
299 s.push_str(&highlight::render_with_highlighting(
302 "rust-example-rendered{}",
303 if ignore != Ignore::None {
305 } else if compile_fail {
307 } else if should_panic {
309 } else if explicit_edition {
315 playground_button.as_deref(),
316 Some((s1.as_str(), s2)),
318 Some(Event::Html(s.into()))
320 s.push_str(&highlight::render_with_highlighting(
323 "rust-example-rendered{}",
324 if ignore != Ignore::None {
326 } else if compile_fail {
328 } else if should_panic {
330 } else if explicit_edition {
336 playground_button.as_deref(),
339 Some(Event::Html(s.into()))
344 /// Make headings links with anchor IDs and build up TOC.
345 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
347 links: &'a [RenderedLink],
348 shortcut_link: Option<&'a RenderedLink>,
351 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
352 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
353 LinkReplacer { inner: iter, links, shortcut_link: None }
357 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
358 type Item = Event<'a>;
360 fn next(&mut self) -> Option<Self::Item> {
361 use pulldown_cmark::LinkType;
363 let mut event = self.inner.next();
365 // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
367 // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
368 // Remove any disambiguator.
369 Some(Event::Start(Tag::Link(
370 // [fn@f] or [fn@f][]
371 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
375 debug!("saw start of shortcut link to {} with title {}", dest, title);
376 // If this is a shortcut link, it was resolved by the broken_link_callback.
377 // So the URL will already be updated properly.
378 let link = self.links.iter().find(|&link| *link.href == **dest);
379 // Since this is an external iterator, we can't replace the inner text just yet.
380 // Store that we saw a link so we know to replace it later.
381 if let Some(link) = link {
382 trace!("it matched");
383 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
384 self.shortcut_link = Some(link);
387 // Now that we're done with the shortcut link, don't replace any more text.
388 Some(Event::End(Tag::Link(
389 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
393 debug!("saw end of shortcut link to {}", dest);
394 if self.links.iter().any(|link| *link.href == **dest) {
395 assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
396 self.shortcut_link = None;
399 // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
401 Some(Event::Code(text)) => {
402 trace!("saw code {}", text);
403 if let Some(link) = self.shortcut_link {
404 trace!("original text was {}", link.original_text);
405 // NOTE: this only replaces if the code block is the *entire* text.
406 // If only part of the link has code highlighting, the disambiguator will not be removed.
408 // This is a limitation from `collect_intra_doc_links`: it passes a full link,
409 // and does not distinguish at all between code blocks.
410 // So we could never be sure we weren't replacing too much:
411 // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
413 // NOTE: &[1..len() - 1] is to strip the backticks
414 if **text == link.original_text[1..link.original_text.len() - 1] {
415 debug!("replacing {} with {}", text, link.new_text);
416 *text = CowStr::Borrowed(&link.new_text);
420 // Replace plain text in links, but only in the middle of a shortcut link.
422 Some(Event::Text(text)) => {
423 trace!("saw text {}", text);
424 if let Some(link) = self.shortcut_link {
425 trace!("original text was {}", link.original_text);
426 // NOTE: same limitations as `Event::Code`
427 if **text == *link.original_text {
428 debug!("replacing {} with {}", text, link.new_text);
429 *text = CowStr::Borrowed(&link.new_text);
433 // If this is a link, but not a shortcut link,
434 // replace the URL, since the broken_link_callback was not called.
435 Some(Event::Start(Tag::Link(_, dest, _))) => {
436 if let Some(link) = self.links.iter().find(|&link| *link.original_text == **dest) {
437 *dest = CowStr::Borrowed(link.href.as_ref());
440 // Anything else couldn't have been a valid Rust path, so no need to replace the text.
444 // Yield the modified event
449 /// Make headings links with anchor IDs and build up TOC.
450 struct HeadingLinks<'a, 'b, 'ids, I> {
452 toc: Option<&'b mut TocBuilder>,
453 buf: VecDeque<(Event<'a>, Range<usize>)>,
454 id_map: &'ids mut IdMap,
457 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
458 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
459 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
463 impl<'a, 'b, 'ids, I: Iterator<Item = (Event<'a>, Range<usize>)>> Iterator
464 for HeadingLinks<'a, 'b, 'ids, I>
466 type Item = (Event<'a>, Range<usize>);
468 fn next(&mut self) -> Option<Self::Item> {
469 if let Some(e) = self.buf.pop_front() {
473 let event = self.inner.next();
474 if let Some((Event::Start(Tag::Heading(level)), _)) = event {
475 let mut id = String::new();
476 for event in &mut self.inner {
478 Event::End(Tag::Heading(..)) => break,
479 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
480 Event::Text(text) | Event::Code(text) => {
481 id.extend(text.chars().filter_map(slugify));
482 self.buf.push_back(event);
484 _ => self.buf.push_back(event),
487 let id = self.id_map.derive(id);
489 if let Some(ref mut builder) = self.toc {
490 let mut html_header = String::new();
491 html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
492 let sec = builder.push(level as u32, html_header, id.clone());
493 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
496 self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
498 let start_tags = format!(
499 "<h{level} id=\"{id}\" class=\"section-header\">\
504 return Some((Event::Html(start_tags.into()), 0..0));
510 /// Extracts just the first paragraph.
511 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
517 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
518 fn new(iter: I) -> Self {
519 SummaryLine { inner: iter, started: false, depth: 0 }
523 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
530 | Tag::BlockQuote => true,
535 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
536 type Item = Event<'a>;
538 fn next(&mut self) -> Option<Self::Item> {
539 if self.started && self.depth == 0 {
545 if let Some(event) = self.inner.next() {
546 let mut is_start = true;
547 let is_allowed_tag = match event {
548 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
551 Event::Start(ref c) => {
553 check_if_allowed_tag(c)
555 Event::End(ref c) => {
558 check_if_allowed_tag(c)
562 return if !is_allowed_tag {
564 Some(Event::Start(Tag::Paragraph))
566 Some(Event::End(Tag::Paragraph))
576 /// Moves all footnote definitions to the end and add back links to the
578 struct Footnotes<'a, I> {
580 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
583 impl<'a, I> Footnotes<'a, I> {
584 fn new(iter: I) -> Self {
585 Footnotes { inner: iter, footnotes: FxHashMap::default() }
588 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
589 let new_id = self.footnotes.keys().count() + 1;
590 let key = key.to_owned();
591 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
595 impl<'a, I: Iterator<Item = (Event<'a>, Range<usize>)>> Iterator for Footnotes<'a, I> {
596 type Item = (Event<'a>, Range<usize>);
598 fn next(&mut self) -> Option<Self::Item> {
600 match self.inner.next() {
601 Some((Event::FootnoteReference(ref reference), range)) => {
602 let entry = self.get_entry(&reference);
603 let reference = format!(
604 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
607 return Some((Event::Html(reference.into()), range));
609 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
610 let mut content = Vec::new();
611 for (event, _) in &mut self.inner {
612 if let Event::End(Tag::FootnoteDefinition(..)) = event {
617 let entry = self.get_entry(&def);
618 (*entry).0 = content;
620 Some(e) => return Some(e),
622 if !self.footnotes.is_empty() {
623 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
624 v.sort_by(|a, b| a.1.cmp(&b.1));
625 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
626 for (mut content, id) in v {
627 write!(ret, "<li id=\"fn{}\">", id).unwrap();
628 let mut is_paragraph = false;
629 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
633 html::push_html(&mut ret, content.into_iter());
634 write!(ret, " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
637 ret.push_str("</p>");
639 ret.push_str("</li>");
641 ret.push_str("</ol></div>");
642 return Some((Event::Html(ret.into()), 0..0));
652 crate fn find_testable_code<T: doctest::Tester>(
655 error_codes: ErrorCodes,
656 enable_per_target_ignores: bool,
657 extra_info: Option<&ExtraInfo<'_, '_>>,
659 let mut parser = Parser::new(doc).into_offset_iter();
660 let mut prev_offset = 0;
661 let mut nb_lines = 0;
662 let mut register_header = None;
663 while let Some((event, offset)) = parser.next() {
665 Event::Start(Tag::CodeBlock(kind)) => {
666 let block_info = match kind {
667 CodeBlockKind::Fenced(ref lang) => {
674 enable_per_target_ignores,
679 CodeBlockKind::Indented => Default::default(),
681 if !block_info.rust {
685 let mut test_s = String::new();
687 while let Some((Event::Text(s), _)) = parser.next() {
692 .map(|l| map_line(l).for_code())
693 .collect::<Vec<Cow<'_, str>>>()
696 nb_lines += doc[prev_offset..offset.start].lines().count();
697 let line = tests.get_line() + nb_lines + 1;
698 tests.add_test(text, block_info, line);
699 prev_offset = offset.start;
701 Event::Start(Tag::Heading(level)) => {
702 register_header = Some(level as u32);
704 Event::Text(ref s) if register_header.is_some() => {
705 let level = register_header.unwrap();
707 tests.register_header("", level);
709 tests.register_header(s, level);
711 register_header = None;
718 crate struct ExtraInfo<'a, 'b> {
719 hir_id: Option<HirId>,
720 item_did: Option<DefId>,
725 impl<'a, 'b> ExtraInfo<'a, 'b> {
726 crate fn new(tcx: &'a TyCtxt<'b>, hir_id: HirId, sp: Span) -> ExtraInfo<'a, 'b> {
727 ExtraInfo { hir_id: Some(hir_id), item_did: None, sp, tcx }
730 crate fn new_did(tcx: &'a TyCtxt<'b>, did: DefId, sp: Span) -> ExtraInfo<'a, 'b> {
731 ExtraInfo { hir_id: None, item_did: Some(did), sp, tcx }
734 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
735 let hir_id = match (self.hir_id, self.item_did) {
737 (None, Some(item_did)) => {
738 match item_did.as_local() {
739 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
741 // If non-local, no need to check anything.
746 (None, None) => return,
748 self.tcx.struct_span_lint_hir(
749 lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES,
753 let mut diag = lint.build(msg);
761 #[derive(Eq, PartialEq, Clone, Debug)]
762 crate struct LangString {
764 crate should_panic: bool,
766 crate ignore: Ignore,
768 crate test_harness: bool,
769 crate compile_fail: bool,
770 crate error_codes: Vec<String>,
771 crate allow_fail: bool,
772 crate edition: Option<Edition>,
775 #[derive(Eq, PartialEq, Clone, Debug)]
782 impl Default for LangString {
783 fn default() -> Self {
785 original: String::new(),
788 ignore: Ignore::None,
792 error_codes: Vec::new(),
800 fn parse_without_check(
802 allow_error_code_check: ErrorCodes,
803 enable_per_target_ignores: bool,
805 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
810 allow_error_code_check: ErrorCodes,
811 enable_per_target_ignores: bool,
812 extra: Option<&ExtraInfo<'_, '_>>,
814 let allow_error_code_check = allow_error_code_check.as_bool();
815 let mut seen_rust_tags = false;
816 let mut seen_other_tags = false;
817 let mut data = LangString::default();
818 let mut ignores = vec![];
820 data.original = string.to_owned();
821 let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
823 for token in tokens {
827 data.should_panic = true;
828 seen_rust_tags = !seen_other_tags;
832 seen_rust_tags = !seen_other_tags;
835 data.ignore = Ignore::All;
836 seen_rust_tags = !seen_other_tags;
838 x if x.starts_with("ignore-") => {
839 if enable_per_target_ignores {
840 ignores.push(x.trim_start_matches("ignore-").to_owned());
841 seen_rust_tags = !seen_other_tags;
845 data.allow_fail = true;
846 seen_rust_tags = !seen_other_tags;
850 seen_rust_tags = true;
853 data.test_harness = true;
854 seen_rust_tags = !seen_other_tags || seen_rust_tags;
857 data.compile_fail = true;
858 seen_rust_tags = !seen_other_tags || seen_rust_tags;
861 x if x.starts_with("edition") => {
862 data.edition = x[7..].parse::<Edition>().ok();
864 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
865 if x[1..].parse::<u32>().is_ok() {
866 data.error_codes.push(x.to_owned());
867 seen_rust_tags = !seen_other_tags || seen_rust_tags;
869 seen_other_tags = true;
872 x if extra.is_some() => {
873 let s = x.to_lowercase();
874 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
877 "the code block will either not be tested if not marked as a rust one \
878 or won't fail if it compiles successfully",
880 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
883 "the code block will either not be tested if not marked as a rust one \
884 or won't fail if it doesn't panic when running",
886 } else if s == "no-run" || s == "no_run" || s == "norun" {
889 "the code block will either not be tested if not marked as a rust one \
890 or will be run (which you might not want)",
892 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
895 "the code block will either not be tested if not marked as a rust one \
896 or will be run (which you might not want)",
898 } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
901 "the code block will either not be tested if not marked as a rust one \
902 or the code will be wrapped inside a main function",
907 Some((flag, help)) => {
908 if let Some(ref extra) = extra {
909 extra.error_invalid_codeblock_attr(
910 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
917 seen_other_tags = true;
919 _ => seen_other_tags = true,
922 // ignore-foo overrides ignore
923 if !ignores.is_empty() {
924 data.ignore = Ignore::Some(ignores);
927 data.rust &= !seen_other_tags || seen_rust_tags;
934 pub fn into_string(self) -> String {
935 let Markdown(md, links, mut ids, codes, edition, playground) = self;
937 // This is actually common enough to special-case
939 return String::new();
941 let mut replacer = |broken_link: BrokenLink<'_>| {
943 links.iter().find(|link| &*link.original_text == broken_link.reference)
945 Some((link.href.as_str().into(), link.new_text.as_str().into()))
951 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
952 let p = p.into_offset_iter();
954 let mut s = String::with_capacity(md.len() * 3 / 2);
956 let p = HeadingLinks::new(p, None, &mut ids);
957 let p = Footnotes::new(p);
958 let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
959 let p = CodeBlocks::new(p, codes, edition, playground);
960 html::push_html(&mut s, p);
966 impl MarkdownWithToc<'_> {
967 crate fn into_string(self) -> String {
968 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
970 let p = Parser::new_ext(md, opts()).into_offset_iter();
972 let mut s = String::with_capacity(md.len() * 3 / 2);
974 let mut toc = TocBuilder::new();
977 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
978 let p = Footnotes::new(p);
979 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
980 html::push_html(&mut s, p);
983 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
987 impl MarkdownHtml<'_> {
988 crate fn into_string(self) -> String {
989 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
991 // This is actually common enough to special-case
993 return String::new();
995 let p = Parser::new_ext(md, opts()).into_offset_iter();
997 // Treat inline HTML as plain text.
998 let p = p.map(|event| match event.0 {
999 Event::Html(text) => (Event::Text(text), event.1),
1003 let mut s = String::with_capacity(md.len() * 3 / 2);
1005 let p = HeadingLinks::new(p, None, &mut ids);
1006 let p = Footnotes::new(p);
1007 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
1008 html::push_html(&mut s, p);
1014 impl MarkdownSummaryLine<'_> {
1015 crate fn into_string(self) -> String {
1016 let MarkdownSummaryLine(md, links) = self;
1017 // This is actually common enough to special-case
1019 return String::new();
1022 let mut replacer = |broken_link: BrokenLink<'_>| {
1024 links.iter().find(|link| &*link.original_text == broken_link.reference)
1026 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1032 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1034 let mut s = String::new();
1036 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1042 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1044 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1045 /// - Headings and links are stripped (though the text *is* rendered).
1046 /// - HTML, code blocks, and everything else are ignored.
1048 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1049 /// due to the provided `length_limit`.
1050 fn markdown_summary_with_limit(md: &str, length_limit: usize) -> (String, bool) {
1052 return (String::new(), false);
1055 let mut s = String::with_capacity(md.len() * 3 / 2);
1056 let mut text_length = 0;
1057 let mut stopped_early = false;
1059 fn push(s: &mut String, text_length: &mut usize, text: &str) {
1061 *text_length += text.len();
1064 'outer: for event in Parser::new_ext(md, summary_opts()) {
1066 Event::Text(text) => {
1067 for word in text.split_inclusive(char::is_whitespace) {
1068 if text_length + word.len() >= length_limit {
1069 stopped_early = true;
1073 push(&mut s, &mut text_length, word);
1076 Event::Code(code) => {
1077 if text_length + code.len() >= length_limit {
1078 stopped_early = true;
1082 s.push_str("<code>");
1083 push(&mut s, &mut text_length, code);
1084 s.push_str("</code>");
1086 Event::Start(tag) => match tag {
1087 Tag::Emphasis => s.push_str("<em>"),
1088 Tag::Strong => s.push_str("<strong>"),
1089 Tag::CodeBlock(..) => break,
1092 Event::End(tag) => match tag {
1093 Tag::Emphasis => s.push_str("</em>"),
1094 Tag::Strong => s.push_str("</strong>"),
1095 Tag::Paragraph => break,
1098 Event::HardBreak | Event::SoftBreak => {
1099 if text_length + 1 >= length_limit {
1100 stopped_early = true;
1104 push(&mut s, &mut text_length, " ");
1113 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1114 /// making it suitable for contexts like the search index.
1116 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1118 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1119 crate fn short_markdown_summary(markdown: &str) -> String {
1120 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, 59);
1129 /// Renders the first paragraph of the provided markdown as plain text.
1130 /// Useful for alt-text.
1132 /// - Headings, links, and formatting are stripped.
1133 /// - Inline code is rendered as-is, surrounded by backticks.
1134 /// - HTML and code blocks are ignored.
1135 crate fn plain_text_summary(md: &str) -> String {
1137 return String::new();
1140 let mut s = String::with_capacity(md.len() * 3 / 2);
1142 for event in Parser::new_ext(md, summary_opts()) {
1144 Event::Text(text) => s.push_str(text),
1145 Event::Code(code) => {
1150 Event::HardBreak | Event::SoftBreak => s.push(' '),
1151 Event::Start(Tag::CodeBlock(..)) => break,
1152 Event::End(Tag::Paragraph) => break,
1160 crate fn markdown_links(md: &str) -> Vec<(String, Range<usize>)> {
1165 let mut links = vec![];
1166 // Used to avoid mutable borrow issues in the `push` closure
1167 // Probably it would be more efficient to use a `RefCell` but it doesn't seem worth the churn.
1168 let mut shortcut_links = vec![];
1170 let span_for_link = |link: &str, span: Range<usize>| {
1171 // Pulldown includes the `[]` as well as the URL. Only highlight the relevant span.
1172 // NOTE: uses `rfind` in case the title and url are the same: `[Ok][Ok]`
1173 match md[span.clone()].rfind(link) {
1175 let start = span.start + start;
1176 start..start + link.len()
1178 // This can happen for things other than intra-doc links, like `#1` expanded to `https://github.com/rust-lang/rust/issues/1`.
1182 let mut push = |link: BrokenLink<'_>| {
1183 let span = span_for_link(link.reference, link.span);
1184 shortcut_links.push((link.reference.to_owned(), span));
1187 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut push));
1189 // There's no need to thread an IdMap through to here because
1190 // the IDs generated aren't going to be emitted anywhere.
1191 let mut ids = IdMap::new();
1192 let iter = Footnotes::new(HeadingLinks::new(p.into_offset_iter(), None, &mut ids));
1195 if let Event::Start(Tag::Link(_, dest, _)) = ev.0 {
1196 debug!("found link: {}", dest);
1197 let span = span_for_link(&dest, ev.1);
1198 links.push((dest.into_string(), span));
1202 links.append(&mut shortcut_links);
1208 crate struct RustCodeBlock {
1209 /// The range in the markdown that the code block occupies. Note that this includes the fences
1210 /// for fenced code blocks.
1211 crate range: Range<usize>,
1212 /// The range in the markdown that the code within the code block occupies.
1213 crate code: Range<usize>,
1214 crate is_fenced: bool,
1215 crate syntax: Option<String>,
1218 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1219 /// untagged (and assumed to be rust).
1220 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustCodeBlock> {
1221 let mut code_blocks = vec![];
1227 let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1229 while let Some((event, offset)) = p.next() {
1230 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1231 let (syntax, code_start, code_end, range, is_fenced) = match syntax {
1232 CodeBlockKind::Fenced(syntax) => {
1233 let syntax = syntax.as_ref();
1234 let lang_string = if syntax.is_empty() {
1237 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1239 if !lang_string.rust {
1242 let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1243 let (code_start, mut code_end) = match p.next() {
1244 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1245 Some((_, sub_offset)) => {
1246 let code = Range { start: sub_offset.start, end: sub_offset.start };
1247 code_blocks.push(RustCodeBlock {
1256 let code = Range { start: offset.end, end: offset.end };
1257 code_blocks.push(RustCodeBlock {
1266 while let Some((Event::Text(_), offset)) = p.next() {
1267 code_end = offset.end;
1269 (syntax, code_start, code_end, offset, true)
1271 CodeBlockKind::Indented => {
1272 // The ending of the offset goes too far sometime so we reduce it by one in
1274 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1279 Range { start: offset.start, end: offset.end - 1 },
1283 (None, offset.start, offset.end, offset, false)
1288 code_blocks.push(RustCodeBlock {
1291 code: Range { start: code_start, end: code_end },
1300 #[derive(Clone, Default, Debug)]
1302 map: FxHashMap<String, usize>,
1305 fn init_id_map() -> FxHashMap<String, usize> {
1306 let mut map = FxHashMap::default();
1307 // This is the list of IDs used by rustdoc templates.
1308 map.insert("mainThemeStyle".to_owned(), 1);
1309 map.insert("themeStyle".to_owned(), 1);
1310 map.insert("theme-picker".to_owned(), 1);
1311 map.insert("theme-choices".to_owned(), 1);
1312 map.insert("settings-menu".to_owned(), 1);
1313 map.insert("main".to_owned(), 1);
1314 map.insert("search".to_owned(), 1);
1315 map.insert("crate-search".to_owned(), 1);
1316 map.insert("render-detail".to_owned(), 1);
1317 map.insert("toggle-all-docs".to_owned(), 1);
1318 map.insert("all-types".to_owned(), 1);
1319 map.insert("default-settings".to_owned(), 1);
1320 // This is the list of IDs used by rustdoc sections.
1321 map.insert("fields".to_owned(), 1);
1322 map.insert("variants".to_owned(), 1);
1323 map.insert("implementors-list".to_owned(), 1);
1324 map.insert("synthetic-implementors-list".to_owned(), 1);
1325 map.insert("implementations".to_owned(), 1);
1326 map.insert("trait-implementations".to_owned(), 1);
1327 map.insert("synthetic-implementations".to_owned(), 1);
1328 map.insert("blanket-implementations".to_owned(), 1);
1329 map.insert("deref-methods".to_owned(), 1);
1334 pub fn new() -> Self {
1335 IdMap { map: init_id_map() }
1338 crate fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1340 let _ = self.derive(id);
1344 crate fn reset(&mut self) {
1345 self.map = init_id_map();
1348 crate fn derive(&mut self, candidate: String) -> String {
1349 let id = match self.map.get_mut(&candidate) {
1352 let id = format!("{}-{}", candidate, *a);
1358 self.map.insert(id.clone(), 1);