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_span::edition::Edition;
27 use std::cell::RefCell;
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;
40 html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag,
43 use super::format::Buffer;
48 /// Options for rendering Markdown in the main body of documentation.
49 pub(crate) fn opts() -> Options {
50 Options::ENABLE_TABLES
51 | Options::ENABLE_FOOTNOTES
52 | Options::ENABLE_STRIKETHROUGH
53 | Options::ENABLE_TASKLISTS
54 | Options::ENABLE_SMART_PUNCTUATION
57 /// A subset of [`opts()`] used for rendering summaries.
58 pub(crate) fn summary_opts() -> Options {
59 Options::ENABLE_STRIKETHROUGH | Options::ENABLE_SMART_PUNCTUATION
62 /// When `to_string` is called, this struct will emit the HTML corresponding to
63 /// the rendered version of the contained markdown string.
64 pub struct Markdown<'a>(
66 /// A list of link replacements.
67 pub &'a [RenderedLink],
68 /// The current list of used header IDs.
70 /// Whether to allow the use of explicit error codes in doctest lang strings.
72 /// Default edition to use when parsing doctests (to add a `fn main`).
74 pub &'a Option<Playground>,
76 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
77 crate struct MarkdownWithToc<'a>(
82 crate &'a Option<Playground>,
84 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
85 crate struct MarkdownHtml<'a>(
90 crate &'a Option<Playground>,
92 /// A tuple struct like `Markdown` that renders only the first paragraph.
93 crate struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
95 #[derive(Copy, Clone, PartialEq, Debug)]
102 crate fn from(b: bool) -> Self {
104 true => ErrorCodes::Yes,
105 false => ErrorCodes::No,
109 crate fn as_bool(self) -> bool {
111 ErrorCodes::Yes => true,
112 ErrorCodes::No => false,
117 /// Controls whether a line will be hidden or shown in HTML output.
119 /// All lines are used in documentation tests.
126 fn for_html(self) -> Option<Cow<'a, str>> {
128 Line::Shown(l) => Some(l),
129 Line::Hidden(_) => None,
133 fn for_code(self) -> Cow<'a, str> {
136 Line::Hidden(l) => Cow::Borrowed(l),
141 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
142 // have no easy way of removing a potential single space after the hashes, which
143 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
144 // order to fix it we'd have to iterate to find the first non-# character, and
145 // then reallocate to remove it; which would make us return a String.
146 fn map_line(s: &str) -> Line<'_> {
147 let trimmed = s.trim();
148 if trimmed.starts_with("##") {
149 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
150 } else if let Some(stripped) = trimmed.strip_prefix("# ") {
152 Line::Hidden(&stripped)
153 } else if trimmed == "#" {
154 // We cannot handle '#text' because it could be #[attr].
157 Line::Shown(Cow::Borrowed(s))
161 /// Convert chars from a title for an id.
163 /// "Hello, world!" -> "hello-world"
164 fn slugify(c: char) -> Option<char> {
165 if c.is_alphanumeric() || c == '-' || c == '_' {
166 if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
167 } else if c.is_whitespace() && c.is_ascii() {
174 #[derive(Clone, Debug)]
175 pub struct Playground {
176 pub crate_name: Option<String>,
180 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
181 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
183 check_error_codes: ErrorCodes,
185 // Information about the playground if a URL has been specified, containing an
186 // optional crate name and the URL.
187 playground: &'p Option<Playground>,
190 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
193 error_codes: ErrorCodes,
195 playground: &'p Option<Playground>,
197 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
201 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
202 type Item = Event<'a>;
204 fn next(&mut self) -> Option<Self::Item> {
205 let event = self.inner.next();
210 if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
211 let parse_result = match kind {
212 CodeBlockKind::Fenced(ref lang) => {
213 LangString::parse_without_check(&lang, self.check_error_codes, false)
215 CodeBlockKind::Indented => Default::default(),
217 if !parse_result.rust {
218 return Some(Event::Start(Tag::CodeBlock(kind)));
220 compile_fail = parse_result.compile_fail;
221 should_panic = parse_result.should_panic;
222 ignore = parse_result.ignore;
223 edition = parse_result.edition;
228 let explicit_edition = edition.is_some();
229 let edition = edition.unwrap_or(self.edition);
231 let mut origtext = String::new();
232 for event in &mut self.inner {
234 Event::End(Tag::CodeBlock(..)) => break,
235 Event::Text(ref s) => {
236 origtext.push_str(s);
241 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
242 let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
244 let playground_button = self.playground.as_ref().and_then(|playground| {
245 let krate = &playground.crate_name;
246 let url = &playground.url;
252 .map(|l| map_line(l).for_code())
253 .collect::<Vec<Cow<'_, str>>>()
255 let krate = krate.as_ref().map(|s| &**s);
257 doctest::make_test(&test, krate, false, &Default::default(), edition, None);
258 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
260 let edition_string = format!("&edition={}", edition);
262 // These characters don't need to be escaped in a URI.
263 // FIXME: use a library function for percent encoding.
264 fn dont_escape(c: u8) -> bool {
265 (b'a' <= c && c <= b'z')
266 || (b'A' <= c && c <= b'Z')
267 || (b'0' <= c && c <= b'9')
278 let mut test_escaped = String::new();
279 for b in test.bytes() {
281 test_escaped.push(char::from(b));
283 write!(test_escaped, "%{:02X}", b).unwrap();
287 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
288 url, test_escaped, channel, edition_string
292 let tooltip = if ignore != Ignore::None {
293 Some((None, "ignore"))
294 } else if compile_fail {
295 Some((None, "compile_fail"))
296 } else if should_panic {
297 Some((None, "should_panic"))
298 } else if explicit_edition {
299 Some((Some(edition), "edition"))
304 // insert newline to clearly separate it from the
305 // previous block so we can shorten the html output
306 let mut s = Buffer::new();
308 highlight::render_with_highlighting(
312 "rust-example-rendered{}",
313 if let Some((_, class)) = tooltip { format!(" {}", class) } else { String::new() }
315 playground_button.as_deref(),
320 Some(Event::Html(s.into_inner().into()))
324 /// Make headings links with anchor IDs and build up TOC.
325 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
327 links: &'a [RenderedLink],
328 shortcut_link: Option<&'a RenderedLink>,
331 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
332 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
333 LinkReplacer { inner: iter, links, shortcut_link: None }
337 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
338 type Item = Event<'a>;
340 fn next(&mut self) -> Option<Self::Item> {
341 let mut event = self.inner.next();
343 // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
345 // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
346 // Remove any disambiguator.
347 Some(Event::Start(Tag::Link(
348 // [fn@f] or [fn@f][]
349 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
353 debug!("saw start of shortcut link to {} with title {}", dest, title);
354 // If this is a shortcut link, it was resolved by the broken_link_callback.
355 // So the URL will already be updated properly.
356 let link = self.links.iter().find(|&link| *link.href == **dest);
357 // Since this is an external iterator, we can't replace the inner text just yet.
358 // Store that we saw a link so we know to replace it later.
359 if let Some(link) = link {
360 trace!("it matched");
361 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
362 self.shortcut_link = Some(link);
365 // Now that we're done with the shortcut link, don't replace any more text.
366 Some(Event::End(Tag::Link(
367 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
371 debug!("saw end of shortcut link to {}", dest);
372 if self.links.iter().any(|link| *link.href == **dest) {
373 assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
374 self.shortcut_link = None;
377 // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
379 Some(Event::Code(text)) => {
380 trace!("saw code {}", text);
381 if let Some(link) = self.shortcut_link {
382 trace!("original text was {}", link.original_text);
383 // NOTE: this only replaces if the code block is the *entire* text.
384 // If only part of the link has code highlighting, the disambiguator will not be removed.
386 // This is a limitation from `collect_intra_doc_links`: it passes a full link,
387 // and does not distinguish at all between code blocks.
388 // So we could never be sure we weren't replacing too much:
389 // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
391 // NOTE: &[1..len() - 1] is to strip the backticks
392 if **text == link.original_text[1..link.original_text.len() - 1] {
393 debug!("replacing {} with {}", text, link.new_text);
394 *text = CowStr::Borrowed(&link.new_text);
398 // Replace plain text in links, but only in the middle of a shortcut link.
400 Some(Event::Text(text)) => {
401 trace!("saw text {}", text);
402 if let Some(link) = self.shortcut_link {
403 trace!("original text was {}", link.original_text);
404 // NOTE: same limitations as `Event::Code`
405 if **text == *link.original_text {
406 debug!("replacing {} with {}", text, link.new_text);
407 *text = CowStr::Borrowed(&link.new_text);
411 // If this is a link, but not a shortcut link,
412 // replace the URL, since the broken_link_callback was not called.
413 Some(Event::Start(Tag::Link(_, dest, _))) => {
414 if let Some(link) = self.links.iter().find(|&link| *link.original_text == **dest) {
415 *dest = CowStr::Borrowed(link.href.as_ref());
418 // Anything else couldn't have been a valid Rust path, so no need to replace the text.
422 // Yield the modified event
427 type SpannedEvent<'a> = (Event<'a>, Range<usize>);
429 /// Make headings links with anchor IDs and build up TOC.
430 struct HeadingLinks<'a, 'b, 'ids, I> {
432 toc: Option<&'b mut TocBuilder>,
433 buf: VecDeque<SpannedEvent<'a>>,
434 id_map: &'ids mut IdMap,
437 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
438 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
439 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
443 impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
444 for HeadingLinks<'a, 'b, 'ids, I>
446 type Item = SpannedEvent<'a>;
448 fn next(&mut self) -> Option<Self::Item> {
449 if let Some(e) = self.buf.pop_front() {
453 let event = self.inner.next();
454 if let Some((Event::Start(Tag::Heading(level)), _)) = event {
455 let mut id = String::new();
456 for event in &mut self.inner {
458 Event::End(Tag::Heading(..)) => break,
459 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
460 Event::Text(text) | Event::Code(text) => {
461 id.extend(text.chars().filter_map(slugify));
462 self.buf.push_back(event);
464 _ => self.buf.push_back(event),
467 let id = self.id_map.derive(id);
469 if let Some(ref mut builder) = self.toc {
470 let mut html_header = String::new();
471 html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
472 let sec = builder.push(level as u32, html_header, id.clone());
473 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
476 self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
478 let start_tags = format!(
479 "<h{level} id=\"{id}\" class=\"section-header\">\
484 return Some((Event::Html(start_tags.into()), 0..0));
490 /// Extracts just the first paragraph.
491 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
497 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
498 fn new(iter: I) -> Self {
499 SummaryLine { inner: iter, started: false, depth: 0 }
503 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
506 Tag::Paragraph | Tag::Item | Tag::Emphasis | Tag::Strong | Tag::Link(..) | Tag::BlockQuote
510 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
511 type Item = Event<'a>;
513 fn next(&mut self) -> Option<Self::Item> {
514 if self.started && self.depth == 0 {
520 if let Some(event) = self.inner.next() {
521 let mut is_start = true;
522 let is_allowed_tag = match event {
523 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
526 Event::Start(ref c) => {
528 check_if_allowed_tag(c)
530 Event::End(ref c) => {
533 check_if_allowed_tag(c)
537 return if !is_allowed_tag {
539 Some(Event::Start(Tag::Paragraph))
541 Some(Event::End(Tag::Paragraph))
551 /// Moves all footnote definitions to the end and add back links to the
553 struct Footnotes<'a, I> {
555 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
558 impl<'a, I> Footnotes<'a, I> {
559 fn new(iter: I) -> Self {
560 Footnotes { inner: iter, footnotes: FxHashMap::default() }
563 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
564 let new_id = self.footnotes.keys().count() + 1;
565 let key = key.to_owned();
566 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
570 impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
571 type Item = SpannedEvent<'a>;
573 fn next(&mut self) -> Option<Self::Item> {
575 match self.inner.next() {
576 Some((Event::FootnoteReference(ref reference), range)) => {
577 let entry = self.get_entry(&reference);
578 let reference = format!(
579 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
582 return Some((Event::Html(reference.into()), range));
584 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
585 let mut content = Vec::new();
586 for (event, _) in &mut self.inner {
587 if let Event::End(Tag::FootnoteDefinition(..)) = event {
592 let entry = self.get_entry(&def);
593 (*entry).0 = content;
595 Some(e) => return Some(e),
597 if !self.footnotes.is_empty() {
598 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
599 v.sort_by(|a, b| a.1.cmp(&b.1));
600 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
601 for (mut content, id) in v {
602 write!(ret, "<li id=\"fn{}\">", id).unwrap();
603 let mut is_paragraph = false;
604 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
608 html::push_html(&mut ret, content.into_iter());
609 write!(ret, " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
612 ret.push_str("</p>");
614 ret.push_str("</li>");
616 ret.push_str("</ol></div>");
617 return Some((Event::Html(ret.into()), 0..0));
627 crate fn find_testable_code<T: doctest::Tester>(
630 error_codes: ErrorCodes,
631 enable_per_target_ignores: bool,
632 extra_info: Option<&ExtraInfo<'_>>,
634 let mut parser = Parser::new(doc).into_offset_iter();
635 let mut prev_offset = 0;
636 let mut nb_lines = 0;
637 let mut register_header = None;
638 while let Some((event, offset)) = parser.next() {
640 Event::Start(Tag::CodeBlock(kind)) => {
641 let block_info = match kind {
642 CodeBlockKind::Fenced(ref lang) => {
649 enable_per_target_ignores,
654 CodeBlockKind::Indented => Default::default(),
656 if !block_info.rust {
660 let mut test_s = String::new();
662 while let Some((Event::Text(s), _)) = parser.next() {
667 .map(|l| map_line(l).for_code())
668 .collect::<Vec<Cow<'_, str>>>()
671 nb_lines += doc[prev_offset..offset.start].lines().count();
672 let line = tests.get_line() + nb_lines + 1;
673 tests.add_test(text, block_info, line);
674 prev_offset = offset.start;
676 Event::Start(Tag::Heading(level)) => {
677 register_header = Some(level as u32);
679 Event::Text(ref s) if register_header.is_some() => {
680 let level = register_header.unwrap();
682 tests.register_header("", level);
684 tests.register_header(s, level);
686 register_header = None;
693 crate struct ExtraInfo<'tcx> {
704 impl<'tcx> ExtraInfo<'tcx> {
705 crate fn new(tcx: TyCtxt<'tcx>, hir_id: HirId, sp: Span) -> ExtraInfo<'tcx> {
706 ExtraInfo { id: ExtraInfoId::Hir(hir_id), sp, tcx }
709 crate fn new_did(tcx: TyCtxt<'tcx>, did: DefId, sp: Span) -> ExtraInfo<'tcx> {
710 ExtraInfo { id: ExtraInfoId::Def(did), sp, tcx }
713 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
714 let hir_id = match self.id {
715 ExtraInfoId::Hir(hir_id) => hir_id,
716 ExtraInfoId::Def(item_did) => {
717 match item_did.as_local() {
718 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
720 // If non-local, no need to check anything.
726 self.tcx.struct_span_lint_hir(
727 crate::lint::INVALID_CODEBLOCK_ATTRIBUTES,
731 let mut diag = lint.build(msg);
739 #[derive(Eq, PartialEq, Clone, Debug)]
740 crate struct LangString {
742 crate should_panic: bool,
744 crate ignore: Ignore,
746 crate test_harness: bool,
747 crate compile_fail: bool,
748 crate error_codes: Vec<String>,
749 crate allow_fail: bool,
750 crate edition: Option<Edition>,
753 #[derive(Eq, PartialEq, Clone, Debug)]
760 impl Default for LangString {
761 fn default() -> Self {
763 original: String::new(),
766 ignore: Ignore::None,
770 error_codes: Vec::new(),
778 fn parse_without_check(
780 allow_error_code_check: ErrorCodes,
781 enable_per_target_ignores: bool,
783 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
786 fn tokens(string: &str) -> impl Iterator<Item = &str> {
787 // Pandoc, which Rust once used for generating documentation,
788 // expects lang strings to be surrounded by `{}` and for each token
789 // to be proceeded by a `.`. Since some of these lang strings are still
790 // loose in the wild, we strip a pair of surrounding `{}` from the lang
791 // string and a leading `.` from each token.
793 let string = string.trim();
795 let first = string.chars().next();
796 let last = string.chars().last();
798 let string = if first == Some('{') && last == Some('}') {
799 &string[1..string.len() - 1]
805 .split(|c| c == ',' || c == ' ' || c == '\t')
807 .map(|token| if token.chars().next() == Some('.') { &token[1..] } else { token })
808 .filter(|token| !token.is_empty())
813 allow_error_code_check: ErrorCodes,
814 enable_per_target_ignores: bool,
815 extra: Option<&ExtraInfo<'_>>,
817 let allow_error_code_check = allow_error_code_check.as_bool();
818 let mut seen_rust_tags = false;
819 let mut seen_other_tags = false;
820 let mut data = LangString::default();
821 let mut ignores = vec![];
823 data.original = string.to_owned();
825 let tokens = Self::tokens(string).collect::<Vec<&str>>();
827 for token in tokens {
830 data.should_panic = true;
831 seen_rust_tags = !seen_other_tags;
835 seen_rust_tags = !seen_other_tags;
838 data.ignore = Ignore::All;
839 seen_rust_tags = !seen_other_tags;
841 x if x.starts_with("ignore-") => {
842 if enable_per_target_ignores {
843 ignores.push(x.trim_start_matches("ignore-").to_owned());
844 seen_rust_tags = !seen_other_tags;
848 data.allow_fail = true;
849 seen_rust_tags = !seen_other_tags;
853 seen_rust_tags = true;
856 data.test_harness = true;
857 seen_rust_tags = !seen_other_tags || seen_rust_tags;
860 data.compile_fail = true;
861 seen_rust_tags = !seen_other_tags || seen_rust_tags;
864 x if x.starts_with("edition") => {
865 data.edition = x[7..].parse::<Edition>().ok();
867 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
868 if x[1..].parse::<u32>().is_ok() {
869 data.error_codes.push(x.to_owned());
870 seen_rust_tags = !seen_other_tags || seen_rust_tags;
872 seen_other_tags = true;
875 x if extra.is_some() => {
876 let s = x.to_lowercase();
877 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
880 "the code block will either not be tested if not marked as a rust one \
881 or won't fail if it compiles successfully",
883 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
886 "the code block will either not be tested if not marked as a rust one \
887 or won't fail if it doesn't panic when running",
889 } else if s == "no-run" || s == "no_run" || s == "norun" {
892 "the code block will either not be tested if not marked as a rust one \
893 or will be run (which you might not want)",
895 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
898 "the code block will either not be tested if not marked as a rust one \
899 or will be run (which you might not want)",
901 } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
904 "the code block will either not be tested if not marked as a rust one \
905 or the code will be wrapped inside a main function",
910 Some((flag, help)) => {
911 if let Some(ref extra) = extra {
912 extra.error_invalid_codeblock_attr(
913 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
920 seen_other_tags = true;
922 _ => seen_other_tags = true,
926 // ignore-foo overrides ignore
927 if !ignores.is_empty() {
928 data.ignore = Ignore::Some(ignores);
931 data.rust &= !seen_other_tags || seen_rust_tags;
938 pub fn into_string(self) -> String {
939 let Markdown(md, links, mut ids, codes, edition, playground) = self;
941 // This is actually common enough to special-case
943 return String::new();
945 let mut replacer = |broken_link: BrokenLink<'_>| {
947 links.iter().find(|link| &*link.original_text == broken_link.reference)
949 Some((link.href.as_str().into(), link.new_text.as_str().into()))
955 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
956 let p = p.into_offset_iter();
958 let mut s = String::with_capacity(md.len() * 3 / 2);
960 let p = HeadingLinks::new(p, None, &mut ids);
961 let p = Footnotes::new(p);
962 let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
963 let p = CodeBlocks::new(p, codes, edition, playground);
964 html::push_html(&mut s, p);
970 impl MarkdownWithToc<'_> {
971 crate fn into_string(self) -> String {
972 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
974 let p = Parser::new_ext(md, opts()).into_offset_iter();
976 let mut s = String::with_capacity(md.len() * 3 / 2);
978 let mut toc = TocBuilder::new();
981 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
982 let p = Footnotes::new(p);
983 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
984 html::push_html(&mut s, p);
987 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
991 impl MarkdownHtml<'_> {
992 crate fn into_string(self) -> String {
993 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
995 // This is actually common enough to special-case
997 return String::new();
999 let p = Parser::new_ext(md, opts()).into_offset_iter();
1001 // Treat inline HTML as plain text.
1002 let p = p.map(|event| match event.0 {
1003 Event::Html(text) => (Event::Text(text), event.1),
1007 let mut s = String::with_capacity(md.len() * 3 / 2);
1009 let p = HeadingLinks::new(p, None, &mut ids);
1010 let p = Footnotes::new(p);
1011 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
1012 html::push_html(&mut s, p);
1018 impl MarkdownSummaryLine<'_> {
1019 crate fn into_string(self) -> String {
1020 let MarkdownSummaryLine(md, links) = self;
1021 // This is actually common enough to special-case
1023 return String::new();
1026 let mut replacer = |broken_link: BrokenLink<'_>| {
1028 links.iter().find(|link| &*link.original_text == broken_link.reference)
1030 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1036 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1038 let mut s = String::new();
1040 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1046 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1048 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1049 /// - Headings and links are stripped (though the text *is* rendered).
1050 /// - HTML, code blocks, and everything else are ignored.
1052 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1053 /// due to the provided `length_limit`.
1054 fn markdown_summary_with_limit(md: &str, length_limit: usize) -> (String, bool) {
1056 return (String::new(), false);
1059 let mut s = String::with_capacity(md.len() * 3 / 2);
1060 let mut text_length = 0;
1061 let mut stopped_early = false;
1063 fn push(s: &mut String, text_length: &mut usize, text: &str) {
1065 *text_length += text.len();
1068 'outer: for event in Parser::new_ext(md, summary_opts()) {
1070 Event::Text(text) => {
1071 for word in text.split_inclusive(char::is_whitespace) {
1072 if text_length + word.len() >= length_limit {
1073 stopped_early = true;
1077 push(&mut s, &mut text_length, word);
1080 Event::Code(code) => {
1081 if text_length + code.len() >= length_limit {
1082 stopped_early = true;
1086 s.push_str("<code>");
1087 push(&mut s, &mut text_length, code);
1088 s.push_str("</code>");
1090 Event::Start(tag) => match tag {
1091 Tag::Emphasis => s.push_str("<em>"),
1092 Tag::Strong => s.push_str("<strong>"),
1093 Tag::CodeBlock(..) => break,
1096 Event::End(tag) => match tag {
1097 Tag::Emphasis => s.push_str("</em>"),
1098 Tag::Strong => s.push_str("</strong>"),
1099 Tag::Paragraph => break,
1100 Tag::Heading(..) => break,
1103 Event::HardBreak | Event::SoftBreak => {
1104 if text_length + 1 >= length_limit {
1105 stopped_early = true;
1109 push(&mut s, &mut text_length, " ");
1118 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1119 /// making it suitable for contexts like the search index.
1121 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1123 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1124 crate fn short_markdown_summary(markdown: &str) -> String {
1125 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, 59);
1134 /// Renders the first paragraph of the provided markdown as plain text.
1135 /// Useful for alt-text.
1137 /// - Headings, links, and formatting are stripped.
1138 /// - Inline code is rendered as-is, surrounded by backticks.
1139 /// - HTML and code blocks are ignored.
1140 crate fn plain_text_summary(md: &str) -> String {
1142 return String::new();
1145 let mut s = String::with_capacity(md.len() * 3 / 2);
1147 for event in Parser::new_ext(md, summary_opts()) {
1149 Event::Text(text) => s.push_str(text),
1150 Event::Code(code) => {
1155 Event::HardBreak | Event::SoftBreak => s.push(' '),
1156 Event::Start(Tag::CodeBlock(..)) => break,
1157 Event::End(Tag::Paragraph) => break,
1158 Event::End(Tag::Heading(..)) => break,
1167 crate struct MarkdownLink {
1170 pub range: Range<usize>,
1173 crate fn markdown_links(md: &str) -> Vec<MarkdownLink> {
1178 let links = RefCell::new(vec![]);
1180 // FIXME: remove this function once pulldown_cmark can provide spans for link definitions.
1181 let locate = |s: &str, fallback: Range<usize>| unsafe {
1182 let s_start = s.as_ptr();
1183 let s_end = s_start.add(s.len());
1184 let md_start = md.as_ptr();
1185 let md_end = md_start.add(md.len());
1186 if md_start <= s_start && s_end <= md_end {
1187 let start = s_start.offset_from(md_start) as usize;
1188 let end = s_end.offset_from(md_start) as usize;
1195 let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1196 // For diagnostics, we want to underline the link's definition but `span` will point at
1197 // where the link is used. This is a problem for reference-style links, where the definition
1198 // is separate from the usage.
1200 // `Borrowed` variant means the string (the link's destination) may come directly from
1201 // the markdown text and we can locate the original link destination.
1202 // NOTE: LinkReplacer also provides `Borrowed` but possibly from other sources,
1203 // so `locate()` can fall back to use `span`.
1204 CowStr::Borrowed(s) => locate(s, span),
1206 // For anything else, we can only use the provided range.
1207 CowStr::Boxed(_) | CowStr::Inlined(_) => span,
1211 let mut push = |link: BrokenLink<'_>| {
1212 let span = span_for_link(&CowStr::Borrowed(link.reference), link.span);
1213 links.borrow_mut().push(MarkdownLink {
1214 kind: LinkType::ShortcutUnknown,
1215 link: link.reference.to_owned(),
1220 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut push)).into_offset_iter();
1222 // There's no need to thread an IdMap through to here because
1223 // the IDs generated aren't going to be emitted anywhere.
1224 let mut ids = IdMap::new();
1225 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1228 if let Event::Start(Tag::Link(kind, dest, _)) = ev.0 {
1229 debug!("found link: {}", dest);
1230 let span = span_for_link(&dest, ev.1);
1231 links.borrow_mut().push(MarkdownLink { kind, link: dest.into_string(), range: span });
1239 crate struct RustCodeBlock {
1240 /// The range in the markdown that the code block occupies. Note that this includes the fences
1241 /// for fenced code blocks.
1242 crate range: Range<usize>,
1243 /// The range in the markdown that the code within the code block occupies.
1244 crate code: Range<usize>,
1245 crate is_fenced: bool,
1246 crate syntax: Option<String>,
1247 crate is_ignore: bool,
1250 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1251 /// untagged (and assumed to be rust).
1252 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_>) -> Vec<RustCodeBlock> {
1253 let mut code_blocks = vec![];
1259 let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1261 while let Some((event, offset)) = p.next() {
1262 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1263 let (syntax, code_start, code_end, range, is_fenced, is_ignore) = match syntax {
1264 CodeBlockKind::Fenced(syntax) => {
1265 let syntax = syntax.as_ref();
1266 let lang_string = if syntax.is_empty() {
1269 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1271 if !lang_string.rust {
1274 let is_ignore = lang_string.ignore != Ignore::None;
1275 let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1276 let (code_start, mut code_end) = match p.next() {
1277 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1278 Some((_, sub_offset)) => {
1279 let code = Range { start: sub_offset.start, end: sub_offset.start };
1280 code_blocks.push(RustCodeBlock {
1290 let code = Range { start: offset.end, end: offset.end };
1291 code_blocks.push(RustCodeBlock {
1301 while let Some((Event::Text(_), offset)) = p.next() {
1302 code_end = offset.end;
1304 (syntax, code_start, code_end, offset, true, is_ignore)
1306 CodeBlockKind::Indented => {
1307 // The ending of the offset goes too far sometime so we reduce it by one in
1309 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1314 Range { start: offset.start, end: offset.end - 1 },
1319 (None, offset.start, offset.end, offset, false, false)
1324 code_blocks.push(RustCodeBlock {
1327 code: Range { start: code_start, end: code_end },
1337 #[derive(Clone, Default, Debug)]
1339 map: FxHashMap<String, usize>,
1342 fn init_id_map() -> FxHashMap<String, usize> {
1343 let mut map = FxHashMap::default();
1344 // This is the list of IDs used by rustdoc templates.
1345 map.insert("mainThemeStyle".to_owned(), 1);
1346 map.insert("themeStyle".to_owned(), 1);
1347 map.insert("theme-picker".to_owned(), 1);
1348 map.insert("theme-choices".to_owned(), 1);
1349 map.insert("settings-menu".to_owned(), 1);
1350 map.insert("main".to_owned(), 1);
1351 map.insert("search".to_owned(), 1);
1352 map.insert("crate-search".to_owned(), 1);
1353 map.insert("render-detail".to_owned(), 1);
1354 map.insert("toggle-all-docs".to_owned(), 1);
1355 map.insert("all-types".to_owned(), 1);
1356 map.insert("default-settings".to_owned(), 1);
1357 map.insert("rustdoc-vars".to_owned(), 1);
1358 map.insert("sidebar-vars".to_owned(), 1);
1359 map.insert("copy-path".to_owned(), 1);
1360 map.insert("help".to_owned(), 1);
1361 map.insert("TOC".to_owned(), 1);
1362 map.insert("render-detail".to_owned(), 1);
1363 // This is the list of IDs used by rustdoc sections.
1364 map.insert("fields".to_owned(), 1);
1365 map.insert("variants".to_owned(), 1);
1366 map.insert("implementors-list".to_owned(), 1);
1367 map.insert("synthetic-implementors-list".to_owned(), 1);
1368 map.insert("implementations".to_owned(), 1);
1369 map.insert("trait-implementations".to_owned(), 1);
1370 map.insert("synthetic-implementations".to_owned(), 1);
1371 map.insert("blanket-implementations".to_owned(), 1);
1372 map.insert("associated-types".to_owned(), 1);
1373 map.insert("associated-const".to_owned(), 1);
1374 map.insert("required-methods".to_owned(), 1);
1375 map.insert("provided-methods".to_owned(), 1);
1376 map.insert("implementors".to_owned(), 1);
1377 map.insert("synthetic-implementors".to_owned(), 1);
1382 pub fn new() -> Self {
1383 IdMap { map: init_id_map() }
1386 crate fn derive<S: AsRef<str> + ToString>(&mut self, candidate: S) -> String {
1387 let id = match self.map.get_mut(candidate.as_ref()) {
1388 None => candidate.to_string(),
1390 let id = format!("{}-{}", candidate.as_ref(), *a);
1396 self.map.insert(id.clone(), 1);