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 //! #![feature(rustc_private)]
21 //! use rustdoc::html::markdown::Markdown;
23 //! let s = "My *markdown* _text_";
24 //! let html = format!("{}", Markdown(s));
25 //! // ... something using html
28 #![allow(non_camel_case_types)]
30 use std::cell::RefCell;
31 use std::collections::{HashMap, VecDeque};
32 use std::default::Default;
33 use std::fmt::{self, Write};
35 use syntax::feature_gate::UnstableFeatures;
36 use syntax::codemap::Span;
38 use html::render::derive_id;
39 use html::toc::TocBuilder;
43 use pulldown_cmark::{html, Event, Tag, Parser};
44 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
46 /// A unit struct which has the `fmt::Display` trait implemented. When
47 /// formatted, this struct will emit the HTML corresponding to the rendered
48 /// version of the contained markdown string.
49 /// The second parameter is a list of link replacements
50 pub struct Markdown<'a>(pub &'a str, pub &'a [(String, String)]);
51 /// A unit struct like `Markdown`, that renders the markdown with a
52 /// table of contents.
53 pub struct MarkdownWithToc<'a>(pub &'a str);
54 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
55 pub struct MarkdownHtml<'a>(pub &'a str);
56 /// A unit struct like `Markdown`, that renders only the first paragraph.
57 pub struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [(String, String)]);
59 /// Controls whether a line will be hidden or shown in HTML output.
61 /// All lines are used in documentation tests.
68 fn for_html(self) -> Option<&'a str> {
70 Line::Shown(l) => Some(l),
71 Line::Hidden(_) => None,
75 fn for_code(self) -> &'a str {
83 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
84 // have no easy way of removing a potential single space after the hashes, which
85 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
86 // order to fix it we'd have to iterate to find the first non-# character, and
87 // then reallocate to remove it; which would make us return a String.
88 fn map_line(s: &str) -> Line {
89 let trimmed = s.trim();
90 if trimmed.starts_with("##") {
91 Line::Shown(&trimmed[1..])
92 } else if trimmed.starts_with("# ") {
94 Line::Hidden(&trimmed[2..])
95 } else if trimmed == "#" {
96 // We cannot handle '#text' because it could be #[attr].
103 /// Convert chars from a title for an id.
105 /// "Hello, world!" -> "hello-world"
106 fn slugify(c: char) -> Option<char> {
107 if c.is_alphanumeric() || c == '-' || c == '_' {
109 Some(c.to_ascii_lowercase())
113 } else if c.is_whitespace() && c.is_ascii() {
120 // Information about the playground if a URL has been specified, containing an
121 // optional crate name and the URL.
122 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
126 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
127 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
131 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
132 fn new(iter: I) -> Self {
139 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
140 type Item = Event<'a>;
142 fn next(&mut self) -> Option<Self::Item> {
143 let event = self.inner.next();
146 if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
147 let parse_result = LangString::parse(&lang);
148 if !parse_result.rust {
149 return Some(Event::Start(Tag::CodeBlock(lang)));
151 compile_fail = parse_result.compile_fail;
152 ignore = parse_result.ignore;
157 let mut origtext = String::new();
158 for event in &mut self.inner {
160 Event::End(Tag::CodeBlock(..)) => break,
161 Event::Text(ref s) => {
162 origtext.push_str(s);
167 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
168 let text = lines.collect::<Vec<&str>>().join("\n");
169 PLAYGROUND.with(|play| {
170 // insert newline to clearly separate it from the
171 // previous block so we can shorten the html output
172 let mut s = String::from("\n");
173 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
177 let test = origtext.lines()
178 .map(|l| map_line(l).for_code())
179 .collect::<Vec<&str>>().join("\n");
180 let krate = krate.as_ref().map(|s| &**s);
181 let (test, _) = test::make_test(&test, krate, false,
182 &Default::default());
183 let channel = if test.contains("#![feature(") {
184 "&version=nightly"
188 // These characters don't need to be escaped in a URI.
189 // FIXME: use a library function for percent encoding.
190 fn dont_escape(c: u8) -> bool {
191 (b'a' <= c && c <= b'z') ||
192 (b'A' <= c && c <= b'Z') ||
193 (b'0' <= c && c <= b'9') ||
194 c == b'-' || c == b'_' || c == b'.' ||
195 c == b'~' || c == b'!' || c == b'\'' ||
196 c == b'(' || c == b')' || c == b'*'
198 let mut test_escaped = String::new();
199 for b in test.bytes() {
201 test_escaped.push(char::from(b));
203 write!(test_escaped, "%{:02X}", b).unwrap();
207 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
208 url, test_escaped, channel
211 let tooltip = if ignore {
212 Some(("This example is not tested", "ignore"))
213 } else if compile_fail {
214 Some(("This example deliberately fails to compile", "compile_fail"))
218 s.push_str(&highlight::render_with_highlighting(
220 Some(&format!("rust-example-rendered{}",
221 if ignore { " ignore" }
222 else if compile_fail { " compile_fail" }
225 playground_button.as_ref().map(String::as_str),
227 Some(Event::Html(s.into()))
232 /// Make headings links with anchor ids and build up TOC.
233 struct LinkReplacer<'a, 'b, I: Iterator<Item = Event<'a>>> {
235 links: &'b [(String, String)]
238 impl<'a, 'b, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, 'b, I> {
239 fn new(iter: I, links: &'b [(String, String)]) -> Self {
247 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, 'b, I> {
248 type Item = Event<'a>;
250 fn next(&mut self) -> Option<Self::Item> {
251 let event = self.inner.next();
252 if let Some(Event::Start(Tag::Link(dest, text))) = event {
253 if let Some(&(_, ref replace)) = self.links.into_iter().find(|link| &*link.0 == &*dest)
255 Some(Event::Start(Tag::Link(replace.to_owned().into(), text)))
257 Some(Event::Start(Tag::Link(dest, text)))
265 /// Make headings links with anchor ids and build up TOC.
266 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
268 toc: Option<&'b mut TocBuilder>,
269 buf: VecDeque<Event<'a>>,
272 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
273 fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
277 buf: VecDeque::new(),
282 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
283 type Item = Event<'a>;
285 fn next(&mut self) -> Option<Self::Item> {
286 if let Some(e) = self.buf.pop_front() {
290 let event = self.inner.next();
291 if let Some(Event::Start(Tag::Header(level))) = event {
292 let mut id = String::new();
293 for event in &mut self.inner {
295 Event::End(Tag::Header(..)) => break,
296 Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
299 self.buf.push_back(event);
301 let id = derive_id(id);
303 if let Some(ref mut builder) = self.toc {
304 let mut html_header = String::new();
305 html::push_html(&mut html_header, self.buf.iter().cloned());
306 let sec = builder.push(level as u32, html_header, id.clone());
307 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
310 self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
312 let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
316 return Some(Event::InlineHtml(start_tags.into()));
322 /// Extracts just the first paragraph.
323 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
329 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
330 fn new(iter: I) -> Self {
339 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
340 type Item = Event<'a>;
342 fn next(&mut self) -> Option<Self::Item> {
343 if self.started && self.depth == 0 {
349 let event = self.inner.next();
351 Some(Event::Start(..)) => self.depth += 1,
352 Some(Event::End(..)) => self.depth -= 1,
359 /// Moves all footnote definitions to the end and add back links to the
361 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
363 footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
366 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
367 fn new(iter: I) -> Self {
370 footnotes: HashMap::new(),
373 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
374 let new_id = self.footnotes.keys().count() + 1;
375 let key = key.to_owned();
376 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
380 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
381 type Item = Event<'a>;
383 fn next(&mut self) -> Option<Self::Item> {
385 match self.inner.next() {
386 Some(Event::FootnoteReference(ref reference)) => {
387 let entry = self.get_entry(&reference);
388 let reference = format!("<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}\
391 return Some(Event::Html(reference.into()));
393 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
394 let mut content = Vec::new();
395 for event in &mut self.inner {
396 if let Event::End(Tag::FootnoteDefinition(..)) = event {
401 let entry = self.get_entry(&def);
402 (*entry).0 = content;
404 Some(e) => return Some(e),
406 if !self.footnotes.is_empty() {
407 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
408 v.sort_by(|a, b| a.1.cmp(&b.1));
409 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
410 for (mut content, id) in v {
411 write!(ret, "<li id=\"fn{}\">", id).unwrap();
412 let mut is_paragraph = false;
413 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
417 html::push_html(&mut ret, content.into_iter());
419 " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>",
422 ret.push_str("</p>");
424 ret.push_str("</li>");
426 ret.push_str("</ol></div>");
427 return Some(Event::Html(ret.into()));
437 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
438 tests.set_position(position);
440 let mut parser = Parser::new(doc);
441 let mut prev_offset = 0;
442 let mut nb_lines = 0;
443 let mut register_header = None;
444 'main: while let Some(event) = parser.next() {
446 Event::Start(Tag::CodeBlock(s)) => {
447 let block_info = if s.is_empty() {
448 LangString::all_false()
450 LangString::parse(&*s)
452 if !block_info.rust {
455 let mut test_s = String::new();
456 let mut offset = None;
458 let event = parser.next();
459 if let Some(event) = event {
461 Event::End(Tag::CodeBlock(_)) => break,
462 Event::Text(ref s) => {
464 if offset.is_none() {
465 offset = Some(parser.get_offset());
474 if let Some(offset) = offset {
475 let lines = test_s.lines().map(|l| map_line(l).for_code());
476 let text = lines.collect::<Vec<&str>>().join("\n");
477 nb_lines += doc[prev_offset..offset].lines().count();
478 let line = tests.get_line() + (nb_lines - 1);
479 let filename = tests.get_filename();
480 tests.add_test(text.to_owned(),
481 block_info.should_panic, block_info.no_run,
482 block_info.ignore, block_info.test_harness,
483 block_info.compile_fail, block_info.error_codes,
484 line, filename, block_info.allow_fail);
485 prev_offset = offset;
490 Event::Start(Tag::Header(level)) => {
491 register_header = Some(level as u32);
493 Event::Text(ref s) if register_header.is_some() => {
494 let level = register_header.unwrap();
496 tests.register_header("", level);
498 tests.register_header(s, level);
500 register_header = None;
507 #[derive(Eq, PartialEq, Clone, Debug)]
516 error_codes: Vec<String>,
521 fn all_false() -> LangString {
523 original: String::new(),
527 rust: true, // NB This used to be `notrust = false`
530 error_codes: Vec::new(),
535 fn parse(string: &str) -> LangString {
536 let mut seen_rust_tags = false;
537 let mut seen_other_tags = false;
538 let mut data = LangString::all_false();
539 let mut allow_error_code_check = false;
540 if UnstableFeatures::from_environment().is_nightly_build() {
541 allow_error_code_check = true;
544 data.original = string.to_owned();
545 let tokens = string.split(|c: char|
546 !(c == '_' || c == '-' || c.is_alphanumeric())
549 for token in tokens {
553 data.should_panic = true;
554 seen_rust_tags = seen_other_tags == false;
556 "no_run" => { data.no_run = true; seen_rust_tags = !seen_other_tags; }
557 "ignore" => { data.ignore = true; seen_rust_tags = !seen_other_tags; }
558 "allow_fail" => { data.allow_fail = true; seen_rust_tags = !seen_other_tags; }
559 "rust" => { data.rust = true; seen_rust_tags = true; }
561 data.test_harness = true;
562 seen_rust_tags = !seen_other_tags || seen_rust_tags;
565 data.compile_fail = true;
566 seen_rust_tags = !seen_other_tags || seen_rust_tags;
569 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
570 if let Ok(_) = x[1..].parse::<u32>() {
571 data.error_codes.push(x.to_owned());
572 seen_rust_tags = !seen_other_tags || seen_rust_tags;
574 seen_other_tags = true;
577 _ => { seen_other_tags = true }
581 data.rust &= !seen_other_tags || seen_rust_tags;
587 impl<'a> fmt::Display for Markdown<'a> {
588 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
589 let Markdown(md, links) = *self;
591 // This is actually common enough to special-case
592 if md.is_empty() { return Ok(()) }
593 let mut opts = Options::empty();
594 opts.insert(OPTION_ENABLE_TABLES);
595 opts.insert(OPTION_ENABLE_FOOTNOTES);
597 let replacer = |_: &str, s: &str| {
598 if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
599 Some((replace.clone(), s.to_owned()))
605 let p = Parser::new_with_broken_link_callback(md, opts, Some(&replacer));
607 let mut s = String::with_capacity(md.len() * 3 / 2);
609 html::push_html(&mut s,
613 HeadingLinks::new(p, None),
620 impl<'a> fmt::Display for MarkdownWithToc<'a> {
621 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
622 let MarkdownWithToc(md) = *self;
624 let mut opts = Options::empty();
625 opts.insert(OPTION_ENABLE_TABLES);
626 opts.insert(OPTION_ENABLE_FOOTNOTES);
628 let p = Parser::new_ext(md, opts);
630 let mut s = String::with_capacity(md.len() * 3 / 2);
632 let mut toc = TocBuilder::new();
634 html::push_html(&mut s,
635 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, Some(&mut toc)))));
637 write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
643 impl<'a> fmt::Display for MarkdownHtml<'a> {
644 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
645 let MarkdownHtml(md) = *self;
647 // This is actually common enough to special-case
648 if md.is_empty() { return Ok(()) }
649 let mut opts = Options::empty();
650 opts.insert(OPTION_ENABLE_TABLES);
651 opts.insert(OPTION_ENABLE_FOOTNOTES);
653 let p = Parser::new_ext(md, opts);
655 // Treat inline HTML as plain text.
656 let p = p.map(|event| match event {
657 Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
661 let mut s = String::with_capacity(md.len() * 3 / 2);
663 html::push_html(&mut s,
664 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
670 impl<'a> fmt::Display for MarkdownSummaryLine<'a> {
671 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
672 let MarkdownSummaryLine(md, links) = *self;
673 // This is actually common enough to special-case
674 if md.is_empty() { return Ok(()) }
676 let replacer = |_: &str, s: &str| {
677 if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
678 Some((replace.clone(), s.to_owned()))
684 let p = Parser::new_with_broken_link_callback(md, Options::empty(),
687 let mut s = String::new();
689 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
695 pub fn plain_summary_line(md: &str) -> String {
696 struct ParserWrapper<'a> {
702 impl<'a> Iterator for ParserWrapper<'a> {
705 fn next(&mut self) -> Option<String> {
706 let next_event = self.inner.next();
707 if next_event.is_none() {
710 let next_event = next_event.unwrap();
711 let (ret, is_in) = match next_event {
712 Event::Start(Tag::Paragraph) => (None, 1),
713 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
714 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
715 Event::Start(Tag::Header(_)) => (None, 1),
716 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
717 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
720 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
724 self.is_first = false;
731 let mut s = String::with_capacity(md.len() * 3 / 2);
732 let mut p = ParserWrapper {
733 inner: Parser::new(md),
737 while let Some(t) = p.next() {
745 pub fn markdown_links(md: &str) -> Vec<String> {
750 let mut opts = Options::empty();
751 opts.insert(OPTION_ENABLE_TABLES);
752 opts.insert(OPTION_ENABLE_FOOTNOTES);
754 let mut links = vec![];
755 let shortcut_links = RefCell::new(vec![]);
758 let push = |_: &str, s: &str| {
759 shortcut_links.borrow_mut().push(s.to_owned());
762 let p = Parser::new_with_broken_link_callback(md, opts,
765 let iter = Footnotes::new(HeadingLinks::new(p, None));
768 if let Event::Start(Tag::Link(dest, _)) = ev {
769 debug!("found link: {}", dest);
770 links.push(dest.into_owned());
775 let mut shortcut_links = shortcut_links.into_inner();
776 links.extend(shortcut_links.drain(..));
783 use super::{LangString, Markdown, MarkdownHtml};
784 use super::plain_summary_line;
785 use html::render::reset_ids;
788 fn test_lang_string_parse() {
790 should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
791 compile_fail: bool, allow_fail: bool, error_codes: Vec<String>) {
792 assert_eq!(LangString::parse(s), LangString {
800 original: s.to_owned(),
805 fn v() -> Vec<String> {
809 // marker | should_panic| no_run| ignore| rust | test_harness| compile_fail
810 // | allow_fail | error_codes
811 t("", false, false, false, true, false, false, false, v());
812 t("rust", false, false, false, true, false, false, false, v());
813 t("sh", false, false, false, false, false, false, false, v());
814 t("ignore", false, false, true, true, false, false, false, v());
815 t("should_panic", true, false, false, true, false, false, false, v());
816 t("no_run", false, true, false, true, false, false, false, v());
817 t("test_harness", false, false, false, true, true, false, false, v());
818 t("compile_fail", false, true, false, true, false, true, false, v());
819 t("allow_fail", false, false, false, true, false, false, true, v());
820 t("{.no_run .example}", false, true, false, true, false, false, false, v());
821 t("{.sh .should_panic}", true, false, false, false, false, false, false, v());
822 t("{.example .rust}", false, false, false, true, false, false, false, v());
823 t("{.test_harness .rust}", false, false, false, true, true, false, false, v());
824 t("text, no_run", false, true, false, false, false, false, false, v());
825 t("text,no_run", false, true, false, false, false, false, false, v());
830 let markdown = "# title";
831 format!("{}", Markdown(markdown, &[]));
837 fn t(input: &str, expect: &str) {
838 let output = format!("{}", Markdown(input, &[]));
839 assert_eq!(output, expect, "original: {}", input);
843 t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
844 <a href=\"#foo-bar\">Foo bar</a></h1>");
845 t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
846 header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
847 t("### **Foo** *bar* baz!?!& -_qux_-%",
848 "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
849 <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
850 <em>bar</em> baz!?!& -<em>qux</em>-%</a></h3>");
851 t("#### **Foo?** & \\*bar?!* _`baz`_ ❤ #qux",
852 "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
853 <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> & *bar?!* \
854 <em><code>baz</code></em> ❤ #qux</a></h4>");
858 fn test_header_ids_multiple_blocks() {
859 fn t(input: &str, expect: &str) {
860 let output = format!("{}", Markdown(input, &[]));
861 assert_eq!(output, expect, "original: {}", input);
865 t("# Example", "<h1 id=\"example\" class=\"section-header\">\
866 <a href=\"#example\">Example</a></h1>");
867 t("# Panics", "<h1 id=\"panics\" class=\"section-header\">\
868 <a href=\"#panics\">Panics</a></h1>");
869 t("# Example", "<h1 id=\"example-1\" class=\"section-header\">\
870 <a href=\"#example-1\">Example</a></h1>");
871 t("# Main", "<h1 id=\"main-1\" class=\"section-header\">\
872 <a href=\"#main-1\">Main</a></h1>");
873 t("# Example", "<h1 id=\"example-2\" class=\"section-header\">\
874 <a href=\"#example-2\">Example</a></h1>");
875 t("# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
876 <a href=\"#panics-1\">Panics</a></h1>");
884 fn test_plain_summary_line() {
885 fn t(input: &str, expect: &str) {
886 let output = plain_summary_line(input);
887 assert_eq!(output, expect, "original: {}", input);
890 t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
891 t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
892 t("code `let x = i32;` ...", "code `let x = i32;` ...");
893 t("type `Type<'static>` ...", "type `Type<'static>` ...");
894 t("# top header", "top header");
895 t("## header", "header");
899 fn test_markdown_html_escape() {
900 fn t(input: &str, expect: &str) {
901 let output = format!("{}", MarkdownHtml(input));
902 assert_eq!(output, expect, "original: {}", input);
905 t("`Struct<'a, T>`", "<p><code>Struct<'a, T></code></p>\n");
906 t("Struct<'a, T>", "<p>Struct<'a, T></p>\n");
907 t("Struct<br>", "<p>Struct<br></p>\n");