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.to_string();
17 //! // ... something using html
20 #![allow(non_camel_case_types)]
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_span::edition::Edition;
25 use std::cell::RefCell;
26 use std::collections::VecDeque;
27 use std::default::Default;
32 use crate::html::highlight;
33 use crate::html::toc::TocBuilder;
36 use pulldown_cmark::{html, CowStr, Event, Options, Parser, Tag};
41 fn opts() -> Options {
42 Options::ENABLE_TABLES | Options::ENABLE_FOOTNOTES
45 /// When `to_string` is called, this struct will emit the HTML corresponding to
46 /// the rendered version of the contained markdown string.
47 pub struct Markdown<'a>(
49 /// A list of link replacements.
50 pub &'a [(String, String)],
51 /// The current list of used header IDs.
53 /// Whether to allow the use of explicit error codes in doctest lang strings.
55 /// Default edition to use when parsing doctests (to add a `fn main`).
57 pub &'a Option<Playground>,
59 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
60 pub struct MarkdownWithToc<'a>(
65 pub &'a Option<Playground>,
67 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
68 pub struct MarkdownHtml<'a>(
73 pub &'a Option<Playground>,
75 /// A tuple struct like `Markdown` that renders only the first paragraph.
76 pub struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [(String, String)]);
78 #[derive(Copy, Clone, PartialEq, Debug)]
85 pub fn from(b: bool) -> Self {
87 true => ErrorCodes::Yes,
88 false => ErrorCodes::No,
92 pub fn as_bool(self) -> bool {
94 ErrorCodes::Yes => true,
95 ErrorCodes::No => false,
100 /// Controls whether a line will be hidden or shown in HTML output.
102 /// All lines are used in documentation tests.
109 fn for_html(self) -> Option<Cow<'a, str>> {
111 Line::Shown(l) => Some(l),
112 Line::Hidden(_) => None,
116 fn for_code(self) -> Cow<'a, str> {
119 Line::Hidden(l) => Cow::Borrowed(l),
124 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
125 // have no easy way of removing a potential single space after the hashes, which
126 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
127 // order to fix it we'd have to iterate to find the first non-# character, and
128 // then reallocate to remove it; which would make us return a String.
129 fn map_line(s: &str) -> Line<'_> {
130 let trimmed = s.trim();
131 if trimmed.starts_with("##") {
132 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
133 } else if trimmed.starts_with("# ") {
135 Line::Hidden(&trimmed[2..])
136 } else if trimmed == "#" {
137 // We cannot handle '#text' because it could be #[attr].
140 Line::Shown(Cow::Borrowed(s))
144 /// Convert chars from a title for an id.
146 /// "Hello, world!" -> "hello-world"
147 fn slugify(c: char) -> Option<char> {
148 if c.is_alphanumeric() || c == '-' || c == '_' {
149 if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
150 } else if c.is_whitespace() && c.is_ascii() {
157 #[derive(Clone, Debug)]
158 pub struct Playground {
159 pub crate_name: Option<String>,
163 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
164 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
166 check_error_codes: ErrorCodes,
168 // Information about the playground if a URL has been specified, containing an
169 // optional crate name and the URL.
170 playground: &'p Option<Playground>,
173 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
176 error_codes: ErrorCodes,
178 playground: &'p Option<Playground>,
180 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
184 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
185 type Item = Event<'a>;
187 fn next(&mut self) -> Option<Self::Item> {
188 let event = self.inner.next();
192 if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
193 let parse_result = LangString::parse(&lang, self.check_error_codes, false);
194 if !parse_result.rust {
195 return Some(Event::Start(Tag::CodeBlock(lang)));
197 compile_fail = parse_result.compile_fail;
198 ignore = parse_result.ignore;
199 edition = parse_result.edition;
204 let explicit_edition = edition.is_some();
205 let edition = edition.unwrap_or(self.edition);
207 let mut origtext = String::new();
208 for event in &mut self.inner {
210 Event::End(Tag::CodeBlock(..)) => break,
211 Event::Text(ref s) => {
212 origtext.push_str(s);
217 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
218 let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
219 // insert newline to clearly separate it from the
220 // previous block so we can shorten the html output
221 let mut s = String::from("\n");
222 let playground_button = self.playground.as_ref().and_then(|playground| {
223 let krate = &playground.crate_name;
224 let url = &playground.url;
230 .map(|l| map_line(l).for_code())
231 .collect::<Vec<Cow<'_, str>>>()
233 let krate = krate.as_ref().map(|s| &**s);
234 let (test, _) = test::make_test(&test, krate, false, &Default::default(), edition);
235 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
237 let edition_string = format!("&edition={}", edition);
239 // These characters don't need to be escaped in a URI.
240 // FIXME: use a library function for percent encoding.
241 fn dont_escape(c: u8) -> bool {
242 (b'a' <= c && c <= b'z')
243 || (b'A' <= c && c <= b'Z')
244 || (b'0' <= c && c <= b'9')
255 let mut test_escaped = String::new();
256 for b in test.bytes() {
258 test_escaped.push(char::from(b));
260 write!(test_escaped, "%{:02X}", b).unwrap();
264 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
265 url, test_escaped, channel, edition_string
269 let tooltip = if ignore != Ignore::None {
270 Some(("This example is not tested".to_owned(), "ignore"))
271 } else if compile_fail {
272 Some(("This example deliberately fails to compile".to_owned(), "compile_fail"))
273 } else if explicit_edition {
274 Some((format!("This code runs with edition {}", edition), "edition"))
279 if let Some((s1, s2)) = tooltip {
280 s.push_str(&highlight::render_with_highlighting(
283 "rust-example-rendered{}",
284 if ignore != Ignore::None {
286 } else if compile_fail {
288 } else if explicit_edition {
294 playground_button.as_ref().map(String::as_str),
295 Some((s1.as_str(), s2)),
297 Some(Event::Html(s.into()))
299 s.push_str(&highlight::render_with_highlighting(
302 "rust-example-rendered{}",
303 if ignore != Ignore::None {
305 } else if compile_fail {
307 } else if explicit_edition {
313 playground_button.as_ref().map(String::as_str),
316 Some(Event::Html(s.into()))
321 /// Make headings links with anchor IDs and build up TOC.
322 struct LinkReplacer<'a, 'b, I: Iterator<Item = Event<'a>>> {
324 links: &'b [(String, String)],
327 impl<'a, 'b, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, 'b, I> {
328 fn new(iter: I, links: &'b [(String, String)]) -> Self {
329 LinkReplacer { inner: iter, links }
333 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, 'b, I> {
334 type Item = Event<'a>;
336 fn next(&mut self) -> Option<Self::Item> {
337 let event = self.inner.next();
338 if let Some(Event::Start(Tag::Link(kind, dest, text))) = event {
339 if let Some(&(_, ref replace)) = self.links.iter().find(|link| link.0 == *dest) {
340 Some(Event::Start(Tag::Link(kind, replace.to_owned().into(), text)))
342 Some(Event::Start(Tag::Link(kind, dest, text)))
350 /// Make headings links with anchor IDs and build up TOC.
351 struct HeadingLinks<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> {
353 toc: Option<&'b mut TocBuilder>,
354 buf: VecDeque<Event<'a>>,
355 id_map: &'ids mut IdMap,
358 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, 'ids, I> {
359 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
360 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
364 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, 'ids, I> {
365 type Item = Event<'a>;
367 fn next(&mut self) -> Option<Self::Item> {
368 if let Some(e) = self.buf.pop_front() {
372 let event = self.inner.next();
373 if let Some(Event::Start(Tag::Header(level))) = event {
374 let mut id = String::new();
375 for event in &mut self.inner {
377 Event::End(Tag::Header(..)) => break,
378 Event::Text(text) | Event::Code(text) => {
379 id.extend(text.chars().filter_map(slugify));
383 self.buf.push_back(event);
385 let id = self.id_map.derive(id);
387 if let Some(ref mut builder) = self.toc {
388 let mut html_header = String::new();
389 html::push_html(&mut html_header, self.buf.iter().cloned());
390 let sec = builder.push(level as u32, html_header, id.clone());
391 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
394 self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
396 let start_tags = format!(
397 "<h{level} id=\"{id}\" class=\"section-header\">\
402 return Some(Event::InlineHtml(start_tags.into()));
408 /// Extracts just the first paragraph.
409 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
415 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
416 fn new(iter: I) -> Self {
417 SummaryLine { inner: iter, started: false, depth: 0 }
421 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
428 | Tag::BlockQuote => true,
433 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
434 type Item = Event<'a>;
436 fn next(&mut self) -> Option<Self::Item> {
437 if self.started && self.depth == 0 {
443 while let Some(event) = self.inner.next() {
444 let mut is_start = true;
445 let is_allowed_tag = match event {
446 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
449 Event::Start(ref c) => {
451 check_if_allowed_tag(c)
453 Event::End(ref c) => {
456 check_if_allowed_tag(c)
460 return if is_allowed_tag == false {
462 Some(Event::Start(Tag::Paragraph))
464 Some(Event::End(Tag::Paragraph))
474 /// Moves all footnote definitions to the end and add back links to the
476 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
478 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
481 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
482 fn new(iter: I) -> Self {
483 Footnotes { inner: iter, footnotes: FxHashMap::default() }
485 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
486 let new_id = self.footnotes.keys().count() + 1;
487 let key = key.to_owned();
488 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
492 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
493 type Item = Event<'a>;
495 fn next(&mut self) -> Option<Self::Item> {
497 match self.inner.next() {
498 Some(Event::FootnoteReference(ref reference)) => {
499 let entry = self.get_entry(&reference);
500 let reference = format!(
501 "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}\
505 return Some(Event::Html(reference.into()));
507 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
508 let mut content = Vec::new();
509 for event in &mut self.inner {
510 if let Event::End(Tag::FootnoteDefinition(..)) = event {
515 let entry = self.get_entry(&def);
516 (*entry).0 = content;
518 Some(e) => return Some(e),
520 if !self.footnotes.is_empty() {
521 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
522 v.sort_by(|a, b| a.1.cmp(&b.1));
523 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
524 for (mut content, id) in v {
525 write!(ret, "<li id=\"fn{}\">", id).unwrap();
526 let mut is_paragraph = false;
527 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
531 html::push_html(&mut ret, content.into_iter());
532 write!(ret, " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
535 ret.push_str("</p>");
537 ret.push_str("</li>");
539 ret.push_str("</ol></div>");
540 return Some(Event::Html(ret.into()));
550 pub fn find_testable_code<T: test::Tester>(
553 error_codes: ErrorCodes,
554 enable_per_target_ignores: bool,
556 let mut parser = Parser::new(doc);
557 let mut prev_offset = 0;
558 let mut nb_lines = 0;
559 let mut register_header = None;
560 while let Some(event) = parser.next() {
562 Event::Start(Tag::CodeBlock(s)) => {
563 let offset = parser.get_offset();
565 let block_info = if s.is_empty() {
566 LangString::all_false()
568 LangString::parse(&*s, error_codes, enable_per_target_ignores)
570 if !block_info.rust {
573 let mut test_s = String::new();
575 while let Some(Event::Text(s)) = parser.next() {
581 .map(|l| map_line(l).for_code())
582 .collect::<Vec<Cow<'_, str>>>()
584 nb_lines += doc[prev_offset..offset].lines().count();
585 let line = tests.get_line() + nb_lines;
586 tests.add_test(text, block_info, line);
587 prev_offset = offset;
589 Event::Start(Tag::Header(level)) => {
590 register_header = Some(level as u32);
592 Event::Text(ref s) if register_header.is_some() => {
593 let level = register_header.unwrap();
595 tests.register_header("", level);
597 tests.register_header(s, level);
599 register_header = None;
606 #[derive(Eq, PartialEq, Clone, Debug)]
607 pub struct LangString {
609 pub should_panic: bool,
613 pub test_harness: bool,
614 pub compile_fail: bool,
615 pub error_codes: Vec<String>,
616 pub allow_fail: bool,
617 pub edition: Option<Edition>,
620 #[derive(Eq, PartialEq, Clone, Debug)]
628 fn all_false() -> LangString {
630 original: String::new(),
633 ignore: Ignore::None,
634 rust: true, // NB This used to be `notrust = false`
637 error_codes: Vec::new(),
645 allow_error_code_check: ErrorCodes,
646 enable_per_target_ignores: bool,
648 let allow_error_code_check = allow_error_code_check.as_bool();
649 let mut seen_rust_tags = false;
650 let mut seen_other_tags = false;
651 let mut data = LangString::all_false();
652 let mut ignores = vec![];
654 data.original = string.to_owned();
655 let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
657 for token in tokens {
661 data.should_panic = true;
662 seen_rust_tags = seen_other_tags == false;
666 seen_rust_tags = !seen_other_tags;
669 data.ignore = Ignore::All;
670 seen_rust_tags = !seen_other_tags;
672 x if x.starts_with("ignore-") => {
673 if enable_per_target_ignores {
674 ignores.push(x.trim_start_matches("ignore-").to_owned());
675 seen_rust_tags = !seen_other_tags;
679 data.allow_fail = true;
680 seen_rust_tags = !seen_other_tags;
684 seen_rust_tags = true;
687 data.test_harness = true;
688 seen_rust_tags = !seen_other_tags || seen_rust_tags;
691 data.compile_fail = true;
692 seen_rust_tags = !seen_other_tags || seen_rust_tags;
695 x if x.starts_with("edition") => {
696 data.edition = x[7..].parse::<Edition>().ok();
698 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
699 if x[1..].parse::<u32>().is_ok() {
700 data.error_codes.push(x.to_owned());
701 seen_rust_tags = !seen_other_tags || seen_rust_tags;
703 seen_other_tags = true;
706 _ => seen_other_tags = true,
709 // ignore-foo overrides ignore
710 if !ignores.is_empty() {
711 data.ignore = Ignore::Some(ignores);
714 data.rust &= !seen_other_tags || seen_rust_tags;
721 pub fn to_string(self) -> String {
722 let Markdown(md, links, mut ids, codes, edition, playground) = self;
724 // This is actually common enough to special-case
726 return String::new();
728 let replacer = |_: &str, s: &str| {
729 if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
730 Some((replace.clone(), s.to_owned()))
736 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&replacer));
738 let mut s = String::with_capacity(md.len() * 3 / 2);
740 let p = HeadingLinks::new(p, None, &mut ids);
741 let p = LinkReplacer::new(p, links);
742 let p = CodeBlocks::new(p, codes, edition, playground);
743 let p = Footnotes::new(p);
744 html::push_html(&mut s, p);
750 impl MarkdownWithToc<'_> {
751 pub fn to_string(self) -> String {
752 let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
754 let p = Parser::new_ext(md, opts());
756 let mut s = String::with_capacity(md.len() * 3 / 2);
758 let mut toc = TocBuilder::new();
761 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
762 let p = CodeBlocks::new(p, codes, edition, playground);
763 let p = Footnotes::new(p);
764 html::push_html(&mut s, p);
767 format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
771 impl MarkdownHtml<'_> {
772 pub fn to_string(self) -> String {
773 let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
775 // This is actually common enough to special-case
777 return String::new();
779 let p = Parser::new_ext(md, opts());
781 // Treat inline HTML as plain text.
782 let p = p.map(|event| match event {
783 Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
787 let mut s = String::with_capacity(md.len() * 3 / 2);
789 let p = HeadingLinks::new(p, None, &mut ids);
790 let p = CodeBlocks::new(p, codes, edition, playground);
791 let p = Footnotes::new(p);
792 html::push_html(&mut s, p);
798 impl MarkdownSummaryLine<'_> {
799 pub fn to_string(self) -> String {
800 let MarkdownSummaryLine(md, links) = self;
801 // This is actually common enough to special-case
803 return String::new();
806 let replacer = |_: &str, s: &str| {
807 if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
808 Some((replace.clone(), s.to_owned()))
814 let p = Parser::new_with_broken_link_callback(md, Options::empty(), Some(&replacer));
816 let mut s = String::new();
818 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
824 pub fn plain_summary_line(md: &str) -> String {
825 struct ParserWrapper<'a> {
831 impl<'a> Iterator for ParserWrapper<'a> {
834 fn next(&mut self) -> Option<String> {
835 let next_event = self.inner.next();
836 if next_event.is_none() {
839 let next_event = next_event.unwrap();
840 let (ret, is_in) = match next_event {
841 Event::Start(Tag::Paragraph) => (None, 1),
842 Event::Start(Tag::Header(_)) => (None, 1),
843 Event::Code(code) => (Some(format!("`{}`", code)), 0),
844 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
845 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
848 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
852 self.is_first = false;
859 let mut s = String::with_capacity(md.len() * 3 / 2);
860 let mut p = ParserWrapper { inner: Parser::new(md), is_in: 0, is_first: true };
861 while let Some(t) = p.next() {
869 pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
874 let mut links = vec![];
875 let shortcut_links = RefCell::new(vec![]);
878 let locate = |s: &str| unsafe {
879 let s_start = s.as_ptr();
880 let s_end = s_start.add(s.len());
881 let md_start = md.as_ptr();
882 let md_end = md_start.add(md.len());
883 if md_start <= s_start && s_end <= md_end {
884 let start = s_start.offset_from(md_start) as usize;
885 let end = s_end.offset_from(md_start) as usize;
892 let push = |_: &str, s: &str| {
893 shortcut_links.borrow_mut().push((s.to_owned(), locate(s)));
896 let p = Parser::new_with_broken_link_callback(md, opts(), Some(&push));
898 // There's no need to thread an IdMap through to here because
899 // the IDs generated aren't going to be emitted anywhere.
900 let mut ids = IdMap::new();
901 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
904 if let Event::Start(Tag::Link(_, dest, _)) = ev {
905 debug!("found link: {}", dest);
906 links.push(match dest {
907 CowStr::Borrowed(s) => (s.to_owned(), locate(s)),
908 s @ CowStr::Boxed(..) | s @ CowStr::Inlined(..) => (s.into_string(), None),
914 let mut shortcut_links = shortcut_links.into_inner();
915 links.extend(shortcut_links.drain(..));
921 crate struct RustCodeBlock {
922 /// The range in the markdown that the code block occupies. Note that this includes the fences
923 /// for fenced code blocks.
924 pub range: Range<usize>,
925 /// The range in the markdown that the code within the code block occupies.
926 pub code: Range<usize>,
928 pub syntax: Option<String>,
931 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
932 /// untagged (and assumed to be rust).
933 crate fn rust_code_blocks(md: &str) -> Vec<RustCodeBlock> {
934 let mut code_blocks = vec![];
940 let mut p = Parser::new_ext(md, opts());
942 let mut code_block_start = 0;
943 let mut code_start = 0;
944 let mut is_fenced = false;
945 let mut previous_offset = 0;
946 let mut in_rust_code_block = false;
947 while let Some(event) = p.next() {
948 let offset = p.get_offset();
951 Event::Start(Tag::CodeBlock(syntax)) => {
952 let lang_string = if syntax.is_empty() {
953 LangString::all_false()
955 LangString::parse(&*syntax, ErrorCodes::Yes, false)
958 if lang_string.rust {
959 in_rust_code_block = true;
962 code_block_start = match md[previous_offset..offset].find("```") {
965 previous_offset + fence_idx
974 Event::End(Tag::CodeBlock(syntax)) if in_rust_code_block => {
975 in_rust_code_block = false;
977 let code_block_end = if is_fenced {
978 let fence_str = &md[previous_offset..offset].chars().rev().collect::<String>();
981 .map(|fence_idx| offset - fence_idx)
982 .unwrap_or_else(|| offset)
983 } else if md.as_bytes().get(offset).map(|b| *b == b'\n').unwrap_or_default() {
989 let code_end = if is_fenced { previous_offset } else { code_block_end };
991 code_blocks.push(RustCodeBlock {
993 range: Range { start: code_block_start, end: code_block_end },
994 code: Range { start: code_start, end: code_end },
995 syntax: if !syntax.is_empty() { Some(syntax.into_string()) } else { None },
1001 previous_offset = offset;
1007 #[derive(Clone, Default, Debug)]
1009 map: FxHashMap<String, usize>,
1013 pub fn new() -> Self {
1017 pub fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1019 let _ = self.derive(id);
1023 pub fn reset(&mut self) {
1024 self.map = FxHashMap::default();
1027 pub fn derive(&mut self, candidate: String) -> String {
1028 let id = match self.map.get_mut(&candidate) {
1031 let id = format!("{}-{}", candidate, *a);
1037 self.map.insert(id.clone(), 1);