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 #![allow(non_camel_case_types)]
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_hir::def_id::DefId;
25 use rustc_middle::ty::TyCtxt;
26 use rustc_session::lint;
27 use rustc_span::edition::Edition;
30 use std::cell::RefCell;
31 use std::collections::VecDeque;
32 use std::default::Default;
37 use crate::html::highlight;
38 use crate::html::toc::TocBuilder;
41 use pulldown_cmark::{html, CodeBlockKind, CowStr, Event, Options, Parser, Tag};
46 fn opts() -> Options {
47 Options::ENABLE_TABLES | Options::ENABLE_FOOTNOTES | Options::ENABLE_STRIKETHROUGH
50 /// When `to_string` is called, this struct will emit the HTML corresponding to
51 /// the rendered version of the contained markdown string.
52 pub struct Markdown<'a>(
54 /// A list of link replacements.
55 pub &'a [(String, String)],
56 /// The current list of used header IDs.
58 /// Whether to allow the use of explicit error codes in doctest lang strings.
60 /// Default edition to use when parsing doctests (to add a `fn main`).
62 pub &'a Option<Playground>,
64 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
65 pub struct MarkdownWithToc<'a>(
70 pub &'a Option<Playground>,
72 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
73 pub struct MarkdownHtml<'a>(
78 pub &'a Option<Playground>,
80 /// A tuple struct like `Markdown` that renders only the first paragraph.
81 pub struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [(String, String)]);
83 #[derive(Copy, Clone, PartialEq, Debug)]
90 pub fn from(b: bool) -> Self {
92 true => ErrorCodes::Yes,
93 false => ErrorCodes::No,
97 pub fn as_bool(self) -> bool {
99 ErrorCodes::Yes => true,
100 ErrorCodes::No => false,
105 /// Controls whether a line will be hidden or shown in HTML output.
107 /// All lines are used in documentation tests.
114 fn for_html(self) -> Option<Cow<'a, str>> {
116 Line::Shown(l) => Some(l),
117 Line::Hidden(_) => None,
121 fn for_code(self) -> Cow<'a, str> {
124 Line::Hidden(l) => Cow::Borrowed(l),
129 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
130 // have no easy way of removing a potential single space after the hashes, which
131 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
132 // order to fix it we'd have to iterate to find the first non-# character, and
133 // then reallocate to remove it; which would make us return a String.
134 fn map_line(s: &str) -> Line<'_> {
135 let trimmed = s.trim();
136 if trimmed.starts_with("##") {
137 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
138 } else if trimmed.starts_with("# ") {
140 Line::Hidden(&trimmed[2..])
141 } else if trimmed == "#" {
142 // We cannot handle '#text' because it could be #[attr].
145 Line::Shown(Cow::Borrowed(s))
149 /// Convert chars from a title for an id.
151 /// "Hello, world!" -> "hello-world"
152 fn slugify(c: char) -> Option<char> {
153 if c.is_alphanumeric() || c == '-' || c == '_' {
154 if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
155 } else if c.is_whitespace() && c.is_ascii() {
162 #[derive(Clone, Debug)]
163 pub struct Playground {
164 pub crate_name: Option<String>,
168 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
169 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
171 check_error_codes: ErrorCodes,
173 // Information about the playground if a URL has been specified, containing an
174 // optional crate name and the URL.
175 playground: &'p Option<Playground>,
178 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
181 error_codes: ErrorCodes,
183 playground: &'p Option<Playground>,
185 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
189 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
190 type Item = Event<'a>;
192 fn next(&mut self) -> Option<Self::Item> {
193 let event = self.inner.next();
198 if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
199 let parse_result = match kind {
200 CodeBlockKind::Fenced(ref lang) => {
201 LangString::parse_without_check(&lang, self.check_error_codes, false)
203 CodeBlockKind::Indented => LangString::all_false(),
205 if !parse_result.rust {
206 return Some(Event::Start(Tag::CodeBlock(kind)));
208 compile_fail = parse_result.compile_fail;
209 should_panic = parse_result.should_panic;
210 ignore = parse_result.ignore;
211 edition = parse_result.edition;
216 let explicit_edition = edition.is_some();
217 let edition = edition.unwrap_or(self.edition);
219 let mut origtext = String::new();
220 for event in &mut self.inner {
222 Event::End(Tag::CodeBlock(..)) => break,
223 Event::Text(ref s) => {
224 origtext.push_str(s);
229 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
230 let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
231 // insert newline to clearly separate it from the
232 // previous block so we can shorten the html output
233 let mut s = String::from("\n");
234 let playground_button = self.playground.as_ref().and_then(|playground| {
235 let krate = &playground.crate_name;
236 let url = &playground.url;
242 .map(|l| map_line(l).for_code())
243 .collect::<Vec<Cow<'_, str>>>()
245 let krate = krate.as_ref().map(|s| &**s);
246 let (test, _) = test::make_test(&test, krate, false, &Default::default(), edition);
247 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
249 let edition_string = format!("&edition={}", edition);
251 // These characters don't need to be escaped in a URI.
252 // FIXME: use a library function for percent encoding.
253 fn dont_escape(c: u8) -> bool {
254 (b'a' <= c && c <= b'z')
255 || (b'A' <= c && c <= b'Z')
256 || (b'0' <= c && c <= b'9')
267 let mut test_escaped = String::new();
268 for b in test.bytes() {
270 test_escaped.push(char::from(b));
272 write!(test_escaped, "%{:02X}", b).unwrap();
276 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
277 url, test_escaped, channel, edition_string
281 let tooltip = if ignore != Ignore::None {
282 Some(("This example is not tested".to_owned(), "ignore"))
283 } else if compile_fail {
284 Some(("This example deliberately fails to compile".to_owned(), "compile_fail"))
285 } else if should_panic {
286 Some(("This example panics".to_owned(), "should_panic"))
287 } else if explicit_edition {
288 Some((format!("This code runs with edition {}", edition), "edition"))
293 if let Some((s1, s2)) = tooltip {
294 s.push_str(&highlight::render_with_highlighting(
297 "rust-example-rendered{}",
298 if ignore != Ignore::None {
300 } else if compile_fail {
302 } else if should_panic {
304 } else if explicit_edition {
310 playground_button.as_deref(),
311 Some((s1.as_str(), s2)),
313 Some(Event::Html(s.into()))
315 s.push_str(&highlight::render_with_highlighting(
318 "rust-example-rendered{}",
319 if ignore != Ignore::None {
321 } else if compile_fail {
323 } else if should_panic {
325 } else if explicit_edition {
331 playground_button.as_deref(),
334 Some(Event::Html(s.into()))
339 /// Make headings links with anchor IDs and build up TOC.
340 struct LinkReplacer<'a, 'b, I: Iterator<Item = Event<'a>>> {
342 links: &'b [(String, String)],
345 impl<'a, 'b, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, 'b, I> {
346 fn new(iter: I, links: &'b [(String, String)]) -> Self {
347 LinkReplacer { inner: iter, links }
351 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, 'b, I> {
352 type Item = Event<'a>;
354 fn next(&mut self) -> Option<Self::Item> {
355 let event = self.inner.next();
356 if let Some(Event::Start(Tag::Link(kind, dest, text))) = event {
357 if let Some(&(_, ref replace)) = self.links.iter().find(|link| link.0 == *dest) {
358 Some(Event::Start(Tag::Link(kind, replace.to_owned().into(), text)))
360 Some(Event::Start(Tag::Link(kind, dest, text)))
368 /// Make headings links with anchor IDs and build up TOC.
369 struct HeadingLinks<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> {
371 toc: Option<&'b mut TocBuilder>,
372 buf: VecDeque<Event<'a>>,
373 id_map: &'ids mut IdMap,
376 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, 'ids, I> {
377 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
378 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
382 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, 'ids, I> {
383 type Item = Event<'a>;
385 fn next(&mut self) -> Option<Self::Item> {
386 if let Some(e) = self.buf.pop_front() {
390 let event = self.inner.next();
391 if let Some(Event::Start(Tag::Heading(level))) = event {
392 let mut id = String::new();
393 for event in &mut self.inner {
395 Event::End(Tag::Heading(..)) => break,
396 Event::Text(text) | Event::Code(text) => {
397 id.extend(text.chars().filter_map(slugify));
402 Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
403 event => self.buf.push_back(event),
406 let id = self.id_map.derive(id);
408 if let Some(ref mut builder) = self.toc {
409 let mut html_header = String::new();
410 html::push_html(&mut html_header, self.buf.iter().cloned());
411 let sec = builder.push(level as u32, html_header, id.clone());
412 self.buf.push_front(Event::Html(format!("{} ", sec).into()));
415 self.buf.push_back(Event::Html(format!("</a></h{}>", level).into()));
417 let start_tags = format!(
418 "<h{level} id=\"{id}\" class=\"section-header\">\
423 return Some(Event::Html(start_tags.into()));
429 /// Extracts just the first paragraph.
430 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
436 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
437 fn new(iter: I) -> Self {
438 SummaryLine { inner: iter, started: false, depth: 0 }
442 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
449 | Tag::BlockQuote => true,
454 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
455 type Item = Event<'a>;
457 fn next(&mut self) -> Option<Self::Item> {
458 if self.started && self.depth == 0 {
464 if let Some(event) = self.inner.next() {
465 let mut is_start = true;
466 let is_allowed_tag = match event {
467 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
470 Event::Start(ref c) => {
472 check_if_allowed_tag(c)
474 Event::End(ref c) => {
477 check_if_allowed_tag(c)
481 return if !is_allowed_tag {
483 Some(Event::Start(Tag::Paragraph))
485 Some(Event::End(Tag::Paragraph))
495 /// Moves all footnote definitions to the end and add back links to the
497 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
499 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
502 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
503 fn new(iter: I) -> Self {
504 Footnotes { inner: iter, footnotes: FxHashMap::default() }
506 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
507 let new_id = self.footnotes.keys().count() + 1;
508 let key = key.to_owned();
509 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
513 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
514 type Item = Event<'a>;
516 fn next(&mut self) -> Option<Self::Item> {
518 match self.inner.next() {
519 Some(Event::FootnoteReference(ref reference)) => {
520 let entry = self.get_entry(&reference);
521 let reference = format!(
522 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}\
526 return Some(Event::Html(reference.into()));
528 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
529 let mut content = Vec::new();
530 for event in &mut self.inner {
531 if let Event::End(Tag::FootnoteDefinition(..)) = event {
536 let entry = self.get_entry(&def);
537 (*entry).0 = content;
539 Some(e) => return Some(e),
541 if !self.footnotes.is_empty() {
542 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
543 v.sort_by(|a, b| a.1.cmp(&b.1));
544 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
545 for (mut content, id) in v {
546 write!(ret, "<li id=\"fn{}\">", id).unwrap();
547 let mut is_paragraph = false;
548 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
552 html::push_html(&mut ret, content.into_iter());
553 write!(ret, " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
556 ret.push_str("</p>");
558 ret.push_str("</li>");
560 ret.push_str("</ol></div>");
561 return Some(Event::Html(ret.into()));
571 pub fn find_testable_code<T: test::Tester>(
574 error_codes: ErrorCodes,
575 enable_per_target_ignores: bool,
576 extra_info: Option<&ExtraInfo<'_, '_>>,
578 let mut parser = Parser::new(doc).into_offset_iter();
579 let mut prev_offset = 0;
580 let mut nb_lines = 0;
581 let mut register_header = None;
582 while let Some((event, offset)) = parser.next() {
584 Event::Start(Tag::CodeBlock(kind)) => {
585 let block_info = match kind {
586 CodeBlockKind::Fenced(ref lang) => {
588 LangString::all_false()
593 enable_per_target_ignores,
598 CodeBlockKind::Indented => LangString::all_false(),
600 if !block_info.rust {
604 let mut test_s = String::new();
606 while let Some((Event::Text(s), _)) = parser.next() {
611 .map(|l| map_line(l).for_code())
612 .collect::<Vec<Cow<'_, str>>>()
615 nb_lines += doc[prev_offset..offset.start].lines().count();
616 let line = tests.get_line() + nb_lines + 1;
617 tests.add_test(text, block_info, line);
618 prev_offset = offset.start;
620 Event::Start(Tag::Heading(level)) => {
621 register_header = Some(level as u32);
623 Event::Text(ref s) if register_header.is_some() => {
624 let level = register_header.unwrap();
626 tests.register_header("", level);
628 tests.register_header(s, level);
630 register_header = None;
637 pub struct ExtraInfo<'a, 'b> {
638 hir_id: Option<HirId>,
639 item_did: Option<DefId>,
644 impl<'a, 'b> ExtraInfo<'a, 'b> {
645 pub fn new(tcx: &'a TyCtxt<'b>, hir_id: HirId, sp: Span) -> ExtraInfo<'a, 'b> {
646 ExtraInfo { hir_id: Some(hir_id), item_did: None, sp, tcx }
649 pub fn new_did(tcx: &'a TyCtxt<'b>, did: DefId, sp: Span) -> ExtraInfo<'a, 'b> {
650 ExtraInfo { hir_id: None, item_did: Some(did), sp, tcx }
653 fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
654 let hir_id = match (self.hir_id, self.item_did) {
656 (None, Some(item_did)) => {
657 match item_did.as_local() {
658 Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
660 // If non-local, no need to check anything.
665 (None, None) => return,
667 self.tcx.struct_span_lint_hir(
668 lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES,
672 let mut diag = lint.build(msg);
680 #[derive(Eq, PartialEq, Clone, Debug)]
681 pub struct LangString {
683 pub should_panic: bool,
687 pub test_harness: bool,
688 pub compile_fail: bool,
689 pub error_codes: Vec<String>,
690 pub allow_fail: bool,
691 pub edition: Option<Edition>,
694 #[derive(Eq, PartialEq, Clone, Debug)]
702 fn all_false() -> LangString {
704 original: String::new(),
707 ignore: Ignore::None,
708 rust: true, // NB This used to be `notrust = false`
711 error_codes: Vec::new(),
717 fn parse_without_check(
719 allow_error_code_check: ErrorCodes,
720 enable_per_target_ignores: bool,
722 Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
727 allow_error_code_check: ErrorCodes,
728 enable_per_target_ignores: bool,
729 extra: Option<&ExtraInfo<'_, '_>>,
731 let allow_error_code_check = allow_error_code_check.as_bool();
732 let mut seen_rust_tags = false;
733 let mut seen_other_tags = false;
734 let mut data = LangString::all_false();
735 let mut ignores = vec![];
737 data.original = string.to_owned();
738 let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
740 for token in tokens {
744 data.should_panic = true;
745 seen_rust_tags = !seen_other_tags;
749 seen_rust_tags = !seen_other_tags;
752 data.ignore = Ignore::All;
753 seen_rust_tags = !seen_other_tags;
755 x if x.starts_with("ignore-") => {
756 if enable_per_target_ignores {
757 ignores.push(x.trim_start_matches("ignore-").to_owned());
758 seen_rust_tags = !seen_other_tags;
762 data.allow_fail = true;
763 seen_rust_tags = !seen_other_tags;
767 seen_rust_tags = true;
770 data.test_harness = true;
771 seen_rust_tags = !seen_other_tags || seen_rust_tags;
774 data.compile_fail = true;
775 seen_rust_tags = !seen_other_tags || seen_rust_tags;
778 x if x.starts_with("edition") => {
779 data.edition = x[7..].parse::<Edition>().ok();
781 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
782 if x[1..].parse::<u32>().is_ok() {
783 data.error_codes.push(x.to_owned());
784 seen_rust_tags = !seen_other_tags || seen_rust_tags;
786 seen_other_tags = true;
789 x if extra.is_some() => {
790 let s = x.to_lowercase();
791 match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
794 "the code block will either not be tested if not marked as a rust one \
795 or won't fail if it compiles successfully",
797 } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
800 "the code block will either not be tested if not marked as a rust one \
801 or won't fail if it doesn't panic when running",
803 } else if s == "no-run" || s == "no_run" || s == "norun" {
806 "the code block will either not be tested if not marked as a rust one \
807 or will be run (which you might not want)",
809 } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
812 "the code block will either not be tested if not marked as a rust one \
813 or will be run (which you might not want)",
815 } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
818 "the code block will either not be tested if not marked as a rust one \
819 or the code will be wrapped inside a main function",
824 Some((flag, help)) => {
825 if let Some(ref extra) = extra {
826 extra.error_invalid_codeblock_attr(
827 &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
834 seen_other_tags = true;
836 _ => seen_other_tags = true,
839 // ignore-foo overrides ignore
840 if !ignores.is_empty() {
841 data.ignore = Ignore::Some(ignores);
844 data.rust &= !seen_other_tags || seen_rust_tags;
851 pub fn into_string(self) -> String {
852 let Markdown(md, links, mut ids, codes, edition, playground) = self;
854 // This is actually common enough to special-case
856 return String::new();
858 let replacer = |_: &str, s: &str| {
859 if let Some(&(_, ref replace)) = links.iter().find(|link| &*link.0 == s) {
860 Some((replace.clone(), s.to_owned()))
866 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&replacer));
868 let mut s = String::with_capacity(md.len() * 3 / 2);
870 let p = HeadingLinks::new(p, None, &mut ids);
871 let p = LinkReplacer::new(p, links);
872 let p = CodeBlocks::new(p, codes, edition, playground);
873 let p = Footnotes::new(p);
874 html::push_html(&mut s, p);
880 impl MarkdownWithToc<'_> {
881 pub fn into_string(self) -> String {
882 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
884 let p = Parser::new_ext(md, opts());
886 let mut s = String::with_capacity(md.len() * 3 / 2);
888 let mut toc = TocBuilder::new();
891 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
892 let p = CodeBlocks::new(p, codes, edition, playground);
893 let p = Footnotes::new(p);
894 html::push_html(&mut s, p);
897 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
901 impl MarkdownHtml<'_> {
902 pub fn into_string(self) -> String {
903 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
905 // This is actually common enough to special-case
907 return String::new();
909 let p = Parser::new_ext(md, opts());
911 // Treat inline HTML as plain text.
912 let p = p.map(|event| match event {
913 Event::Html(text) => Event::Text(text),
917 let mut s = String::with_capacity(md.len() * 3 / 2);
919 let p = HeadingLinks::new(p, None, &mut ids);
920 let p = CodeBlocks::new(p, codes, edition, playground);
921 let p = Footnotes::new(p);
922 html::push_html(&mut s, p);
928 impl MarkdownSummaryLine<'_> {
929 pub fn into_string(self) -> String {
930 let MarkdownSummaryLine(md, links) = self;
931 // This is actually common enough to special-case
933 return String::new();
936 let replacer = |_: &str, s: &str| {
937 if let Some(&(_, ref replace)) = links.iter().find(|link| &*link.0 == s) {
938 Some((replace.clone(), s.to_owned()))
944 let p = Parser::new_with_broken_link_callback(
946 Options::ENABLE_STRIKETHROUGH,
950 let mut s = String::new();
952 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
958 pub fn plain_summary_line(md: &str) -> String {
959 struct ParserWrapper<'a> {
965 impl<'a> Iterator for ParserWrapper<'a> {
968 fn next(&mut self) -> Option<String> {
969 let next_event = self.inner.next()?;
970 let (ret, is_in) = match next_event {
971 Event::Start(Tag::Paragraph) => (None, 1),
972 Event::Start(Tag::Heading(_)) => (None, 1),
973 Event::Code(code) => (Some(format!("`{}`", code)), 0),
974 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
975 Event::End(Tag::Paragraph | Tag::Heading(_)) => (None, -1),
978 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
982 self.is_first = false;
989 let mut s = String::with_capacity(md.len() * 3 / 2);
990 let p = ParserWrapper {
991 inner: Parser::new_ext(md, Options::ENABLE_STRIKETHROUGH),
995 p.filter(|t| !t.is_empty()).for_each(|i| s.push_str(&i));
999 pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
1004 let mut links = vec![];
1005 let shortcut_links = RefCell::new(vec![]);
1008 let locate = |s: &str| unsafe {
1009 let s_start = s.as_ptr();
1010 let s_end = s_start.add(s.len());
1011 let md_start = md.as_ptr();
1012 let md_end = md_start.add(md.len());
1013 if md_start <= s_start && s_end <= md_end {
1014 let start = s_start.offset_from(md_start) as usize;
1015 let end = s_end.offset_from(md_start) as usize;
1022 let push = |_: &str, s: &str| {
1023 shortcut_links.borrow_mut().push((s.to_owned(), locate(s)));
1026 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&push));
1028 // There's no need to thread an IdMap through to here because
1029 // the IDs generated aren't going to be emitted anywhere.
1030 let mut ids = IdMap::new();
1031 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1034 if let Event::Start(Tag::Link(_, dest, _)) = ev {
1035 debug!("found link: {}", dest);
1036 links.push(match dest {
1037 CowStr::Borrowed(s) => (s.to_owned(), locate(s)),
1038 s @ (CowStr::Boxed(..) | CowStr::Inlined(..)) => (s.into_string(), None),
1044 let mut shortcut_links = shortcut_links.into_inner();
1045 links.extend(shortcut_links.drain(..));
1051 crate struct RustCodeBlock {
1052 /// The range in the markdown that the code block occupies. Note that this includes the fences
1053 /// for fenced code blocks.
1054 pub range: Range<usize>,
1055 /// The range in the markdown that the code within the code block occupies.
1056 pub code: Range<usize>,
1057 pub is_fenced: bool,
1058 pub syntax: Option<String>,
1061 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1062 /// untagged (and assumed to be rust).
1063 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustCodeBlock> {
1064 let mut code_blocks = vec![];
1070 let mut p = Parser::new_ext(md, opts()).into_offset_iter();
1072 while let Some((event, offset)) = p.next() {
1073 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1074 let (syntax, code_start, code_end, range, is_fenced) = match syntax {
1075 CodeBlockKind::Fenced(syntax) => {
1076 let syntax = syntax.as_ref();
1077 let lang_string = if syntax.is_empty() {
1078 LangString::all_false()
1080 LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1082 if !lang_string.rust {
1085 let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1086 let (code_start, mut code_end) = match p.next() {
1087 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1088 Some((_, sub_offset)) => {
1089 let code = Range { start: sub_offset.start, end: sub_offset.start };
1090 code_blocks.push(RustCodeBlock {
1099 let code = Range { start: offset.end, end: offset.end };
1100 code_blocks.push(RustCodeBlock {
1109 while let Some((Event::Text(_), offset)) = p.next() {
1110 code_end = offset.end;
1112 (syntax, code_start, code_end, offset, true)
1114 CodeBlockKind::Indented => {
1115 // The ending of the offset goes too far sometime so we reduce it by one in
1117 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1122 Range { start: offset.start, end: offset.end - 1 },
1126 (None, offset.start, offset.end, offset, false)
1131 code_blocks.push(RustCodeBlock {
1134 code: Range { start: code_start, end: code_end },
1143 #[derive(Clone, Default, Debug)]
1145 map: FxHashMap<String, usize>,
1148 fn init_id_map() -> FxHashMap<String, usize> {
1149 let mut map = FxHashMap::default();
1150 // This is the list of IDs used by rustdoc templates.
1151 map.insert("mainThemeStyle".to_owned(), 1);
1152 map.insert("themeStyle".to_owned(), 1);
1153 map.insert("theme-picker".to_owned(), 1);
1154 map.insert("theme-choices".to_owned(), 1);
1155 map.insert("settings-menu".to_owned(), 1);
1156 map.insert("main".to_owned(), 1);
1157 map.insert("search".to_owned(), 1);
1158 map.insert("crate-search".to_owned(), 1);
1159 map.insert("render-detail".to_owned(), 1);
1160 map.insert("toggle-all-docs".to_owned(), 1);
1161 map.insert("all-types".to_owned(), 1);
1162 // This is the list of IDs used by rustdoc sections.
1163 map.insert("fields".to_owned(), 1);
1164 map.insert("variants".to_owned(), 1);
1165 map.insert("implementors-list".to_owned(), 1);
1166 map.insert("synthetic-implementors-list".to_owned(), 1);
1167 map.insert("implementations".to_owned(), 1);
1168 map.insert("trait-implementations".to_owned(), 1);
1169 map.insert("synthetic-implementations".to_owned(), 1);
1170 map.insert("blanket-implementations".to_owned(), 1);
1171 map.insert("deref-methods".to_owned(), 1);
1176 pub fn new() -> Self {
1177 IdMap { map: init_id_map() }
1180 pub fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1182 let _ = self.derive(id);
1186 pub fn reset(&mut self) {
1187 self.map = init_id_map();
1190 pub fn derive(&mut self, candidate: String) -> String {
1191 let id = match self.map.get_mut(&candidate) {
1194 let id = format!("{}-{}", candidate, *a);
1200 self.map.insert(id.clone(), 1);