1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Markdown formatting for rustdoc
13 //! This module implements markdown formatting through the pulldown-cmark
14 //! rust-library. This module exposes all of the
15 //! functionality through a unit-struct, `Markdown`, which has an implementation
16 //! of `fmt::Display`. Example usage:
19 //! use rustdoc::html::markdown::Markdown;
21 //! let s = "My *markdown* _text_";
22 //! let html = format!("{}", Markdown(s));
23 //! // ... something using html
26 #![allow(non_camel_case_types)]
31 use std::ascii::AsciiExt;
32 use std::cell::RefCell;
33 use std::collections::{HashMap, VecDeque};
34 use std::default::Default;
35 use std::fmt::{self, Write};
37 use syntax::feature_gate::UnstableFeatures;
38 use syntax::codemap::Span;
40 use html::render::derive_id;
41 use html::toc::TocBuilder;
45 use pulldown_cmark::{html, Event, Tag, Parser};
46 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
48 /// A unit struct which has the `fmt::Display` trait implemented. When
49 /// formatted, this struct will emit the HTML corresponding to the rendered
50 /// version of the contained markdown string.
51 // The second parameter is whether we need a shorter version or not.
52 pub struct Markdown<'a>(pub &'a str);
53 /// A unit struct like `Markdown`, that renders the markdown with a
54 /// table of contents.
55 pub struct MarkdownWithToc<'a>(pub &'a str);
56 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
57 pub struct MarkdownHtml<'a>(pub &'a str);
58 /// A unit struct like `Markdown`, that renders only the first paragraph.
59 pub struct MarkdownSummaryLine<'a>(pub &'a str);
61 /// Returns Some(code) if `s` is a line that should be stripped from
62 /// documentation but used in example code. `code` is the portion of
63 /// `s` that should be used in tests. (None for lines that should be
65 fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
66 let trimmed = s.trim();
69 } else if trimmed.starts_with("# ") {
76 /// Convert chars from a title for an id.
78 /// "Hello, world!" -> "hello-world"
79 fn slugify(c: char) -> Option<char> {
80 if c.is_alphanumeric() || c == '-' || c == '_' {
82 Some(c.to_ascii_lowercase())
86 } else if c.is_whitespace() && c.is_ascii() {
93 // Information about the playground if a URL has been specified, containing an
94 // optional crate name and the URL.
95 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
99 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
100 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
104 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
105 fn new(iter: I) -> Self {
112 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
113 type Item = Event<'a>;
115 fn next(&mut self) -> Option<Self::Item> {
116 let event = self.inner.next();
117 if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
118 if !LangString::parse(&lang).rust {
119 return Some(Event::Start(Tag::CodeBlock(lang)));
125 let mut origtext = String::new();
126 for event in &mut self.inner {
128 Event::End(Tag::CodeBlock(..)) => break,
129 Event::Text(ref s) => {
130 origtext.push_str(s);
135 let lines = origtext.lines().filter(|l| {
136 stripped_filtered_line(*l).is_none()
138 let text = lines.collect::<Vec<&str>>().join("\n");
139 PLAYGROUND.with(|play| {
140 // insert newline to clearly separate it from the
141 // previous block so we can shorten the html output
142 let mut s = String::from("\n");
143 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
147 let test = origtext.lines().map(|l| {
148 stripped_filtered_line(l).unwrap_or(l)
149 }).collect::<Vec<&str>>().join("\n");
150 let krate = krate.as_ref().map(|s| &**s);
151 let test = test::maketest(&test, krate, false,
152 &Default::default());
153 let channel = if test.contains("#![feature(") {
154 "&version=nightly"
158 // These characters don't need to be escaped in a URI.
159 // FIXME: use a library function for percent encoding.
160 fn dont_escape(c: u8) -> bool {
161 (b'a' <= c && c <= b'z') ||
162 (b'A' <= c && c <= b'Z') ||
163 (b'0' <= c && c <= b'9') ||
164 c == b'-' || c == b'_' || c == b'.' ||
165 c == b'~' || c == b'!' || c == b'\'' ||
166 c == b'(' || c == b')' || c == b'*'
168 let mut test_escaped = String::new();
169 for b in test.bytes() {
171 test_escaped.push(char::from(b));
173 write!(test_escaped, "%{:02X}", b).unwrap();
177 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
178 url, test_escaped, channel
181 s.push_str(&highlight::render_with_highlighting(
183 Some("rust-example-rendered"),
185 playground_button.as_ref().map(String::as_str)));
186 Some(Event::Html(s.into()))
191 /// Make headings links with anchor ids and build up TOC.
192 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
194 toc: Option<&'b mut TocBuilder>,
195 buf: VecDeque<Event<'a>>,
198 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
199 fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
203 buf: VecDeque::new(),
208 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
209 type Item = Event<'a>;
211 fn next(&mut self) -> Option<Self::Item> {
212 if let Some(e) = self.buf.pop_front() {
216 let event = self.inner.next();
217 if let Some(Event::Start(Tag::Header(level))) = event {
218 let mut id = String::new();
219 for event in &mut self.inner {
221 Event::End(Tag::Header(..)) => break,
222 Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
225 self.buf.push_back(event);
227 let id = derive_id(id);
229 if let Some(ref mut builder) = self.toc {
230 let mut html_header = String::new();
231 html::push_html(&mut html_header, self.buf.iter().cloned());
232 let sec = builder.push(level as u32, html_header, id.clone());
233 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
236 self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
238 let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
242 return Some(Event::InlineHtml(start_tags.into()));
248 /// Extracts just the first paragraph.
249 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
255 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
256 fn new(iter: I) -> Self {
265 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
266 type Item = Event<'a>;
268 fn next(&mut self) -> Option<Self::Item> {
269 if self.started && self.depth == 0 {
275 let event = self.inner.next();
277 Some(Event::Start(..)) => self.depth += 1,
278 Some(Event::End(..)) => self.depth -= 1,
285 /// Moves all footnote definitions to the end and add back links to the
287 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
289 footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
292 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
293 fn new(iter: I) -> Self {
296 footnotes: HashMap::new(),
299 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
300 let new_id = self.footnotes.keys().count() + 1;
301 let key = key.to_owned();
302 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
306 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
307 type Item = Event<'a>;
309 fn next(&mut self) -> Option<Self::Item> {
311 match self.inner.next() {
312 Some(Event::FootnoteReference(ref reference)) => {
313 let entry = self.get_entry(&reference);
314 let reference = format!("<sup id=\"supref{0}\"><a href=\"#ref{0}\">{0}\
317 return Some(Event::Html(reference.into()));
319 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
320 let mut content = Vec::new();
321 for event in &mut self.inner {
322 if let Event::End(Tag::FootnoteDefinition(..)) = event {
327 let entry = self.get_entry(&def);
328 (*entry).0 = content;
330 Some(e) => return Some(e),
332 if !self.footnotes.is_empty() {
333 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
334 v.sort_by(|a, b| a.1.cmp(&b.1));
335 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
336 for (mut content, id) in v {
337 write!(ret, "<li id=\"ref{}\">", id).unwrap();
338 let mut is_paragraph = false;
339 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
343 html::push_html(&mut ret, content.into_iter());
345 " <a href=\"#supref{}\" rev=\"footnote\">↩</a>",
348 ret.push_str("</p>");
350 ret.push_str("</li>");
352 ret.push_str("</ol></div>");
353 return Some(Event::Html(ret.into()));
363 const DEF_OUNIT: libc::size_t = 64;
364 const HOEDOWN_EXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 11;
365 const HOEDOWN_EXT_TABLES: libc::c_uint = 1 << 0;
366 const HOEDOWN_EXT_FENCED_CODE: libc::c_uint = 1 << 1;
367 const HOEDOWN_EXT_AUTOLINK: libc::c_uint = 1 << 3;
368 const HOEDOWN_EXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
369 const HOEDOWN_EXT_SUPERSCRIPT: libc::c_uint = 1 << 8;
370 const HOEDOWN_EXT_FOOTNOTES: libc::c_uint = 1 << 2;
372 const HOEDOWN_EXTENSIONS: libc::c_uint =
373 HOEDOWN_EXT_NO_INTRA_EMPHASIS | HOEDOWN_EXT_TABLES |
374 HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_AUTOLINK |
375 HOEDOWN_EXT_STRIKETHROUGH | HOEDOWN_EXT_SUPERSCRIPT |
376 HOEDOWN_EXT_FOOTNOTES;
378 enum hoedown_document {}
380 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
381 *const hoedown_buffer, *const hoedown_renderer_data,
384 type blockquotefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
385 *const hoedown_renderer_data, libc::size_t);
387 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
388 libc::c_int, *const hoedown_renderer_data,
391 type blockhtmlfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
392 *const hoedown_renderer_data, libc::size_t);
394 type codespanfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
395 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
397 type linkfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
398 *const hoedown_buffer, *const hoedown_buffer,
399 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
401 type entityfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
402 *const hoedown_renderer_data, libc::size_t);
404 type normaltextfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
405 *const hoedown_renderer_data, libc::size_t);
408 struct hoedown_renderer_data {
409 opaque: *mut libc::c_void,
413 struct hoedown_renderer {
414 opaque: *mut libc::c_void,
416 blockcode: Option<blockcodefn>,
417 blockquote: Option<blockquotefn>,
418 header: Option<headerfn>,
420 other_block_level_callbacks: [libc::size_t; 11],
422 blockhtml: Option<blockhtmlfn>,
424 /* span level callbacks - NULL or return 0 prints the span verbatim */
425 autolink: libc::size_t, // unused
426 codespan: Option<codespanfn>,
427 other_span_level_callbacks_1: [libc::size_t; 7],
428 link: Option<linkfn>,
429 other_span_level_callbacks_2: [libc::size_t; 6],
431 /* low level callbacks - NULL copies input directly into the output */
432 entity: Option<entityfn>,
433 normal_text: Option<normaltextfn>,
435 /* header and footer */
436 other_callbacks: [libc::size_t; 2],
440 struct hoedown_html_renderer_state {
441 opaque: *mut libc::c_void,
442 toc_data: html_toc_data,
444 link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
445 *const hoedown_buffer,
446 *const hoedown_renderer_data)>,
450 struct html_toc_data {
451 header_count: libc::c_int,
452 current_level: libc::c_int,
453 level_offset: libc::c_int,
454 nesting_level: libc::c_int,
458 struct hoedown_buffer {
466 fn hoedown_html_renderer_new(render_flags: libc::c_uint,
467 nesting_level: libc::c_int)
468 -> *mut hoedown_renderer;
469 fn hoedown_html_renderer_free(renderer: *mut hoedown_renderer);
471 fn hoedown_document_new(rndr: *const hoedown_renderer,
472 extensions: libc::c_uint,
473 max_nesting: libc::size_t) -> *mut hoedown_document;
474 fn hoedown_document_render(doc: *mut hoedown_document,
475 ob: *mut hoedown_buffer,
477 doc_size: libc::size_t);
478 fn hoedown_document_free(md: *mut hoedown_document);
480 fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer;
481 fn hoedown_buffer_free(b: *mut hoedown_buffer);
484 impl hoedown_buffer {
485 fn as_bytes(&self) -> &[u8] {
486 unsafe { slice::from_raw_parts(self.data, self.size as usize) }
490 pub fn old_find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
491 extern fn block(_ob: *mut hoedown_buffer,
492 text: *const hoedown_buffer,
493 lang: *const hoedown_buffer,
494 data: *const hoedown_renderer_data,
495 line: libc::size_t) {
497 if text.is_null() { return }
498 let block_info = if lang.is_null() {
499 LangString::all_false()
501 let lang = (*lang).as_bytes();
502 let s = str::from_utf8(lang).unwrap();
505 if !block_info.rust { return }
506 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
507 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
508 let line = tests.get_line() + line;
509 let filename = tests.get_filename();
510 tests.add_old_test(line, filename);
514 extern fn header(_ob: *mut hoedown_buffer,
515 text: *const hoedown_buffer,
516 level: libc::c_int, data: *const hoedown_renderer_data,
519 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
520 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
522 tests.register_header("", level as u32);
524 let text = (*text).as_bytes();
525 let text = str::from_utf8(text).unwrap();
526 tests.register_header(text, level as u32);
531 tests.set_position(position);
534 let ob = hoedown_buffer_new(DEF_OUNIT);
535 let renderer = hoedown_html_renderer_new(0, 0);
536 (*renderer).blockcode = Some(block);
537 (*renderer).header = Some(header);
538 (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
539 = tests as *mut _ as *mut libc::c_void;
541 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
542 hoedown_document_render(document, ob, doc.as_ptr(),
543 doc.len() as libc::size_t);
544 hoedown_document_free(document);
546 hoedown_html_renderer_free(renderer);
547 hoedown_buffer_free(ob);
551 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
552 tests.set_position(position);
554 let mut parser = Parser::new(doc);
555 let mut prev_offset = 0;
556 let mut nb_lines = 0;
557 let mut register_header = None;
558 'main: while let Some(event) = parser.next() {
560 Event::Start(Tag::CodeBlock(s)) => {
561 let block_info = if s.is_empty() {
562 LangString::all_false()
564 LangString::parse(&*s)
566 if !block_info.rust {
569 let mut test_s = String::new();
570 let mut offset = None;
572 let event = parser.next();
573 if let Some(event) = event {
575 Event::End(Tag::CodeBlock(_)) => break,
576 Event::Text(ref s) => {
578 if offset.is_none() {
579 offset = Some(parser.get_offset());
588 let offset = offset.unwrap_or(0);
589 let lines = test_s.lines().map(|l| {
590 stripped_filtered_line(l).unwrap_or(l)
592 let text = lines.collect::<Vec<&str>>().join("\n");
593 nb_lines += doc[prev_offset..offset].lines().count();
594 let line = tests.get_line() + (nb_lines - 1);
595 let filename = tests.get_filename();
596 tests.add_test(text.to_owned(),
597 block_info.should_panic, block_info.no_run,
598 block_info.ignore, block_info.test_harness,
599 block_info.compile_fail, block_info.error_codes,
601 prev_offset = offset;
603 Event::Start(Tag::Header(level)) => {
604 register_header = Some(level as u32);
606 Event::Text(ref s) if register_header.is_some() => {
607 let level = register_header.unwrap();
609 tests.register_header("", level);
611 tests.register_header(s, level);
613 register_header = None;
620 #[derive(Eq, PartialEq, Clone, Debug)]
629 error_codes: Vec<String>,
633 fn all_false() -> LangString {
635 original: String::new(),
639 rust: true, // NB This used to be `notrust = false`
642 error_codes: Vec::new(),
646 fn parse(string: &str) -> LangString {
647 let mut seen_rust_tags = false;
648 let mut seen_other_tags = false;
649 let mut data = LangString::all_false();
650 let mut allow_compile_fail = false;
651 let mut allow_error_code_check = false;
652 if UnstableFeatures::from_environment().is_nightly_build() {
653 allow_compile_fail = true;
654 allow_error_code_check = true;
657 data.original = string.to_owned();
658 let tokens = string.split(|c: char|
659 !(c == '_' || c == '-' || c.is_alphanumeric())
662 for token in tokens {
666 data.should_panic = true;
667 seen_rust_tags = seen_other_tags == false;
669 "no_run" => { data.no_run = true; seen_rust_tags = !seen_other_tags; }
670 "ignore" => { data.ignore = true; seen_rust_tags = !seen_other_tags; }
671 "rust" => { data.rust = true; seen_rust_tags = true; }
673 data.test_harness = true;
674 seen_rust_tags = !seen_other_tags || seen_rust_tags;
676 "compile_fail" if allow_compile_fail => {
677 data.compile_fail = true;
678 seen_rust_tags = !seen_other_tags || seen_rust_tags;
681 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
682 if let Ok(_) = x[1..].parse::<u32>() {
683 data.error_codes.push(x.to_owned());
684 seen_rust_tags = !seen_other_tags || seen_rust_tags;
686 seen_other_tags = true;
689 _ => { seen_other_tags = true }
693 data.rust &= !seen_other_tags || seen_rust_tags;
699 impl<'a> fmt::Display for Markdown<'a> {
700 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
701 let Markdown(md) = *self;
702 // This is actually common enough to special-case
703 if md.is_empty() { return Ok(()) }
705 let mut opts = Options::empty();
706 opts.insert(OPTION_ENABLE_TABLES);
707 opts.insert(OPTION_ENABLE_FOOTNOTES);
709 let p = Parser::new_ext(md, opts);
711 let mut s = String::with_capacity(md.len() * 3 / 2);
713 html::push_html(&mut s,
714 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
720 impl<'a> fmt::Display for MarkdownWithToc<'a> {
721 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
722 let MarkdownWithToc(md) = *self;
724 let mut opts = Options::empty();
725 opts.insert(OPTION_ENABLE_TABLES);
726 opts.insert(OPTION_ENABLE_FOOTNOTES);
728 let p = Parser::new_ext(md, opts);
730 let mut s = String::with_capacity(md.len() * 3 / 2);
732 let mut toc = TocBuilder::new();
734 html::push_html(&mut s,
735 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, Some(&mut toc)))));
737 write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
743 impl<'a> fmt::Display for MarkdownHtml<'a> {
744 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
745 let MarkdownHtml(md) = *self;
746 // This is actually common enough to special-case
747 if md.is_empty() { return Ok(()) }
749 let mut opts = Options::empty();
750 opts.insert(OPTION_ENABLE_TABLES);
751 opts.insert(OPTION_ENABLE_FOOTNOTES);
753 let p = Parser::new_ext(md, opts);
755 // Treat inline HTML as plain text.
756 let p = p.map(|event| match event {
757 Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
761 let mut s = String::with_capacity(md.len() * 3 / 2);
763 html::push_html(&mut s,
764 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
770 impl<'a> fmt::Display for MarkdownSummaryLine<'a> {
771 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
772 let MarkdownSummaryLine(md) = *self;
773 // This is actually common enough to special-case
774 if md.is_empty() { return Ok(()) }
776 let p = Parser::new(md);
778 let mut s = String::new();
780 html::push_html(&mut s, SummaryLine::new(p));
786 pub fn plain_summary_line(md: &str) -> String {
787 struct ParserWrapper<'a> {
793 impl<'a> Iterator for ParserWrapper<'a> {
796 fn next(&mut self) -> Option<String> {
797 let next_event = self.inner.next();
798 if next_event.is_none() {
801 let next_event = next_event.unwrap();
802 let (ret, is_in) = match next_event {
803 Event::Start(Tag::Paragraph) => (None, 1),
804 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
805 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
806 Event::Start(Tag::Header(_)) => (None, 1),
807 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
808 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
811 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
815 self.is_first = false;
822 let mut s = String::with_capacity(md.len() * 3 / 2);
823 let mut p = ParserWrapper {
824 inner: Parser::new(md),
828 while let Some(t) = p.next() {
838 use super::{LangString, Markdown, MarkdownHtml};
839 use super::plain_summary_line;
840 use html::render::reset_ids;
843 fn test_lang_string_parse() {
845 should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
846 compile_fail: bool, error_codes: Vec<String>) {
847 assert_eq!(LangString::parse(s), LangString {
848 should_panic: should_panic,
852 test_harness: test_harness,
853 compile_fail: compile_fail,
854 error_codes: error_codes,
855 original: s.to_owned(),
859 // marker | should_panic| no_run| ignore| rust | test_harness| compile_fail
861 t("", false, false, false, true, false, false, Vec::new());
862 t("rust", false, false, false, true, false, false, Vec::new());
863 t("sh", false, false, false, false, false, false, Vec::new());
864 t("ignore", false, false, true, true, false, false, Vec::new());
865 t("should_panic", true, false, false, true, false, false, Vec::new());
866 t("no_run", false, true, false, true, false, false, Vec::new());
867 t("test_harness", false, false, false, true, true, false, Vec::new());
868 t("compile_fail", false, true, false, true, false, true, Vec::new());
869 t("{.no_run .example}", false, true, false, true, false, false, Vec::new());
870 t("{.sh .should_panic}", true, false, false, false, false, false, Vec::new());
871 t("{.example .rust}", false, false, false, true, false, false, Vec::new());
872 t("{.test_harness .rust}", false, false, false, true, true, false, Vec::new());
873 t("text, no_run", false, true, false, false, false, false, Vec::new());
874 t("text,no_run", false, true, false, false, false, false, Vec::new());
879 let markdown = "# title";
880 format!("{}", Markdown(markdown));
886 fn t(input: &str, expect: &str) {
887 let output = format!("{}", Markdown(input));
888 assert_eq!(output, expect, "original: {}", input);
892 t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
893 <a href=\"#foo-bar\">Foo bar</a></h1>");
894 t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
895 header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
896 t("### **Foo** *bar* baz!?!& -_qux_-%",
897 "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
898 <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
899 <em>bar</em> baz!?!& -<em>qux</em>-%</a></h3>");
900 t("#### **Foo?** & \\*bar?!* _`baz`_ ❤ #qux",
901 "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
902 <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> & *bar?!* \
903 <em><code>baz</code></em> ❤ #qux</a></h4>");
907 fn test_header_ids_multiple_blocks() {
908 fn t(input: &str, expect: &str) {
909 let output = format!("{}", Markdown(input));
910 assert_eq!(output, expect, "original: {}", input);
914 t("# Example", "<h1 id=\"example\" class=\"section-header\">\
915 <a href=\"#example\">Example</a></h1>");
916 t("# Panics", "<h1 id=\"panics\" class=\"section-header\">\
917 <a href=\"#panics\">Panics</a></h1>");
918 t("# Example", "<h1 id=\"example-1\" class=\"section-header\">\
919 <a href=\"#example-1\">Example</a></h1>");
920 t("# Main", "<h1 id=\"main-1\" class=\"section-header\">\
921 <a href=\"#main-1\">Main</a></h1>");
922 t("# Example", "<h1 id=\"example-2\" class=\"section-header\">\
923 <a href=\"#example-2\">Example</a></h1>");
924 t("# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
925 <a href=\"#panics-1\">Panics</a></h1>");
933 fn test_plain_summary_line() {
934 fn t(input: &str, expect: &str) {
935 let output = plain_summary_line(input);
936 assert_eq!(output, expect, "original: {}", input);
939 t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
940 t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
941 t("code `let x = i32;` ...", "code `let x = i32;` ...");
942 t("type `Type<'static>` ...", "type `Type<'static>` ...");
943 t("# top header", "top header");
944 t("## header", "header");
948 fn test_markdown_html_escape() {
949 fn t(input: &str, expect: &str) {
950 let output = format!("{}", MarkdownHtml(input));
951 assert_eq!(output, expect, "original: {}", input);
954 t("`Struct<'a, T>`", "<p><code>Struct<'a, T></code></p>\n");
955 t("Struct<'a, T>", "<p>Struct<'a, T></p>\n");
956 t("Struct<br>", "<p>Struct<br></p>\n");