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, None);
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((None, "ignore"))
288 } else if compile_fail {
289 Some((None, "compile_fail"))
290 } else if should_panic {
291 Some((None, "should_panic"))
292 } else if explicit_edition {
293 Some((Some(edition), "edition"))
298 s.push_str(&highlight::render_with_highlighting(
301 "rust-example-rendered{}",
302 if let Some((_, class)) = tooltip { format!(" {}", class) } else { String::new() }
304 playground_button.as_deref(),
308 Some(Event::Html(s.into()))
312 /// Make headings links with anchor IDs and build up TOC.
313 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
315 links: &'a [RenderedLink],
316 shortcut_link: Option<&'a RenderedLink>,
319 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
320 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
321 LinkReplacer { inner: iter, links, shortcut_link: None }
325 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
326 type Item = Event<'a>;
328 fn next(&mut self) -> Option<Self::Item> {
329 use pulldown_cmark::LinkType;
331 let mut event = self.inner.next();
333 // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
335 // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
336 // Remove any disambiguator.
337 Some(Event::Start(Tag::Link(
338 // [fn@f] or [fn@f][]
339 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
343 debug!("saw start of shortcut link to {} with title {}", dest, title);
344 // If this is a shortcut link, it was resolved by the broken_link_callback.
345 // So the URL will already be updated properly.
346 let link = self.links.iter().find(|&link| *link.href == **dest);
347 // Since this is an external iterator, we can't replace the inner text just yet.
348 // Store that we saw a link so we know to replace it later.
349 if let Some(link) = link {
350 trace!("it matched");
351 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
352 self.shortcut_link = Some(link);
355 // Now that we're done with the shortcut link, don't replace any more text.
356 Some(Event::End(Tag::Link(
357 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
361 debug!("saw end of shortcut link to {}", dest);
362 if self.links.iter().any(|link| *link.href == **dest) {
363 assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
364 self.shortcut_link = None;
367 // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
369 Some(Event::Code(text)) => {
370 trace!("saw code {}", text);
371 if let Some(link) = self.shortcut_link {
372 trace!("original text was {}", link.original_text);
373 // NOTE: this only replaces if the code block is the *entire* text.
374 // If only part of the link has code highlighting, the disambiguator will not be removed.
376 // This is a limitation from `collect_intra_doc_links`: it passes a full link,
377 // and does not distinguish at all between code blocks.
378 // So we could never be sure we weren't replacing too much:
379 // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
381 // NOTE: &[1..len() - 1] is to strip the backticks
382 if **text == link.original_text[1..link.original_text.len() - 1] {
383 debug!("replacing {} with {}", text, link.new_text);
384 *text = CowStr::Borrowed(&link.new_text);
388 // Replace plain text in links, but only in the middle of a shortcut link.
390 Some(Event::Text(text)) => {
391 trace!("saw text {}", text);
392 if let Some(link) = self.shortcut_link {
393 trace!("original text was {}", link.original_text);
394 // NOTE: same limitations as `Event::Code`
395 if **text == *link.original_text {
396 debug!("replacing {} with {}", text, link.new_text);
397 *text = CowStr::Borrowed(&link.new_text);
401 // If this is a link, but not a shortcut link,
402 // replace the URL, since the broken_link_callback was not called.
403 Some(Event::Start(Tag::Link(_, dest, _))) => {
404 if let Some(link) = self.links.iter().find(|&link| *link.original_text == **dest) {
405 *dest = CowStr::Borrowed(link.href.as_ref());
408 // Anything else couldn't have been a valid Rust path, so no need to replace the text.
412 // Yield the modified event
417 type SpannedEvent<'a> = (Event<'a>, Range<usize>);
419 /// Make headings links with anchor IDs and build up TOC.
420 struct HeadingLinks<'a, 'b, 'ids, I> {
422 toc: Option<&'b mut TocBuilder>,
423 buf: VecDeque<SpannedEvent<'a>>,
424 id_map: &'ids mut IdMap,
427 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
428 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
429 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
433 impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
434 for HeadingLinks<'a, 'b, 'ids, I>
436 type Item = SpannedEvent<'a>;
438 fn next(&mut self) -> Option<Self::Item> {
439 if let Some(e) = self.buf.pop_front() {
443 let event = self.inner.next();
444 if let Some((Event::Start(Tag::Heading(level)), _)) = event {
445 let mut id = String::new();
446 for event in &mut self.inner {
448 Event::End(Tag::Heading(..)) => break,
449 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
450 Event::Text(text) | Event::Code(text) => {
451 id.extend(text.chars().filter_map(slugify));
452 self.buf.push_back(event);
454 _ => self.buf.push_back(event),
457 let id = self.id_map.derive(id);
459 if let Some(ref mut builder) = self.toc {
460 let mut html_header = String::new();
461 html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
462 let sec = builder.push(level as u32, html_header, id.clone());
463 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
466 self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
468 let start_tags = format!(
469 "<h{level} id=\"{id}\" class=\"section-header\">\
474 return Some((Event::Html(start_tags.into()), 0..0));
480 /// Extracts just the first paragraph.
481 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
487 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
488 fn new(iter: I) -> Self {
489 SummaryLine { inner: iter, started: false, depth: 0 }
493 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
500 | Tag::BlockQuote => true,
505 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
506 type Item = Event<'a>;
508 fn next(&mut self) -> Option<Self::Item> {
509 if self.started && self.depth == 0 {
515 if let Some(event) = self.inner.next() {
516 let mut is_start = true;
517 let is_allowed_tag = match event {
518 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
521 Event::Start(ref c) => {
523 check_if_allowed_tag(c)
525 Event::End(ref c) => {
528 check_if_allowed_tag(c)
532 return if !is_allowed_tag {
534 Some(Event::Start(Tag::Paragraph))
536 Some(Event::End(Tag::Paragraph))
546 /// Moves all footnote definitions to the end and add back links to the
548 struct Footnotes<'a, I> {
550 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
553 impl<'a, I> Footnotes<'a, I> {
554 fn new(iter: I) -> Self {
555 Footnotes { inner: iter, footnotes: FxHashMap::default() }
558 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
559 let new_id = self.footnotes.keys().count() + 1;
560 let key = key.to_owned();
561 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
565 impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
566 type Item = SpannedEvent<'a>;
568 fn next(&mut self) -> Option<Self::Item> {
570 match self.inner.next() {
571 Some((Event::FootnoteReference(ref reference), range)) => {
572 let entry = self.get_entry(&reference);
573 let reference = format!(
574 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
577 return Some((Event::Html(reference.into()), range));
579 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
580 let mut content = Vec::new();
581 for (event, _) in &mut self.inner {
582 if let Event::End(Tag::FootnoteDefinition(..)) = event {
587 let entry = self.get_entry(&def);
588 (*entry).0 = content;
590 Some(e) => return Some(e),
592 if !self.footnotes.is_empty() {
593 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
594 v.sort_by(|a, b| a.1.cmp(&b.1));
595 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
596 for (mut content, id) in v {
597 write!(ret, "<li id=\"fn{}\">", id).unwrap();
598 let mut is_paragraph = false;
599 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
603 html::push_html(&mut ret, content.into_iter());
604 write!(ret, " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
607 ret.push_str("</p>");
609 ret.push_str("</li>");
611 ret.push_str("</ol></div>");
612 return Some((Event::Html(ret.into()), 0..0));
622 crate fn find_testable_code<T: doctest::Tester>(
625 error_codes: ErrorCodes,
626 enable_per_target_ignores: bool,
627 extra_info: Option<&ExtraInfo<'_, '_>>,
629 let mut parser = Parser::new(doc).into_offset_iter();
630 let mut prev_offset = 0;
631 let mut nb_lines = 0;
632 let mut register_header = None;
633 while let Some((event, offset)) = parser.next() {
635 Event::Start(Tag::CodeBlock(kind)) => {
636 let block_info = match kind {
637 CodeBlockKind::Fenced(ref lang) => {
644 enable_per_target_ignores,
649 CodeBlockKind::Indented => Default::default(),
651 if !block_info.rust {
655 let mut test_s = String::new();
657 while let Some((Event::Text(s), _)) = parser.next() {
662 .map(|l| map_line(l).for_code())
663 .collect::<Vec<Cow<'_, str>>>()
666 nb_lines += doc[prev_offset..offset.start].lines().count();
667 let line = tests.get_line() + nb_lines + 1;
668 tests.add_test(text, block_info, line);
669 prev_offset = offset.start;
671 Event::Start(Tag::Heading(level)) => {
672 register_header = Some(level as u32);
674 Event::Text(ref s) if register_header.is_some() => {
675 let level = register_header.unwrap();
677 tests.register_header("", level);
679 tests.register_header(s, level);
681 register_header = None;
688 crate struct ExtraInfo<'a, 'b> {
689 hir_id: Option<HirId>,
690 item_did: Option<DefId>,
695 impl<'a, 'b> ExtraInfo<'a, 'b> {
696 crate fn new(tcx: &'a TyCtxt<'b>, hir_id: HirId, sp: Span) -> ExtraInfo<'a, 'b> {
697 ExtraInfo { hir_id: Some(hir_id), item_did: None, sp, tcx }
700 crate fn new_did(tcx: &'a TyCtxt<'b>, did: DefId, sp: Span) -> ExtraInfo<'a, 'b> {
701 ExtraInfo { hir_id: None, item_did: Some(did), sp, tcx }
704 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
705 let hir_id = match (self.hir_id, self.item_did) {
707 (None, Some(item_did)) => {
708 match item_did.as_local() {
709 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
711 // If non-local, no need to check anything.
716 (None, None) => return,
718 self.tcx.struct_span_lint_hir(
719 lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES,
723 let mut diag = lint.build(msg);
731 #[derive(Eq, PartialEq, Clone, Debug)]
732 crate struct LangString {
734 crate should_panic: bool,
736 crate ignore: Ignore,
738 crate test_harness: bool,
739 crate compile_fail: bool,
740 crate error_codes: Vec<String>,
741 crate allow_fail: bool,
742 crate edition: Option<Edition>,
745 #[derive(Eq, PartialEq, Clone, Debug)]
752 impl Default for LangString {
753 fn default() -> Self {
755 original: String::new(),
758 ignore: Ignore::None,
762 error_codes: Vec::new(),
770 fn parse_without_check(
772 allow_error_code_check: ErrorCodes,
773 enable_per_target_ignores: bool,
775 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
780 allow_error_code_check: ErrorCodes,
781 enable_per_target_ignores: bool,
782 extra: Option<&ExtraInfo<'_, '_>>,
784 let allow_error_code_check = allow_error_code_check.as_bool();
785 let mut seen_rust_tags = false;
786 let mut seen_other_tags = false;
787 let mut data = LangString::default();
788 let mut ignores = vec![];
790 data.original = string.to_owned();
791 let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
793 for token in tokens {
797 data.should_panic = true;
798 seen_rust_tags = !seen_other_tags;
802 seen_rust_tags = !seen_other_tags;
805 data.ignore = Ignore::All;
806 seen_rust_tags = !seen_other_tags;
808 x if x.starts_with("ignore-") => {
809 if enable_per_target_ignores {
810 ignores.push(x.trim_start_matches("ignore-").to_owned());
811 seen_rust_tags = !seen_other_tags;
815 data.allow_fail = true;
816 seen_rust_tags = !seen_other_tags;
820 seen_rust_tags = true;
823 data.test_harness = true;
824 seen_rust_tags = !seen_other_tags || seen_rust_tags;
827 data.compile_fail = true;
828 seen_rust_tags = !seen_other_tags || seen_rust_tags;
831 x if x.starts_with("edition") => {
832 data.edition = x[7..].parse::<Edition>().ok();
834 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
835 if x[1..].parse::<u32>().is_ok() {
836 data.error_codes.push(x.to_owned());
837 seen_rust_tags = !seen_other_tags || seen_rust_tags;
839 seen_other_tags = true;
842 x if extra.is_some() => {
843 let s = x.to_lowercase();
844 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
847 "the code block will either not be tested if not marked as a rust one \
848 or won't fail if it compiles successfully",
850 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
853 "the code block will either not be tested if not marked as a rust one \
854 or won't fail if it doesn't panic when running",
856 } else if s == "no-run" || s == "no_run" || s == "norun" {
859 "the code block will either not be tested if not marked as a rust one \
860 or will be run (which you might not want)",
862 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
865 "the code block will either not be tested if not marked as a rust one \
866 or will be run (which you might not want)",
868 } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
871 "the code block will either not be tested if not marked as a rust one \
872 or the code will be wrapped inside a main function",
877 Some((flag, help)) => {
878 if let Some(ref extra) = extra {
879 extra.error_invalid_codeblock_attr(
880 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
887 seen_other_tags = true;
889 _ => seen_other_tags = true,
892 // ignore-foo overrides ignore
893 if !ignores.is_empty() {
894 data.ignore = Ignore::Some(ignores);
897 data.rust &= !seen_other_tags || seen_rust_tags;
904 pub fn into_string(self) -> String {
905 let Markdown(md, links, mut ids, codes, edition, playground) = self;
907 // This is actually common enough to special-case
909 return String::new();
911 let mut replacer = |broken_link: BrokenLink<'_>| {
913 links.iter().find(|link| &*link.original_text == broken_link.reference)
915 Some((link.href.as_str().into(), link.new_text.as_str().into()))
921 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
922 let p = p.into_offset_iter();
924 let mut s = String::with_capacity(md.len() * 3 / 2);
926 let p = HeadingLinks::new(p, None, &mut ids);
927 let p = Footnotes::new(p);
928 let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
929 let p = CodeBlocks::new(p, codes, edition, playground);
930 html::push_html(&mut s, p);
936 impl MarkdownWithToc<'_> {
937 crate fn into_string(self) -> String {
938 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
940 let p = Parser::new_ext(md, opts()).into_offset_iter();
942 let mut s = String::with_capacity(md.len() * 3 / 2);
944 let mut toc = TocBuilder::new();
947 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
948 let p = Footnotes::new(p);
949 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
950 html::push_html(&mut s, p);
953 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
957 impl MarkdownHtml<'_> {
958 crate fn into_string(self) -> String {
959 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
961 // This is actually common enough to special-case
963 return String::new();
965 let p = Parser::new_ext(md, opts()).into_offset_iter();
967 // Treat inline HTML as plain text.
968 let p = p.map(|event| match event.0 {
969 Event::Html(text) => (Event::Text(text), event.1),
973 let mut s = String::with_capacity(md.len() * 3 / 2);
975 let p = HeadingLinks::new(p, None, &mut ids);
976 let p = Footnotes::new(p);
977 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
978 html::push_html(&mut s, p);
984 impl MarkdownSummaryLine<'_> {
985 crate fn into_string(self) -> String {
986 let MarkdownSummaryLine(md, links) = self;
987 // This is actually common enough to special-case
989 return String::new();
992 let mut replacer = |broken_link: BrokenLink<'_>| {
994 links.iter().find(|link| &*link.original_text == broken_link.reference)
996 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1002 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1004 let mut s = String::new();
1006 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1012 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1014 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1015 /// - Headings and links are stripped (though the text *is* rendered).
1016 /// - HTML, code blocks, and everything else are ignored.
1018 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1019 /// due to the provided `length_limit`.
1020 fn markdown_summary_with_limit(md: &str, length_limit: usize) -> (String, bool) {
1022 return (String::new(), false);
1025 let mut s = String::with_capacity(md.len() * 3 / 2);
1026 let mut text_length = 0;
1027 let mut stopped_early = false;
1029 fn push(s: &mut String, text_length: &mut usize, text: &str) {
1031 *text_length += text.len();
1034 'outer: for event in Parser::new_ext(md, summary_opts()) {
1036 Event::Text(text) => {
1037 for word in text.split_inclusive(char::is_whitespace) {
1038 if text_length + word.len() >= length_limit {
1039 stopped_early = true;
1043 push(&mut s, &mut text_length, word);
1046 Event::Code(code) => {
1047 if text_length + code.len() >= length_limit {
1048 stopped_early = true;
1052 s.push_str("<code>");
1053 push(&mut s, &mut text_length, code);
1054 s.push_str("</code>");
1056 Event::Start(tag) => match tag {
1057 Tag::Emphasis => s.push_str("<em>"),
1058 Tag::Strong => s.push_str("<strong>"),
1059 Tag::CodeBlock(..) => break,
1062 Event::End(tag) => match tag {
1063 Tag::Emphasis => s.push_str("</em>"),
1064 Tag::Strong => s.push_str("</strong>"),
1065 Tag::Paragraph => break,
1068 Event::HardBreak | Event::SoftBreak => {
1069 if text_length + 1 >= length_limit {
1070 stopped_early = true;
1074 push(&mut s, &mut text_length, " ");
1083 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1084 /// making it suitable for contexts like the search index.
1086 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1088 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1089 crate fn short_markdown_summary(markdown: &str) -> String {
1090 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, 59);
1099 /// Renders the first paragraph of the provided markdown as plain text.
1100 /// Useful for alt-text.
1102 /// - Headings, links, and formatting are stripped.
1103 /// - Inline code is rendered as-is, surrounded by backticks.
1104 /// - HTML and code blocks are ignored.
1105 crate fn plain_text_summary(md: &str) -> String {
1107 return String::new();
1110 let mut s = String::with_capacity(md.len() * 3 / 2);
1112 for event in Parser::new_ext(md, summary_opts()) {
1114 Event::Text(text) => s.push_str(text),
1115 Event::Code(code) => {
1120 Event::HardBreak | Event::SoftBreak => s.push(' '),
1121 Event::Start(Tag::CodeBlock(..)) => break,
1122 Event::End(Tag::Paragraph) => break,
1130 crate fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
1135 let mut links = vec![];
1136 let mut shortcut_links = vec![];
1138 let locate = |s: &str| unsafe {
1139 let s_start = s.as_ptr();
1140 let s_end = s_start.add(s.len());
1141 let md_start = md.as_ptr();
1142 let md_end = md_start.add(md.len());
1143 if md_start <= s_start && s_end <= md_end {
1144 let start = s_start.offset_from(md_start) as usize;
1145 let end = s_end.offset_from(md_start) as usize;
1152 let mut push = |link: BrokenLink<'_>| {
1153 // FIXME: use `link.span` instead of `locate`
1154 // (doing it now includes the `[]` as well as the text)
1155 shortcut_links.push((link.reference.to_owned(), locate(link.reference)));
1158 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut push)).into_offset_iter();
1160 // There's no need to thread an IdMap through to here because
1161 // the IDs generated aren't going to be emitted anywhere.
1162 let mut ids = IdMap::new();
1163 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1166 if let Event::Start(Tag::Link(_, dest, _)) = ev.0 {
1167 debug!("found link: {}", dest);
1168 links.push(match dest {
1169 CowStr::Borrowed(s) => (s.to_owned(), locate(s)),
1170 s @ (CowStr::Boxed(..) | CowStr::Inlined(..)) => (s.into_string(), None),
1175 links.append(&mut shortcut_links);
1181 crate struct RustCodeBlock {
1182 /// The range in the markdown that the code block occupies. Note that this includes the fences
1183 /// for fenced code blocks.
1184 crate range: Range<usize>,
1185 /// The range in the markdown that the code within the code block occupies.
1186 crate code: Range<usize>,
1187 crate is_fenced: bool,
1188 crate syntax: Option<String>,
1191 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1192 /// untagged (and assumed to be rust).
1193 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustCodeBlock> {
1194 let mut code_blocks = vec![];
1200 let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1202 while let Some((event, offset)) = p.next() {
1203 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1204 let (syntax, code_start, code_end, range, is_fenced) = match syntax {
1205 CodeBlockKind::Fenced(syntax) => {
1206 let syntax = syntax.as_ref();
1207 let lang_string = if syntax.is_empty() {
1210 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1212 if !lang_string.rust {
1215 let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1216 let (code_start, mut code_end) = match p.next() {
1217 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1218 Some((_, sub_offset)) => {
1219 let code = Range { start: sub_offset.start, end: sub_offset.start };
1220 code_blocks.push(RustCodeBlock {
1229 let code = Range { start: offset.end, end: offset.end };
1230 code_blocks.push(RustCodeBlock {
1239 while let Some((Event::Text(_), offset)) = p.next() {
1240 code_end = offset.end;
1242 (syntax, code_start, code_end, offset, true)
1244 CodeBlockKind::Indented => {
1245 // The ending of the offset goes too far sometime so we reduce it by one in
1247 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1252 Range { start: offset.start, end: offset.end - 1 },
1256 (None, offset.start, offset.end, offset, false)
1261 code_blocks.push(RustCodeBlock {
1264 code: Range { start: code_start, end: code_end },
1273 #[derive(Clone, Default, Debug)]
1275 map: FxHashMap<String, usize>,
1278 fn init_id_map() -> FxHashMap<String, usize> {
1279 let mut map = FxHashMap::default();
1280 // This is the list of IDs used by rustdoc templates.
1281 map.insert("mainThemeStyle".to_owned(), 1);
1282 map.insert("themeStyle".to_owned(), 1);
1283 map.insert("theme-picker".to_owned(), 1);
1284 map.insert("theme-choices".to_owned(), 1);
1285 map.insert("settings-menu".to_owned(), 1);
1286 map.insert("main".to_owned(), 1);
1287 map.insert("search".to_owned(), 1);
1288 map.insert("crate-search".to_owned(), 1);
1289 map.insert("render-detail".to_owned(), 1);
1290 map.insert("toggle-all-docs".to_owned(), 1);
1291 map.insert("all-types".to_owned(), 1);
1292 map.insert("default-settings".to_owned(), 1);
1293 // This is the list of IDs used by rustdoc sections.
1294 map.insert("fields".to_owned(), 1);
1295 map.insert("variants".to_owned(), 1);
1296 map.insert("implementors-list".to_owned(), 1);
1297 map.insert("synthetic-implementors-list".to_owned(), 1);
1298 map.insert("implementations".to_owned(), 1);
1299 map.insert("trait-implementations".to_owned(), 1);
1300 map.insert("synthetic-implementations".to_owned(), 1);
1301 map.insert("blanket-implementations".to_owned(), 1);
1302 map.insert("deref-methods".to_owned(), 1);
1307 pub fn new() -> Self {
1308 IdMap { map: init_id_map() }
1311 crate fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1313 let _ = self.derive(id);
1317 crate fn reset(&mut self) {
1318 self.map = init_id_map();
1321 crate fn derive(&mut self, candidate: String) -> String {
1322 let id = match self.map.get_mut(&candidate) {
1325 let id = format!("{}-{}", candidate, *a);
1331 self.map.insert(id.clone(), 1);