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 /// Make headings links with anchor IDs and build up TOC.
418 struct HeadingLinks<'a, 'b, 'ids, I> {
420 toc: Option<&'b mut TocBuilder>,
421 buf: VecDeque<Event<'a>>,
422 id_map: &'ids mut IdMap,
425 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
426 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
427 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
431 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, 'ids, I> {
432 type Item = Event<'a>;
434 fn next(&mut self) -> Option<Self::Item> {
435 if let Some(e) = self.buf.pop_front() {
439 let event = self.inner.next();
440 if let Some(Event::Start(Tag::Heading(level))) = event {
441 let mut id = String::new();
442 for event in &mut self.inner {
444 Event::End(Tag::Heading(..)) => break,
445 Event::Text(text) | Event::Code(text) => {
446 id.extend(text.chars().filter_map(slugify));
451 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
452 event => self.buf.push_back(event),
455 let id = self.id_map.derive(id);
457 if let Some(ref mut builder) = self.toc {
458 let mut html_header = String::new();
459 html::push_html(&mut html_header, self.buf.iter().cloned());
460 let sec = builder.push(level as u32, html_header, id.clone());
461 self.buf.push_front(Event::Html(format!("{} ", sec).into()));
464 self.buf.push_back(Event::Html(format!("</a></h{}>", level).into()));
466 let start_tags = format!(
467 "<h{level} id=\"{id}\" class=\"section-header\">\
472 return Some(Event::Html(start_tags.into()));
478 /// Extracts just the first paragraph.
479 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
485 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
486 fn new(iter: I) -> Self {
487 SummaryLine { inner: iter, started: false, depth: 0 }
491 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
494 Tag::Paragraph | Tag::Item | Tag::Emphasis | Tag::Strong | Tag::Link(..) | Tag::BlockQuote
498 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
499 type Item = Event<'a>;
501 fn next(&mut self) -> Option<Self::Item> {
502 if self.started && self.depth == 0 {
508 if let Some(event) = self.inner.next() {
509 let mut is_start = true;
510 let is_allowed_tag = match event {
511 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
514 Event::Start(ref c) => {
516 check_if_allowed_tag(c)
518 Event::End(ref c) => {
521 check_if_allowed_tag(c)
525 return if !is_allowed_tag {
527 Some(Event::Start(Tag::Paragraph))
529 Some(Event::End(Tag::Paragraph))
539 /// Moves all footnote definitions to the end and add back links to the
541 struct Footnotes<'a, I> {
543 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
546 impl<'a, I> Footnotes<'a, I> {
547 fn new(iter: I) -> Self {
548 Footnotes { inner: iter, footnotes: FxHashMap::default() }
551 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
552 let new_id = self.footnotes.keys().count() + 1;
553 let key = key.to_owned();
554 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
558 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
559 type Item = Event<'a>;
561 fn next(&mut self) -> Option<Self::Item> {
563 match self.inner.next() {
564 Some(Event::FootnoteReference(ref reference)) => {
565 let entry = self.get_entry(&reference);
566 let reference = format!(
567 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
570 return Some(Event::Html(reference.into()));
572 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
573 let mut content = Vec::new();
574 for event in &mut self.inner {
575 if let Event::End(Tag::FootnoteDefinition(..)) = event {
580 let entry = self.get_entry(&def);
581 (*entry).0 = content;
583 Some(e) => return Some(e),
585 if !self.footnotes.is_empty() {
586 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
587 v.sort_by(|a, b| a.1.cmp(&b.1));
588 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
589 for (mut content, id) in v {
590 write!(ret, "<li id=\"fn{}\">", id).unwrap();
591 let mut is_paragraph = false;
592 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
596 html::push_html(&mut ret, content.into_iter());
597 write!(ret, " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
600 ret.push_str("</p>");
602 ret.push_str("</li>");
604 ret.push_str("</ol></div>");
605 return Some(Event::Html(ret.into()));
615 crate fn find_testable_code<T: doctest::Tester>(
618 error_codes: ErrorCodes,
619 enable_per_target_ignores: bool,
620 extra_info: Option<&ExtraInfo<'_, '_>>,
622 let mut parser = Parser::new(doc).into_offset_iter();
623 let mut prev_offset = 0;
624 let mut nb_lines = 0;
625 let mut register_header = None;
626 while let Some((event, offset)) = parser.next() {
628 Event::Start(Tag::CodeBlock(kind)) => {
629 let block_info = match kind {
630 CodeBlockKind::Fenced(ref lang) => {
637 enable_per_target_ignores,
642 CodeBlockKind::Indented => Default::default(),
644 if !block_info.rust {
648 let mut test_s = String::new();
650 while let Some((Event::Text(s), _)) = parser.next() {
655 .map(|l| map_line(l).for_code())
656 .collect::<Vec<Cow<'_, str>>>()
659 nb_lines += doc[prev_offset..offset.start].lines().count();
660 let line = tests.get_line() + nb_lines + 1;
661 tests.add_test(text, block_info, line);
662 prev_offset = offset.start;
664 Event::Start(Tag::Heading(level)) => {
665 register_header = Some(level as u32);
667 Event::Text(ref s) if register_header.is_some() => {
668 let level = register_header.unwrap();
670 tests.register_header("", level);
672 tests.register_header(s, level);
674 register_header = None;
681 crate struct ExtraInfo<'a, 'b> {
682 hir_id: Option<HirId>,
683 item_did: Option<DefId>,
688 impl<'a, 'b> ExtraInfo<'a, 'b> {
689 crate fn new(tcx: &'a TyCtxt<'b>, hir_id: HirId, sp: Span) -> ExtraInfo<'a, 'b> {
690 ExtraInfo { hir_id: Some(hir_id), item_did: None, sp, tcx }
693 crate fn new_did(tcx: &'a TyCtxt<'b>, did: DefId, sp: Span) -> ExtraInfo<'a, 'b> {
694 ExtraInfo { hir_id: None, item_did: Some(did), sp, tcx }
697 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
698 let hir_id = match (self.hir_id, self.item_did) {
700 (None, Some(item_did)) => {
701 match item_did.as_local() {
702 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
704 // If non-local, no need to check anything.
709 (None, None) => return,
711 self.tcx.struct_span_lint_hir(
712 lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES,
716 let mut diag = lint.build(msg);
724 #[derive(Eq, PartialEq, Clone, Debug)]
725 crate struct LangString {
727 crate should_panic: bool,
729 crate ignore: Ignore,
731 crate test_harness: bool,
732 crate compile_fail: bool,
733 crate error_codes: Vec<String>,
734 crate allow_fail: bool,
735 crate edition: Option<Edition>,
738 #[derive(Eq, PartialEq, Clone, Debug)]
745 impl Default for LangString {
746 fn default() -> Self {
748 original: String::new(),
751 ignore: Ignore::None,
755 error_codes: Vec::new(),
763 fn parse_without_check(
765 allow_error_code_check: ErrorCodes,
766 enable_per_target_ignores: bool,
768 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
773 allow_error_code_check: ErrorCodes,
774 enable_per_target_ignores: bool,
775 extra: Option<&ExtraInfo<'_, '_>>,
777 let allow_error_code_check = allow_error_code_check.as_bool();
778 let mut seen_rust_tags = false;
779 let mut seen_other_tags = false;
780 let mut data = LangString::default();
781 let mut ignores = vec![];
783 data.original = string.to_owned();
784 let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
786 for token in tokens {
790 data.should_panic = true;
791 seen_rust_tags = !seen_other_tags;
795 seen_rust_tags = !seen_other_tags;
798 data.ignore = Ignore::All;
799 seen_rust_tags = !seen_other_tags;
801 x if x.starts_with("ignore-") => {
802 if enable_per_target_ignores {
803 ignores.push(x.trim_start_matches("ignore-").to_owned());
804 seen_rust_tags = !seen_other_tags;
808 data.allow_fail = true;
809 seen_rust_tags = !seen_other_tags;
813 seen_rust_tags = true;
816 data.test_harness = true;
817 seen_rust_tags = !seen_other_tags || seen_rust_tags;
820 data.compile_fail = true;
821 seen_rust_tags = !seen_other_tags || seen_rust_tags;
824 x if x.starts_with("edition") => {
825 data.edition = x[7..].parse::<Edition>().ok();
827 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
828 if x[1..].parse::<u32>().is_ok() {
829 data.error_codes.push(x.to_owned());
830 seen_rust_tags = !seen_other_tags || seen_rust_tags;
832 seen_other_tags = true;
835 x if extra.is_some() => {
836 let s = x.to_lowercase();
837 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
840 "the code block will either not be tested if not marked as a rust one \
841 or won't fail if it compiles successfully",
843 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
846 "the code block will either not be tested if not marked as a rust one \
847 or won't fail if it doesn't panic when running",
849 } else if s == "no-run" || s == "no_run" || s == "norun" {
852 "the code block will either not be tested if not marked as a rust one \
853 or will be run (which you might not want)",
855 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
858 "the code block will either not be tested if not marked as a rust one \
859 or will be run (which you might not want)",
861 } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
864 "the code block will either not be tested if not marked as a rust one \
865 or the code will be wrapped inside a main function",
870 Some((flag, help)) => {
871 if let Some(ref extra) = extra {
872 extra.error_invalid_codeblock_attr(
873 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
880 seen_other_tags = true;
882 _ => seen_other_tags = true,
885 // ignore-foo overrides ignore
886 if !ignores.is_empty() {
887 data.ignore = Ignore::Some(ignores);
890 data.rust &= !seen_other_tags || seen_rust_tags;
897 pub fn into_string(self) -> String {
898 let Markdown(md, links, mut ids, codes, edition, playground) = self;
900 // This is actually common enough to special-case
902 return String::new();
904 let mut replacer = |broken_link: BrokenLink<'_>| {
906 links.iter().find(|link| &*link.original_text == broken_link.reference)
908 Some((link.href.as_str().into(), link.new_text.as_str().into()))
914 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
916 let mut s = String::with_capacity(md.len() * 3 / 2);
918 let p = HeadingLinks::new(p, None, &mut ids);
919 let p = LinkReplacer::new(p, links);
920 let p = CodeBlocks::new(p, codes, edition, playground);
921 let p = Footnotes::new(p);
922 html::push_html(&mut s, p);
928 impl MarkdownWithToc<'_> {
929 crate fn into_string(self) -> String {
930 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
932 let p = Parser::new_ext(md, opts());
934 let mut s = String::with_capacity(md.len() * 3 / 2);
936 let mut toc = TocBuilder::new();
939 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
940 let p = CodeBlocks::new(p, codes, edition, playground);
941 let p = Footnotes::new(p);
942 html::push_html(&mut s, p);
945 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
949 impl MarkdownHtml<'_> {
950 crate fn into_string(self) -> String {
951 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
953 // This is actually common enough to special-case
955 return String::new();
957 let p = Parser::new_ext(md, opts());
959 // Treat inline HTML as plain text.
960 let p = p.map(|event| match event {
961 Event::Html(text) => Event::Text(text),
965 let mut s = String::with_capacity(md.len() * 3 / 2);
967 let p = HeadingLinks::new(p, None, &mut ids);
968 let p = CodeBlocks::new(p, codes, edition, playground);
969 let p = Footnotes::new(p);
970 html::push_html(&mut s, p);
976 impl MarkdownSummaryLine<'_> {
977 crate fn into_string(self) -> String {
978 let MarkdownSummaryLine(md, links) = self;
979 // This is actually common enough to special-case
981 return String::new();
984 let mut replacer = |broken_link: BrokenLink<'_>| {
986 links.iter().find(|link| &*link.original_text == broken_link.reference)
988 Some((link.href.as_str().into(), link.new_text.as_str().into()))
994 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
996 let mut s = String::new();
998 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1004 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1006 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1007 /// - Headings and links are stripped (though the text *is* rendered).
1008 /// - HTML, code blocks, and everything else are ignored.
1010 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1011 /// due to the provided `length_limit`.
1012 fn markdown_summary_with_limit(md: &str, length_limit: usize) -> (String, bool) {
1014 return (String::new(), false);
1017 let mut s = String::with_capacity(md.len() * 3 / 2);
1018 let mut text_length = 0;
1019 let mut stopped_early = false;
1021 fn push(s: &mut String, text_length: &mut usize, text: &str) {
1023 *text_length += text.len();
1026 'outer: for event in Parser::new_ext(md, summary_opts()) {
1028 Event::Text(text) => {
1029 for word in text.split_inclusive(char::is_whitespace) {
1030 if text_length + word.len() >= length_limit {
1031 stopped_early = true;
1035 push(&mut s, &mut text_length, word);
1038 Event::Code(code) => {
1039 if text_length + code.len() >= length_limit {
1040 stopped_early = true;
1044 s.push_str("<code>");
1045 push(&mut s, &mut text_length, code);
1046 s.push_str("</code>");
1048 Event::Start(tag) => match tag {
1049 Tag::Emphasis => s.push_str("<em>"),
1050 Tag::Strong => s.push_str("<strong>"),
1051 Tag::CodeBlock(..) => break,
1054 Event::End(tag) => match tag {
1055 Tag::Emphasis => s.push_str("</em>"),
1056 Tag::Strong => s.push_str("</strong>"),
1057 Tag::Paragraph => break,
1060 Event::HardBreak | Event::SoftBreak => {
1061 if text_length + 1 >= length_limit {
1062 stopped_early = true;
1066 push(&mut s, &mut text_length, " ");
1075 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1076 /// making it suitable for contexts like the search index.
1078 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1080 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1081 crate fn short_markdown_summary(markdown: &str) -> String {
1082 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, 59);
1091 /// Renders the first paragraph of the provided markdown as plain text.
1092 /// Useful for alt-text.
1094 /// - Headings, links, and formatting are stripped.
1095 /// - Inline code is rendered as-is, surrounded by backticks.
1096 /// - HTML and code blocks are ignored.
1097 crate fn plain_text_summary(md: &str) -> String {
1099 return String::new();
1102 let mut s = String::with_capacity(md.len() * 3 / 2);
1104 for event in Parser::new_ext(md, summary_opts()) {
1106 Event::Text(text) => s.push_str(text),
1107 Event::Code(code) => {
1112 Event::HardBreak | Event::SoftBreak => s.push(' '),
1113 Event::Start(Tag::CodeBlock(..)) => break,
1114 Event::End(Tag::Paragraph) => break,
1122 crate fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
1127 let mut links = vec![];
1128 let mut shortcut_links = vec![];
1131 let locate = |s: &str| unsafe {
1132 let s_start = s.as_ptr();
1133 let s_end = s_start.add(s.len());
1134 let md_start = md.as_ptr();
1135 let md_end = md_start.add(md.len());
1136 if md_start <= s_start && s_end <= md_end {
1137 let start = s_start.offset_from(md_start) as usize;
1138 let end = s_end.offset_from(md_start) as usize;
1145 let mut push = |link: BrokenLink<'_>| {
1146 // FIXME: use `link.span` instead of `locate`
1147 // (doing it now includes the `[]` as well as the text)
1148 shortcut_links.push((link.reference.to_owned(), locate(link.reference)));
1151 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut push));
1153 // There's no need to thread an IdMap through to here because
1154 // the IDs generated aren't going to be emitted anywhere.
1155 let mut ids = IdMap::new();
1156 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1159 if let Event::Start(Tag::Link(_, dest, _)) = ev {
1160 debug!("found link: {}", dest);
1161 links.push(match dest {
1162 CowStr::Borrowed(s) => (s.to_owned(), locate(s)),
1163 s @ (CowStr::Boxed(..) | CowStr::Inlined(..)) => (s.into_string(), None),
1169 links.append(&mut shortcut_links);
1175 crate struct RustCodeBlock {
1176 /// The range in the markdown that the code block occupies. Note that this includes the fences
1177 /// for fenced code blocks.
1178 crate range: Range<usize>,
1179 /// The range in the markdown that the code within the code block occupies.
1180 crate code: Range<usize>,
1181 crate is_fenced: bool,
1182 crate syntax: Option<String>,
1185 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1186 /// untagged (and assumed to be rust).
1187 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustCodeBlock> {
1188 let mut code_blocks = vec![];
1194 let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1196 while let Some((event, offset)) = p.next() {
1197 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1198 let (syntax, code_start, code_end, range, is_fenced) = match syntax {
1199 CodeBlockKind::Fenced(syntax) => {
1200 let syntax = syntax.as_ref();
1201 let lang_string = if syntax.is_empty() {
1204 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1206 if !lang_string.rust {
1209 let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1210 let (code_start, mut code_end) = match p.next() {
1211 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1212 Some((_, sub_offset)) => {
1213 let code = Range { start: sub_offset.start, end: sub_offset.start };
1214 code_blocks.push(RustCodeBlock {
1223 let code = Range { start: offset.end, end: offset.end };
1224 code_blocks.push(RustCodeBlock {
1233 while let Some((Event::Text(_), offset)) = p.next() {
1234 code_end = offset.end;
1236 (syntax, code_start, code_end, offset, true)
1238 CodeBlockKind::Indented => {
1239 // The ending of the offset goes too far sometime so we reduce it by one in
1241 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1246 Range { start: offset.start, end: offset.end - 1 },
1250 (None, offset.start, offset.end, offset, false)
1255 code_blocks.push(RustCodeBlock {
1258 code: Range { start: code_start, end: code_end },
1267 #[derive(Clone, Default, Debug)]
1269 map: FxHashMap<String, usize>,
1272 fn init_id_map() -> FxHashMap<String, usize> {
1273 let mut map = FxHashMap::default();
1274 // This is the list of IDs used by rustdoc templates.
1275 map.insert("mainThemeStyle".to_owned(), 1);
1276 map.insert("themeStyle".to_owned(), 1);
1277 map.insert("theme-picker".to_owned(), 1);
1278 map.insert("theme-choices".to_owned(), 1);
1279 map.insert("settings-menu".to_owned(), 1);
1280 map.insert("main".to_owned(), 1);
1281 map.insert("search".to_owned(), 1);
1282 map.insert("crate-search".to_owned(), 1);
1283 map.insert("render-detail".to_owned(), 1);
1284 map.insert("toggle-all-docs".to_owned(), 1);
1285 map.insert("all-types".to_owned(), 1);
1286 map.insert("default-settings".to_owned(), 1);
1287 // This is the list of IDs used by rustdoc sections.
1288 map.insert("fields".to_owned(), 1);
1289 map.insert("variants".to_owned(), 1);
1290 map.insert("implementors-list".to_owned(), 1);
1291 map.insert("synthetic-implementors-list".to_owned(), 1);
1292 map.insert("implementations".to_owned(), 1);
1293 map.insert("trait-implementations".to_owned(), 1);
1294 map.insert("synthetic-implementations".to_owned(), 1);
1295 map.insert("blanket-implementations".to_owned(), 1);
1296 map.insert("deref-methods".to_owned(), 1);
1301 pub fn new() -> Self {
1302 IdMap { map: init_id_map() }
1305 crate fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1307 let _ = self.derive(id);
1311 crate fn reset(&mut self) {
1312 self.map = init_id_map();
1315 crate fn derive(&mut self, candidate: String) -> String {
1316 let id = match self.map.get_mut(&candidate) {
1319 let id = format!("{}-{}", candidate, *a);
1325 self.map.insert(id.clone(), 1);