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, MarkdownOutputStyle};
21 //! let s = "My *markdown* _text_";
22 //! let html = format!("{}", Markdown(s, MarkdownOutputStyle::Fancy));
23 //! // ... something using html
26 #![allow(non_camel_case_types)]
28 use std::ascii::AsciiExt;
29 use std::cell::RefCell;
30 use std::default::Default;
31 use std::fmt::{self, Write};
33 use syntax::feature_gate::UnstableFeatures;
34 use syntax::codemap::Span;
36 use html::render::derive_id;
37 use html::toc::TocBuilder;
39 use html::escape::Escape;
42 use pulldown_cmark::{self, Event, Parser, Tag};
44 #[derive(Copy, Clone)]
45 pub enum MarkdownOutputStyle {
50 impl MarkdownOutputStyle {
51 pub fn is_compact(&self) -> bool {
53 MarkdownOutputStyle::Compact => true,
58 pub fn is_fancy(&self) -> bool {
60 MarkdownOutputStyle::Fancy => true,
66 /// A unit struct which has the `fmt::Display` trait implemented. When
67 /// formatted, this struct will emit the HTML corresponding to the rendered
68 /// version of the contained markdown string.
69 // The second parameter is whether we need a shorter version or not.
70 pub struct Markdown<'a>(pub &'a str, pub MarkdownOutputStyle);
71 /// A unit struct like `Markdown`, that renders the markdown with a
72 /// table of contents.
73 pub struct MarkdownWithToc<'a>(pub &'a str);
74 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
75 pub struct MarkdownHtml<'a>(pub &'a str);
77 /// Returns Some(code) if `s` is a line that should be stripped from
78 /// documentation but used in example code. `code` is the portion of
79 /// `s` that should be used in tests. (None for lines that should be
81 fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
82 let trimmed = s.trim();
85 } else if trimmed.starts_with("# ") {
92 /// Returns a new string with all consecutive whitespace collapsed into
95 /// Any leading or trailing whitespace will be trimmed.
96 fn collapse_whitespace(s: &str) -> String {
97 s.split_whitespace().collect::<Vec<_>>().join(" ")
100 // Information about the playground if a URL has been specified, containing an
101 // optional crate name and the URL.
102 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
106 macro_rules! event_loop_break {
107 ($parser:expr, $toc_builder:expr, $shorter:expr, $buf:expr, $escape:expr, $id:expr,
108 $($end_event:pat)|*) => {{
109 fn inner(id: &mut Option<&mut String>, s: &str) {
110 if let Some(ref mut id) = *id {
114 while let Some(event) = $parser.next() {
116 $($end_event)|* => break,
117 Event::Text(ref s) => {
120 $buf.push_str(&format!("{}", Escape(s)));
125 Event::SoftBreak | Event::HardBreak if !$buf.is_empty() => {
129 looper($parser, &mut $buf, Some(x), $toc_builder, $shorter, $id);
136 pub fn render(w: &mut fmt::Formatter,
139 shorter: MarkdownOutputStyle) -> fmt::Result {
140 fn code_block(parser: &mut Parser, buffer: &mut String, lang: &str) {
141 let mut origtext = String::new();
142 while let Some(event) = parser.next() {
144 Event::End(Tag::CodeBlock(_)) => break,
145 Event::Text(ref s) => {
146 origtext.push_str(s);
151 let origtext = origtext.trim_left();
152 debug!("docblock: ==============\n{:?}\n=======", origtext);
154 let lines = origtext.lines().filter(|l| {
155 stripped_filtered_line(*l).is_none()
157 let text = lines.collect::<Vec<&str>>().join("\n");
158 let block_info = if lang.is_empty() {
159 LangString::all_false()
161 LangString::parse(lang)
163 if !block_info.rust {
164 buffer.push_str(&format!("<pre><code class=\"language-{}\">{}</code></pre>",
168 PLAYGROUND.with(|play| {
169 // insert newline to clearly separate it from the
170 // previous block so we can shorten the html output
172 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
176 let test = origtext.lines().map(|l| {
177 stripped_filtered_line(l).unwrap_or(l)
178 }).collect::<Vec<&str>>().join("\n");
179 let krate = krate.as_ref().map(|s| &**s);
180 let test = test::maketest(&test, krate, false,
181 &Default::default());
182 let channel = if test.contains("#![feature(") {
183 "&version=nightly"
187 // These characters don't need to be escaped in a URI.
188 // FIXME: use a library function for percent encoding.
189 fn dont_escape(c: u8) -> bool {
190 (b'a' <= c && c <= b'z') ||
191 (b'A' <= c && c <= b'Z') ||
192 (b'0' <= c && c <= b'9') ||
193 c == b'-' || c == b'_' || c == b'.' ||
194 c == b'~' || c == b'!' || c == b'\'' ||
195 c == b'(' || c == b')' || c == b'*'
197 let mut test_escaped = String::new();
198 for b in test.bytes() {
200 test_escaped.push(char::from(b));
202 write!(test_escaped, "%{:02X}", b).unwrap();
206 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
207 url, test_escaped, channel
210 buffer.push_str(&highlight::render_with_highlighting(
212 Some("rust-example-rendered"),
214 playground_button.as_ref().map(String::as_str)));
218 fn heading(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
219 shorter: MarkdownOutputStyle, level: i32) {
220 let mut ret = String::new();
221 let mut id = String::new();
222 event_loop_break!(parser, toc_builder, shorter, ret, true, &mut Some(&mut id),
223 Event::End(Tag::Header(_)));
224 ret = ret.trim_right().to_owned();
226 let id = id.chars().filter_map(|c| {
227 if c.is_alphanumeric() || c == '-' || c == '_' {
229 Some(c.to_ascii_lowercase())
233 } else if c.is_whitespace() && c.is_ascii() {
238 }).collect::<String>();
240 let id = derive_id(id);
242 let sec = toc_builder.as_mut().map_or("".to_owned(), |builder| {
243 format!("{} ", builder.push(level as u32, ret.clone(), id.clone()))
247 buffer.push_str(&format!("<h{lvl} id=\"{id}\" class=\"section-header\">\
248 <a href=\"#{id}\">{sec}{}</a></h{lvl}>",
249 ret, lvl = level, id = id, sec = sec));
252 fn inline_code(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
253 shorter: MarkdownOutputStyle, id: &mut Option<&mut String>) {
254 let mut content = String::new();
255 event_loop_break!(parser, toc_builder, shorter, content, false, id, Event::End(Tag::Code));
256 buffer.push_str(&format!("<code>{}</code>",
257 Escape(&collapse_whitespace(content.trim_right()))));
260 fn link(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
261 shorter: MarkdownOutputStyle, url: &str, mut title: String,
262 id: &mut Option<&mut String>) {
263 event_loop_break!(parser, toc_builder, shorter, title, true, id,
264 Event::End(Tag::Link(_, _)));
265 buffer.push_str(&format!("<a href=\"{}\">{}</a>", url, title));
268 fn paragraph(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
269 shorter: MarkdownOutputStyle, id: &mut Option<&mut String>) {
270 let mut content = String::new();
271 event_loop_break!(parser, toc_builder, shorter, content, true, id,
272 Event::End(Tag::Paragraph));
273 buffer.push_str(&format!("<p>{}</p>", content.trim_right()));
276 fn table_cell(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
277 shorter: MarkdownOutputStyle) {
278 let mut content = String::new();
279 event_loop_break!(parser, toc_builder, shorter, content, true, &mut None,
280 Event::End(Tag::TableHead) |
281 Event::End(Tag::Table(_)) |
282 Event::End(Tag::TableRow) |
283 Event::End(Tag::TableCell));
284 buffer.push_str(&format!("<td>{}</td>", content.trim()));
287 fn table_row(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
288 shorter: MarkdownOutputStyle) {
289 let mut content = String::new();
290 while let Some(event) = parser.next() {
292 Event::End(Tag::TableHead) |
293 Event::End(Tag::Table(_)) |
294 Event::End(Tag::TableRow) => break,
295 Event::Start(Tag::TableCell) => {
296 table_cell(parser, &mut content, toc_builder, shorter);
299 looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
303 buffer.push_str(&format!("<tr>{}</tr>", content));
306 fn table_head(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
307 shorter: MarkdownOutputStyle) {
308 let mut content = String::new();
309 while let Some(event) = parser.next() {
311 Event::End(Tag::TableHead) | Event::End(Tag::Table(_)) => break,
312 Event::Start(Tag::TableCell) => {
313 table_cell(parser, &mut content, toc_builder, shorter);
316 looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
320 if !content.is_empty() {
321 buffer.push_str(&format!("<thead><tr>{}</tr></thead>", content.replace("td>", "th>")));
325 fn table(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
326 shorter: MarkdownOutputStyle) {
327 let mut content = String::new();
328 let mut rows = String::new();
329 while let Some(event) = parser.next() {
331 Event::End(Tag::Table(_)) => break,
332 Event::Start(Tag::TableHead) => {
333 table_head(parser, &mut content, toc_builder, shorter);
335 Event::Start(Tag::TableRow) => {
336 table_row(parser, &mut rows, toc_builder, shorter);
341 buffer.push_str(&format!("<table>{}{}</table>",
343 if shorter.is_compact() || rows.is_empty() {
346 format!("<tbody>{}</tbody>", rows)
350 fn blockquote(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
351 shorter: MarkdownOutputStyle) {
352 let mut content = String::new();
353 event_loop_break!(parser, toc_builder, shorter, content, true, &mut None,
354 Event::End(Tag::BlockQuote));
355 buffer.push_str(&format!("<blockquote>{}</blockquote>", content.trim_right()));
358 fn list_item(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
359 shorter: MarkdownOutputStyle) {
360 let mut content = String::new();
361 while let Some(event) = parser.next() {
363 Event::End(Tag::Item) => break,
364 Event::Text(ref s) => {
365 content.push_str(&format!("{}", Escape(s)));
368 looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
372 buffer.push_str(&format!("<li>{}</li>", content));
375 fn list(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
376 shorter: MarkdownOutputStyle) {
377 let mut content = String::new();
378 while let Some(event) = parser.next() {
380 Event::End(Tag::List(_)) => break,
381 Event::Start(Tag::Item) => {
382 list_item(parser, &mut content, toc_builder, shorter);
385 looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
389 buffer.push_str(&format!("<ul>{}</ul>", content));
392 fn emphasis(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
393 shorter: MarkdownOutputStyle, id: &mut Option<&mut String>) {
394 let mut content = String::new();
395 event_loop_break!(parser, toc_builder, shorter, content, false, id,
396 Event::End(Tag::Emphasis));
397 buffer.push_str(&format!("<em>{}</em>", content));
400 fn strong(parser: &mut Parser, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
401 shorter: MarkdownOutputStyle, id: &mut Option<&mut String>) {
402 let mut content = String::new();
403 event_loop_break!(parser, toc_builder, shorter, content, false, id,
404 Event::End(Tag::Strong));
405 buffer.push_str(&format!("<strong>{}</strong>", content));
408 fn looper<'a>(parser: &'a mut Parser, buffer: &mut String, next_event: Option<Event<'a>>,
409 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
410 id: &mut Option<&mut String>) -> bool {
411 if let Some(event) = next_event {
413 Event::Start(Tag::CodeBlock(lang)) => {
414 code_block(parser, buffer, &*lang);
416 Event::Start(Tag::Header(level)) => {
417 heading(parser, buffer, toc_builder, shorter, level);
419 Event::Start(Tag::Code) => {
420 inline_code(parser, buffer, toc_builder, shorter, id);
422 Event::Start(Tag::Paragraph) => {
423 paragraph(parser, buffer, toc_builder, shorter, id);
425 Event::Start(Tag::Link(ref url, ref t)) => {
426 link(parser, buffer, toc_builder, shorter, url, t.as_ref().to_owned(), id);
428 Event::Start(Tag::Table(_)) => {
429 table(parser, buffer, toc_builder, shorter);
431 Event::Start(Tag::BlockQuote) => {
432 blockquote(parser, buffer, toc_builder, shorter);
434 Event::Start(Tag::List(_)) => {
435 list(parser, buffer, toc_builder, shorter);
437 Event::Start(Tag::Emphasis) => {
438 emphasis(parser, buffer, toc_builder, shorter, id);
440 Event::Start(Tag::Strong) => {
441 strong(parser, buffer, toc_builder, shorter, id);
443 Event::Html(h) | Event::InlineHtml(h) => {
444 buffer.push_str(&*h);
454 let mut toc_builder = if print_toc {
455 Some(TocBuilder::new())
459 let mut buffer = String::new();
460 let mut parser = Parser::new_ext(s, pulldown_cmark::OPTION_ENABLE_TABLES);
462 let next_event = parser.next();
463 if !looper(&mut parser, &mut buffer, next_event, &mut toc_builder, shorter, &mut None) {
467 let mut ret = toc_builder.map_or(Ok(()), |builder| {
468 write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
472 ret = w.write_str(&buffer);
477 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
478 tests.set_position(position);
480 let mut parser = Parser::new(doc);
481 let mut prev_offset = 0;
482 let mut nb_lines = 0;
483 let mut register_header = None;
484 'main: while let Some(event) = parser.next() {
486 Event::Start(Tag::CodeBlock(s)) => {
487 let block_info = if s.is_empty() {
488 LangString::all_false()
490 LangString::parse(&*s)
492 if !block_info.rust {
495 let mut test_s = String::new();
496 let mut offset = None;
498 let event = parser.next();
499 if let Some(event) = event {
501 Event::End(Tag::CodeBlock(_)) => break,
502 Event::Text(ref s) => {
504 if offset.is_none() {
505 offset = Some(parser.get_offset());
514 let offset = offset.unwrap_or(0);
515 let lines = test_s.lines().map(|l| {
516 stripped_filtered_line(l).unwrap_or(l)
518 let text = lines.collect::<Vec<&str>>().join("\n");
519 nb_lines += doc[prev_offset..offset].lines().count();
520 let line = tests.get_line() + (nb_lines - 1);
521 let filename = tests.get_filename();
522 tests.add_test(text.to_owned(),
523 block_info.should_panic, block_info.no_run,
524 block_info.ignore, block_info.test_harness,
525 block_info.compile_fail, block_info.error_codes,
527 prev_offset = offset;
529 Event::Start(Tag::Header(level)) => {
530 register_header = Some(level as u32);
532 Event::Text(ref s) if register_header.is_some() => {
533 let level = register_header.unwrap();
535 tests.register_header("", level);
537 tests.register_header(s, level);
539 register_header = None;
546 #[derive(Eq, PartialEq, Clone, Debug)]
555 error_codes: Vec<String>,
559 fn all_false() -> LangString {
561 original: String::new(),
565 rust: true, // NB This used to be `notrust = false`
568 error_codes: Vec::new(),
572 fn parse(string: &str) -> LangString {
573 let mut seen_rust_tags = false;
574 let mut seen_other_tags = false;
575 let mut data = LangString::all_false();
576 let mut allow_compile_fail = false;
577 let mut allow_error_code_check = false;
578 if UnstableFeatures::from_environment().is_nightly_build() {
579 allow_compile_fail = true;
580 allow_error_code_check = true;
583 data.original = string.to_owned();
584 let tokens = string.split(|c: char|
585 !(c == '_' || c == '-' || c.is_alphanumeric())
588 for token in tokens {
591 "should_panic" => { data.should_panic = true; seen_rust_tags = true; },
592 "no_run" => { data.no_run = true; seen_rust_tags = true; },
593 "ignore" => { data.ignore = true; seen_rust_tags = true; },
594 "rust" => { data.rust = true; seen_rust_tags = true; },
595 "test_harness" => { data.test_harness = true; seen_rust_tags = true; },
596 "compile_fail" if allow_compile_fail => {
597 data.compile_fail = true;
598 seen_rust_tags = true;
601 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
602 if let Ok(_) = x[1..].parse::<u32>() {
603 data.error_codes.push(x.to_owned());
604 seen_rust_tags = true;
606 seen_other_tags = true;
609 _ => { seen_other_tags = true }
613 data.rust &= !seen_other_tags || seen_rust_tags;
619 impl<'a> fmt::Display for Markdown<'a> {
620 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
621 let Markdown(md, shorter) = *self;
622 // This is actually common enough to special-case
623 if md.is_empty() { return Ok(()) }
624 render(fmt, md, false, shorter)
628 impl<'a> fmt::Display for MarkdownWithToc<'a> {
629 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
630 let MarkdownWithToc(md) = *self;
631 render(fmt, md, true, MarkdownOutputStyle::Fancy)
635 impl<'a> fmt::Display for MarkdownHtml<'a> {
636 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
637 let MarkdownHtml(md) = *self;
638 // This is actually common enough to special-case
639 if md.is_empty() { return Ok(()) }
640 render(fmt, md, false, MarkdownOutputStyle::Fancy)
644 pub fn plain_summary_line(md: &str) -> String {
645 struct ParserWrapper<'a> {
651 impl<'a> Iterator for ParserWrapper<'a> {
654 fn next(&mut self) -> Option<String> {
655 let next_event = self.inner.next();
656 if next_event.is_none() {
659 let next_event = next_event.unwrap();
660 let (ret, is_in) = match next_event {
661 Event::Start(Tag::Paragraph) => (None, 1),
662 Event::Start(Tag::Link(_, ref t)) if !self.is_first => {
663 (Some(t.as_ref().to_owned()), 1)
665 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
666 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
667 Event::Start(Tag::Header(_)) => (None, 1),
668 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
669 Event::End(Tag::Link(_, ref t)) => (Some(t.as_ref().to_owned()), -1),
670 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
673 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
677 self.is_first = false;
684 let mut s = String::with_capacity(md.len() * 3 / 2);
685 let mut p = ParserWrapper {
686 inner: Parser::new(md),
690 while let Some(t) = p.next() {
700 use super::{LangString, Markdown, MarkdownHtml, MarkdownOutputStyle};
701 use super::plain_summary_line;
702 use html::render::reset_ids;
705 fn test_lang_string_parse() {
707 should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
708 compile_fail: bool, error_codes: Vec<String>) {
709 assert_eq!(LangString::parse(s), LangString {
710 should_panic: should_panic,
714 test_harness: test_harness,
715 compile_fail: compile_fail,
716 error_codes: error_codes,
717 original: s.to_owned(),
721 // marker | should_panic| no_run| ignore| rust | test_harness| compile_fail
723 t("", false, false, false, true, false, false, Vec::new());
724 t("rust", false, false, false, true, false, false, Vec::new());
725 t("sh", false, false, false, false, false, false, Vec::new());
726 t("ignore", false, false, true, true, false, false, Vec::new());
727 t("should_panic", true, false, false, true, false, false, Vec::new());
728 t("no_run", false, true, false, true, false, false, Vec::new());
729 t("test_harness", false, false, false, true, true, false, Vec::new());
730 t("compile_fail", false, true, false, true, false, true, Vec::new());
731 t("{.no_run .example}", false, true, false, true, false, false, Vec::new());
732 t("{.sh .should_panic}", true, false, false, true, false, false, Vec::new());
733 t("{.example .rust}", false, false, false, true, false, false, Vec::new());
734 t("{.test_harness .rust}", false, false, false, true, true, false, Vec::new());
739 let markdown = "# title";
740 format!("{}", Markdown(markdown, MarkdownOutputStyle::Fancy));
746 fn t(input: &str, expect: &str) {
747 let output = format!("{}", Markdown(input, MarkdownOutputStyle::Fancy));
748 assert_eq!(output, expect, "original: {}", input);
752 t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
753 <a href=\"#foo-bar\">Foo bar</a></h1>");
754 t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
755 header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
756 t("### **Foo** *bar* baz!?!& -_qux_-%",
757 "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
758 <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
759 <em>bar</em> baz!?!& -<em>qux</em>-%</a></h3>");
760 t("#### **Foo?** & \\*bar?!* _`baz`_ ❤ #qux",
761 "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
762 <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> & *bar?!* \
763 <em><code>baz</code></em> ❤ #qux</a></h4>");
767 fn test_header_ids_multiple_blocks() {
768 fn t(input: &str, expect: &str) {
769 let output = format!("{}", Markdown(input, MarkdownOutputStyle::Fancy));
770 assert_eq!(output, expect, "original: {}", input);
774 t("# Example", "<h1 id=\"example\" class=\"section-header\">\
775 <a href=\"#example\">Example</a></h1>");
776 t("# Panics", "<h1 id=\"panics\" class=\"section-header\">\
777 <a href=\"#panics\">Panics</a></h1>");
778 t("# Example", "<h1 id=\"example-1\" class=\"section-header\">\
779 <a href=\"#example-1\">Example</a></h1>");
780 t("# Main", "<h1 id=\"main-1\" class=\"section-header\">\
781 <a href=\"#main-1\">Main</a></h1>");
782 t("# Example", "<h1 id=\"example-2\" class=\"section-header\">\
783 <a href=\"#example-2\">Example</a></h1>");
784 t("# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
785 <a href=\"#panics-1\">Panics</a></h1>");
793 fn test_plain_summary_line() {
794 fn t(input: &str, expect: &str) {
795 let output = plain_summary_line(input);
796 assert_eq!(output, expect, "original: {}", input);
799 t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
800 t("code `let x = i32;` ...", "code `let x = i32;` ...");
801 t("type `Type<'static>` ...", "type `Type<'static>` ...");
802 t("# top header", "top header");
803 t("## header", "header");
807 fn test_markdown_html_escape() {
808 fn t(input: &str, expect: &str) {
809 let output = format!("{}", MarkdownHtml(input));
810 assert_eq!(output, expect, "original: {}", input);
813 t("`Struct<'a, T>`", "<p><code>Struct<'a, T></code></p>");
814 t("Struct<'a, T>", "<p>Struct<'a, T></p>");