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::cell::RefCell;
29 use std::collections::VecDeque;
30 use std::default::Default;
35 use crate::clean::RenderedLink;
37 use crate::html::highlight;
38 use crate::html::toc::TocBuilder;
41 html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag,
47 /// Options for rendering Markdown in the main body of documentation.
48 pub(crate) fn opts() -> Options {
49 Options::ENABLE_TABLES | Options::ENABLE_FOOTNOTES | Options::ENABLE_STRIKETHROUGH
52 /// A subset of [`opts()`] used for rendering summaries.
53 pub(crate) fn summary_opts() -> Options {
54 Options::ENABLE_STRIKETHROUGH
57 /// When `to_string` is called, this struct will emit the HTML corresponding to
58 /// the rendered version of the contained markdown string.
59 pub struct Markdown<'a>(
61 /// A list of link replacements.
62 pub &'a [RenderedLink],
63 /// The current list of used header IDs.
65 /// Whether to allow the use of explicit error codes in doctest lang strings.
67 /// Default edition to use when parsing doctests (to add a `fn main`).
69 pub &'a Option<Playground>,
71 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
72 crate struct MarkdownWithToc<'a>(
77 crate &'a Option<Playground>,
79 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
80 crate struct MarkdownHtml<'a>(
85 crate &'a Option<Playground>,
87 /// A tuple struct like `Markdown` that renders only the first paragraph.
88 crate struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
90 #[derive(Copy, Clone, PartialEq, Debug)]
97 crate fn from(b: bool) -> Self {
99 true => ErrorCodes::Yes,
100 false => ErrorCodes::No,
104 crate fn as_bool(self) -> bool {
106 ErrorCodes::Yes => true,
107 ErrorCodes::No => false,
112 /// Controls whether a line will be hidden or shown in HTML output.
114 /// All lines are used in documentation tests.
121 fn for_html(self) -> Option<Cow<'a, str>> {
123 Line::Shown(l) => Some(l),
124 Line::Hidden(_) => None,
128 fn for_code(self) -> Cow<'a, str> {
131 Line::Hidden(l) => Cow::Borrowed(l),
136 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
137 // have no easy way of removing a potential single space after the hashes, which
138 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
139 // order to fix it we'd have to iterate to find the first non-# character, and
140 // then reallocate to remove it; which would make us return a String.
141 fn map_line(s: &str) -> Line<'_> {
142 let trimmed = s.trim();
143 if trimmed.starts_with("##") {
144 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
145 } else if let Some(stripped) = trimmed.strip_prefix("# ") {
147 Line::Hidden(&stripped)
148 } else if trimmed == "#" {
149 // We cannot handle '#text' because it could be #[attr].
152 Line::Shown(Cow::Borrowed(s))
156 /// Convert chars from a title for an id.
158 /// "Hello, world!" -> "hello-world"
159 fn slugify(c: char) -> Option<char> {
160 if c.is_alphanumeric() || c == '-' || c == '_' {
161 if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
162 } else if c.is_whitespace() && c.is_ascii() {
169 #[derive(Clone, Debug)]
170 pub struct Playground {
171 pub crate_name: Option<String>,
175 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
176 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
178 check_error_codes: ErrorCodes,
180 // Information about the playground if a URL has been specified, containing an
181 // optional crate name and the URL.
182 playground: &'p Option<Playground>,
185 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
188 error_codes: ErrorCodes,
190 playground: &'p Option<Playground>,
192 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
196 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
197 type Item = Event<'a>;
199 fn next(&mut self) -> Option<Self::Item> {
200 let event = self.inner.next();
205 if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
206 let parse_result = match kind {
207 CodeBlockKind::Fenced(ref lang) => {
208 LangString::parse_without_check(&lang, self.check_error_codes, false)
210 CodeBlockKind::Indented => Default::default(),
212 if !parse_result.rust {
213 return Some(Event::Start(Tag::CodeBlock(kind)));
215 compile_fail = parse_result.compile_fail;
216 should_panic = parse_result.should_panic;
217 ignore = parse_result.ignore;
218 edition = parse_result.edition;
223 let explicit_edition = edition.is_some();
224 let edition = edition.unwrap_or(self.edition);
226 let mut origtext = String::new();
227 for event in &mut self.inner {
229 Event::End(Tag::CodeBlock(..)) => break,
230 Event::Text(ref s) => {
231 origtext.push_str(s);
236 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
237 let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
238 // insert newline to clearly separate it from the
239 // previous block so we can shorten the html output
240 let mut s = String::from("\n");
241 let playground_button = self.playground.as_ref().and_then(|playground| {
242 let krate = &playground.crate_name;
243 let url = &playground.url;
249 .map(|l| map_line(l).for_code())
250 .collect::<Vec<Cow<'_, str>>>()
252 let krate = krate.as_ref().map(|s| &**s);
254 doctest::make_test(&test, krate, false, &Default::default(), edition, None);
255 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
257 let edition_string = format!("&edition={}", edition);
259 // These characters don't need to be escaped in a URI.
260 // FIXME: use a library function for percent encoding.
261 fn dont_escape(c: u8) -> bool {
262 (b'a' <= c && c <= b'z')
263 || (b'A' <= c && c <= b'Z')
264 || (b'0' <= c && c <= b'9')
275 let mut test_escaped = String::new();
276 for b in test.bytes() {
278 test_escaped.push(char::from(b));
280 write!(test_escaped, "%{:02X}", b).unwrap();
284 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
285 url, test_escaped, channel, edition_string
289 let tooltip = if ignore != Ignore::None {
290 Some((None, "ignore"))
291 } else if compile_fail {
292 Some((None, "compile_fail"))
293 } else if should_panic {
294 Some((None, "should_panic"))
295 } else if explicit_edition {
296 Some((Some(edition), "edition"))
301 s.push_str(&highlight::render_with_highlighting(
304 "rust-example-rendered{}",
305 if let Some((_, class)) = tooltip { format!(" {}", class) } else { String::new() }
307 playground_button.as_deref(),
311 Some(Event::Html(s.into()))
315 /// Make headings links with anchor IDs and build up TOC.
316 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
318 links: &'a [RenderedLink],
319 shortcut_link: Option<&'a RenderedLink>,
322 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
323 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
324 LinkReplacer { inner: iter, links, shortcut_link: None }
328 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
329 type Item = Event<'a>;
331 fn next(&mut self) -> Option<Self::Item> {
332 let mut event = self.inner.next();
334 // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
336 // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
337 // Remove any disambiguator.
338 Some(Event::Start(Tag::Link(
339 // [fn@f] or [fn@f][]
340 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
344 debug!("saw start of shortcut link to {} with title {}", dest, title);
345 // If this is a shortcut link, it was resolved by the broken_link_callback.
346 // So the URL will already be updated properly.
347 let link = self.links.iter().find(|&link| *link.href == **dest);
348 // Since this is an external iterator, we can't replace the inner text just yet.
349 // Store that we saw a link so we know to replace it later.
350 if let Some(link) = link {
351 trace!("it matched");
352 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
353 self.shortcut_link = Some(link);
356 // Now that we're done with the shortcut link, don't replace any more text.
357 Some(Event::End(Tag::Link(
358 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
362 debug!("saw end of shortcut link to {}", dest);
363 if self.links.iter().any(|link| *link.href == **dest) {
364 assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
365 self.shortcut_link = None;
368 // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
370 Some(Event::Code(text)) => {
371 trace!("saw code {}", text);
372 if let Some(link) = self.shortcut_link {
373 trace!("original text was {}", link.original_text);
374 // NOTE: this only replaces if the code block is the *entire* text.
375 // If only part of the link has code highlighting, the disambiguator will not be removed.
377 // This is a limitation from `collect_intra_doc_links`: it passes a full link,
378 // and does not distinguish at all between code blocks.
379 // So we could never be sure we weren't replacing too much:
380 // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
382 // NOTE: &[1..len() - 1] is to strip the backticks
383 if **text == link.original_text[1..link.original_text.len() - 1] {
384 debug!("replacing {} with {}", text, link.new_text);
385 *text = CowStr::Borrowed(&link.new_text);
389 // Replace plain text in links, but only in the middle of a shortcut link.
391 Some(Event::Text(text)) => {
392 trace!("saw text {}", text);
393 if let Some(link) = self.shortcut_link {
394 trace!("original text was {}", link.original_text);
395 // NOTE: same limitations as `Event::Code`
396 if **text == *link.original_text {
397 debug!("replacing {} with {}", text, link.new_text);
398 *text = CowStr::Borrowed(&link.new_text);
402 // If this is a link, but not a shortcut link,
403 // replace the URL, since the broken_link_callback was not called.
404 Some(Event::Start(Tag::Link(_, dest, _))) => {
405 if let Some(link) = self.links.iter().find(|&link| *link.original_text == **dest) {
406 *dest = CowStr::Borrowed(link.href.as_ref());
409 // Anything else couldn't have been a valid Rust path, so no need to replace the text.
413 // Yield the modified event
418 type SpannedEvent<'a> = (Event<'a>, Range<usize>);
420 /// Make headings links with anchor IDs and build up TOC.
421 struct HeadingLinks<'a, 'b, 'ids, I> {
423 toc: Option<&'b mut TocBuilder>,
424 buf: VecDeque<SpannedEvent<'a>>,
425 id_map: &'ids mut IdMap,
428 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
429 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
430 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
434 impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
435 for HeadingLinks<'a, 'b, 'ids, I>
437 type Item = SpannedEvent<'a>;
439 fn next(&mut self) -> Option<Self::Item> {
440 if let Some(e) = self.buf.pop_front() {
444 let event = self.inner.next();
445 if let Some((Event::Start(Tag::Heading(level)), _)) = event {
446 let mut id = String::new();
447 for event in &mut self.inner {
449 Event::End(Tag::Heading(..)) => break,
450 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
451 Event::Text(text) | Event::Code(text) => {
452 id.extend(text.chars().filter_map(slugify));
453 self.buf.push_back(event);
455 _ => self.buf.push_back(event),
458 let id = self.id_map.derive(id);
460 if let Some(ref mut builder) = self.toc {
461 let mut html_header = String::new();
462 html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
463 let sec = builder.push(level as u32, html_header, id.clone());
464 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
467 self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
469 let start_tags = format!(
470 "<h{level} id=\"{id}\" class=\"section-header\">\
475 return Some((Event::Html(start_tags.into()), 0..0));
481 /// Extracts just the first paragraph.
482 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
488 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
489 fn new(iter: I) -> Self {
490 SummaryLine { inner: iter, started: false, depth: 0 }
494 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
497 Tag::Paragraph | Tag::Item | Tag::Emphasis | Tag::Strong | Tag::Link(..) | Tag::BlockQuote
501 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
502 type Item = Event<'a>;
504 fn next(&mut self) -> Option<Self::Item> {
505 if self.started && self.depth == 0 {
511 if let Some(event) = self.inner.next() {
512 let mut is_start = true;
513 let is_allowed_tag = match event {
514 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
517 Event::Start(ref c) => {
519 check_if_allowed_tag(c)
521 Event::End(ref c) => {
524 check_if_allowed_tag(c)
528 return if !is_allowed_tag {
530 Some(Event::Start(Tag::Paragraph))
532 Some(Event::End(Tag::Paragraph))
542 /// Moves all footnote definitions to the end and add back links to the
544 struct Footnotes<'a, I> {
546 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
549 impl<'a, I> Footnotes<'a, I> {
550 fn new(iter: I) -> Self {
551 Footnotes { inner: iter, footnotes: FxHashMap::default() }
554 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
555 let new_id = self.footnotes.keys().count() + 1;
556 let key = key.to_owned();
557 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
561 impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
562 type Item = SpannedEvent<'a>;
564 fn next(&mut self) -> Option<Self::Item> {
566 match self.inner.next() {
567 Some((Event::FootnoteReference(ref reference), range)) => {
568 let entry = self.get_entry(&reference);
569 let reference = format!(
570 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
573 return Some((Event::Html(reference.into()), range));
575 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
576 let mut content = Vec::new();
577 for (event, _) in &mut self.inner {
578 if let Event::End(Tag::FootnoteDefinition(..)) = event {
583 let entry = self.get_entry(&def);
584 (*entry).0 = content;
586 Some(e) => return Some(e),
588 if !self.footnotes.is_empty() {
589 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
590 v.sort_by(|a, b| a.1.cmp(&b.1));
591 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
592 for (mut content, id) in v {
593 write!(ret, "<li id=\"fn{}\">", id).unwrap();
594 let mut is_paragraph = false;
595 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
599 html::push_html(&mut ret, content.into_iter());
600 write!(ret, " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
603 ret.push_str("</p>");
605 ret.push_str("</li>");
607 ret.push_str("</ol></div>");
608 return Some((Event::Html(ret.into()), 0..0));
618 crate fn find_testable_code<T: doctest::Tester>(
621 error_codes: ErrorCodes,
622 enable_per_target_ignores: bool,
623 extra_info: Option<&ExtraInfo<'_, '_>>,
625 let mut parser = Parser::new(doc).into_offset_iter();
626 let mut prev_offset = 0;
627 let mut nb_lines = 0;
628 let mut register_header = None;
629 while let Some((event, offset)) = parser.next() {
631 Event::Start(Tag::CodeBlock(kind)) => {
632 let block_info = match kind {
633 CodeBlockKind::Fenced(ref lang) => {
640 enable_per_target_ignores,
645 CodeBlockKind::Indented => Default::default(),
647 if !block_info.rust {
651 let mut test_s = String::new();
653 while let Some((Event::Text(s), _)) = parser.next() {
658 .map(|l| map_line(l).for_code())
659 .collect::<Vec<Cow<'_, str>>>()
662 nb_lines += doc[prev_offset..offset.start].lines().count();
663 let line = tests.get_line() + nb_lines + 1;
664 tests.add_test(text, block_info, line);
665 prev_offset = offset.start;
667 Event::Start(Tag::Heading(level)) => {
668 register_header = Some(level as u32);
670 Event::Text(ref s) if register_header.is_some() => {
671 let level = register_header.unwrap();
673 tests.register_header("", level);
675 tests.register_header(s, level);
677 register_header = None;
684 crate struct ExtraInfo<'a, 'b> {
685 hir_id: Option<HirId>,
686 item_did: Option<DefId>,
691 impl<'a, 'b> ExtraInfo<'a, 'b> {
692 crate fn new(tcx: &'a TyCtxt<'b>, hir_id: HirId, sp: Span) -> ExtraInfo<'a, 'b> {
693 ExtraInfo { hir_id: Some(hir_id), item_did: None, sp, tcx }
696 crate fn new_did(tcx: &'a TyCtxt<'b>, did: DefId, sp: Span) -> ExtraInfo<'a, 'b> {
697 ExtraInfo { hir_id: None, item_did: Some(did), sp, tcx }
700 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
701 let hir_id = match (self.hir_id, self.item_did) {
703 (None, Some(item_did)) => {
704 match item_did.as_local() {
705 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
707 // If non-local, no need to check anything.
712 (None, None) => return,
714 self.tcx.struct_span_lint_hir(
715 lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES,
719 let mut diag = lint.build(msg);
727 #[derive(Eq, PartialEq, Clone, Debug)]
728 crate struct LangString {
730 crate should_panic: bool,
732 crate ignore: Ignore,
734 crate test_harness: bool,
735 crate compile_fail: bool,
736 crate error_codes: Vec<String>,
737 crate allow_fail: bool,
738 crate edition: Option<Edition>,
741 #[derive(Eq, PartialEq, Clone, Debug)]
748 impl Default for LangString {
749 fn default() -> Self {
751 original: String::new(),
754 ignore: Ignore::None,
758 error_codes: Vec::new(),
766 fn parse_without_check(
768 allow_error_code_check: ErrorCodes,
769 enable_per_target_ignores: bool,
771 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
776 allow_error_code_check: ErrorCodes,
777 enable_per_target_ignores: bool,
778 extra: Option<&ExtraInfo<'_, '_>>,
780 let allow_error_code_check = allow_error_code_check.as_bool();
781 let mut seen_rust_tags = false;
782 let mut seen_other_tags = false;
783 let mut data = LangString::default();
784 let mut ignores = vec![];
786 data.original = string.to_owned();
787 let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
789 for token in tokens {
793 data.should_panic = true;
794 seen_rust_tags = !seen_other_tags;
798 seen_rust_tags = !seen_other_tags;
801 data.ignore = Ignore::All;
802 seen_rust_tags = !seen_other_tags;
804 x if x.starts_with("ignore-") => {
805 if enable_per_target_ignores {
806 ignores.push(x.trim_start_matches("ignore-").to_owned());
807 seen_rust_tags = !seen_other_tags;
811 data.allow_fail = true;
812 seen_rust_tags = !seen_other_tags;
816 seen_rust_tags = true;
819 data.test_harness = true;
820 seen_rust_tags = !seen_other_tags || seen_rust_tags;
823 data.compile_fail = true;
824 seen_rust_tags = !seen_other_tags || seen_rust_tags;
827 x if x.starts_with("edition") => {
828 data.edition = x[7..].parse::<Edition>().ok();
830 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
831 if x[1..].parse::<u32>().is_ok() {
832 data.error_codes.push(x.to_owned());
833 seen_rust_tags = !seen_other_tags || seen_rust_tags;
835 seen_other_tags = true;
838 x if extra.is_some() => {
839 let s = x.to_lowercase();
840 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
843 "the code block will either not be tested if not marked as a rust one \
844 or won't fail if it compiles successfully",
846 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
849 "the code block will either not be tested if not marked as a rust one \
850 or won't fail if it doesn't panic when running",
852 } else if s == "no-run" || s == "no_run" || s == "norun" {
855 "the code block will either not be tested if not marked as a rust one \
856 or will be run (which you might not want)",
858 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
861 "the code block will either not be tested if not marked as a rust one \
862 or will be run (which you might not want)",
864 } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
867 "the code block will either not be tested if not marked as a rust one \
868 or the code will be wrapped inside a main function",
873 Some((flag, help)) => {
874 if let Some(ref extra) = extra {
875 extra.error_invalid_codeblock_attr(
876 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
883 seen_other_tags = true;
885 _ => seen_other_tags = true,
888 // ignore-foo overrides ignore
889 if !ignores.is_empty() {
890 data.ignore = Ignore::Some(ignores);
893 data.rust &= !seen_other_tags || seen_rust_tags;
900 pub fn into_string(self) -> String {
901 let Markdown(md, links, mut ids, codes, edition, playground) = self;
903 // This is actually common enough to special-case
905 return String::new();
907 let mut replacer = |broken_link: BrokenLink<'_>| {
909 links.iter().find(|link| &*link.original_text == broken_link.reference)
911 Some((link.href.as_str().into(), link.new_text.as_str().into()))
917 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
918 let p = p.into_offset_iter();
920 let mut s = String::with_capacity(md.len() * 3 / 2);
922 let p = HeadingLinks::new(p, None, &mut ids);
923 let p = Footnotes::new(p);
924 let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
925 let p = CodeBlocks::new(p, codes, edition, playground);
926 html::push_html(&mut s, p);
932 impl MarkdownWithToc<'_> {
933 crate fn into_string(self) -> String {
934 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
936 let p = Parser::new_ext(md, opts()).into_offset_iter();
938 let mut s = String::with_capacity(md.len() * 3 / 2);
940 let mut toc = TocBuilder::new();
943 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
944 let p = Footnotes::new(p);
945 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
946 html::push_html(&mut s, p);
949 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
953 impl MarkdownHtml<'_> {
954 crate fn into_string(self) -> String {
955 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
957 // This is actually common enough to special-case
959 return String::new();
961 let p = Parser::new_ext(md, opts()).into_offset_iter();
963 // Treat inline HTML as plain text.
964 let p = p.map(|event| match event.0 {
965 Event::Html(text) => (Event::Text(text), event.1),
969 let mut s = String::with_capacity(md.len() * 3 / 2);
971 let p = HeadingLinks::new(p, None, &mut ids);
972 let p = Footnotes::new(p);
973 let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
974 html::push_html(&mut s, p);
980 impl MarkdownSummaryLine<'_> {
981 crate fn into_string(self) -> String {
982 let MarkdownSummaryLine(md, links) = self;
983 // This is actually common enough to special-case
985 return String::new();
988 let mut replacer = |broken_link: BrokenLink<'_>| {
990 links.iter().find(|link| &*link.original_text == broken_link.reference)
992 Some((link.href.as_str().into(), link.new_text.as_str().into()))
998 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1000 let mut s = String::new();
1002 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1008 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1010 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1011 /// - Headings and links are stripped (though the text *is* rendered).
1012 /// - HTML, code blocks, and everything else are ignored.
1014 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1015 /// due to the provided `length_limit`.
1016 fn markdown_summary_with_limit(md: &str, length_limit: usize) -> (String, bool) {
1018 return (String::new(), false);
1021 let mut s = String::with_capacity(md.len() * 3 / 2);
1022 let mut text_length = 0;
1023 let mut stopped_early = false;
1025 fn push(s: &mut String, text_length: &mut usize, text: &str) {
1027 *text_length += text.len();
1030 'outer: for event in Parser::new_ext(md, summary_opts()) {
1032 Event::Text(text) => {
1033 for word in text.split_inclusive(char::is_whitespace) {
1034 if text_length + word.len() >= length_limit {
1035 stopped_early = true;
1039 push(&mut s, &mut text_length, word);
1042 Event::Code(code) => {
1043 if text_length + code.len() >= length_limit {
1044 stopped_early = true;
1048 s.push_str("<code>");
1049 push(&mut s, &mut text_length, code);
1050 s.push_str("</code>");
1052 Event::Start(tag) => match tag {
1053 Tag::Emphasis => s.push_str("<em>"),
1054 Tag::Strong => s.push_str("<strong>"),
1055 Tag::CodeBlock(..) => break,
1058 Event::End(tag) => match tag {
1059 Tag::Emphasis => s.push_str("</em>"),
1060 Tag::Strong => s.push_str("</strong>"),
1061 Tag::Paragraph => break,
1064 Event::HardBreak | Event::SoftBreak => {
1065 if text_length + 1 >= length_limit {
1066 stopped_early = true;
1070 push(&mut s, &mut text_length, " ");
1079 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1080 /// making it suitable for contexts like the search index.
1082 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1084 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1085 crate fn short_markdown_summary(markdown: &str) -> String {
1086 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, 59);
1095 /// Renders the first paragraph of the provided markdown as plain text.
1096 /// Useful for alt-text.
1098 /// - Headings, links, and formatting are stripped.
1099 /// - Inline code is rendered as-is, surrounded by backticks.
1100 /// - HTML and code blocks are ignored.
1101 crate fn plain_text_summary(md: &str) -> String {
1103 return String::new();
1106 let mut s = String::with_capacity(md.len() * 3 / 2);
1108 for event in Parser::new_ext(md, summary_opts()) {
1110 Event::Text(text) => s.push_str(text),
1111 Event::Code(code) => {
1116 Event::HardBreak | Event::SoftBreak => s.push(' '),
1117 Event::Start(Tag::CodeBlock(..)) => break,
1118 Event::End(Tag::Paragraph) => break,
1126 crate struct MarkdownLink {
1129 pub range: Range<usize>,
1132 crate fn markdown_links(md: &str) -> Vec<MarkdownLink> {
1137 let links = RefCell::new(vec![]);
1139 // FIXME: remove this function once pulldown_cmark can provide spans for link definitions.
1140 let locate = |s: &str, fallback: Range<usize>| unsafe {
1141 let s_start = s.as_ptr();
1142 let s_end = s_start.add(s.len());
1143 let md_start = md.as_ptr();
1144 let md_end = md_start.add(md.len());
1145 if md_start <= s_start && s_end <= md_end {
1146 let start = s_start.offset_from(md_start) as usize;
1147 let end = s_end.offset_from(md_start) as usize;
1154 let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1155 // For diagnostics, we want to underline the link's definition but `span` will point at
1156 // where the link is used. This is a problem for reference-style links, where the definition
1157 // is separate from the usage.
1159 // `Borrowed` variant means the string (the link's destination) may come directly from
1160 // the markdown text and we can locate the original link destination.
1161 // NOTE: LinkReplacer also provides `Borrowed` but possibly from other sources,
1162 // so `locate()` can fall back to use `span`.
1163 CowStr::Borrowed(s) => locate(s, span),
1165 // For anything else, we can only use the provided range.
1166 CowStr::Boxed(_) | CowStr::Inlined(_) => span,
1170 let mut push = |link: BrokenLink<'_>| {
1171 let span = span_for_link(&CowStr::Borrowed(link.reference), link.span);
1172 links.borrow_mut().push(MarkdownLink {
1173 kind: LinkType::ShortcutUnknown,
1174 link: link.reference.to_owned(),
1179 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut push)).into_offset_iter();
1181 // There's no need to thread an IdMap through to here because
1182 // the IDs generated aren't going to be emitted anywhere.
1183 let mut ids = IdMap::new();
1184 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1187 if let Event::Start(Tag::Link(kind, dest, _)) = ev.0 {
1188 debug!("found link: {}", dest);
1189 let span = span_for_link(&dest, ev.1);
1190 links.borrow_mut().push(MarkdownLink { kind, link: dest.into_string(), range: span });
1198 crate struct RustCodeBlock {
1199 /// The range in the markdown that the code block occupies. Note that this includes the fences
1200 /// for fenced code blocks.
1201 crate range: Range<usize>,
1202 /// The range in the markdown that the code within the code block occupies.
1203 crate code: Range<usize>,
1204 crate is_fenced: bool,
1205 crate syntax: Option<String>,
1206 crate is_ignore: bool,
1209 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1210 /// untagged (and assumed to be rust).
1211 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustCodeBlock> {
1212 let mut code_blocks = vec![];
1218 let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1220 while let Some((event, offset)) = p.next() {
1221 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1222 let (syntax, code_start, code_end, range, is_fenced, is_ignore) = match syntax {
1223 CodeBlockKind::Fenced(syntax) => {
1224 let syntax = syntax.as_ref();
1225 let lang_string = if syntax.is_empty() {
1228 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1230 if !lang_string.rust {
1233 let is_ignore = lang_string.ignore != Ignore::None;
1234 let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1235 let (code_start, mut code_end) = match p.next() {
1236 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1237 Some((_, sub_offset)) => {
1238 let code = Range { start: sub_offset.start, end: sub_offset.start };
1239 code_blocks.push(RustCodeBlock {
1249 let code = Range { start: offset.end, end: offset.end };
1250 code_blocks.push(RustCodeBlock {
1260 while let Some((Event::Text(_), offset)) = p.next() {
1261 code_end = offset.end;
1263 (syntax, code_start, code_end, offset, true, is_ignore)
1265 CodeBlockKind::Indented => {
1266 // The ending of the offset goes too far sometime so we reduce it by one in
1268 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1273 Range { start: offset.start, end: offset.end - 1 },
1278 (None, offset.start, offset.end, offset, false, false)
1283 code_blocks.push(RustCodeBlock {
1286 code: Range { start: code_start, end: code_end },
1296 #[derive(Clone, Default, Debug)]
1298 map: FxHashMap<String, usize>,
1301 fn init_id_map() -> FxHashMap<String, usize> {
1302 let mut map = FxHashMap::default();
1303 // This is the list of IDs used by rustdoc templates.
1304 map.insert("mainThemeStyle".to_owned(), 1);
1305 map.insert("themeStyle".to_owned(), 1);
1306 map.insert("theme-picker".to_owned(), 1);
1307 map.insert("theme-choices".to_owned(), 1);
1308 map.insert("settings-menu".to_owned(), 1);
1309 map.insert("main".to_owned(), 1);
1310 map.insert("search".to_owned(), 1);
1311 map.insert("crate-search".to_owned(), 1);
1312 map.insert("render-detail".to_owned(), 1);
1313 map.insert("toggle-all-docs".to_owned(), 1);
1314 map.insert("all-types".to_owned(), 1);
1315 map.insert("default-settings".to_owned(), 1);
1316 // This is the list of IDs used by rustdoc sections.
1317 map.insert("fields".to_owned(), 1);
1318 map.insert("variants".to_owned(), 1);
1319 map.insert("implementors-list".to_owned(), 1);
1320 map.insert("synthetic-implementors-list".to_owned(), 1);
1321 map.insert("implementations".to_owned(), 1);
1322 map.insert("trait-implementations".to_owned(), 1);
1323 map.insert("synthetic-implementations".to_owned(), 1);
1324 map.insert("blanket-implementations".to_owned(), 1);
1325 map.insert("deref-methods".to_owned(), 1);
1330 pub fn new() -> Self {
1331 IdMap { map: init_id_map() }
1334 crate fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1336 let _ = self.derive(id);
1340 crate fn reset(&mut self) {
1341 self.map = init_id_map();
1344 crate fn derive(&mut self, candidate: String) -> String {
1345 let id = match self.map.get_mut(&candidate) {
1348 let id = format!("{}-{}", candidate, *a);
1354 self.map.insert(id.clone(), 1);