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::collections::HashMap;
31 use std::default::Default;
32 use std::fmt::{self, Write};
34 use syntax::feature_gate::UnstableFeatures;
35 use syntax::codemap::Span;
37 use html::render::derive_id;
38 use html::toc::TocBuilder;
40 use html::escape::Escape;
43 use pulldown_cmark::{self, Event, Parser, Tag};
45 #[derive(Copy, Clone)]
46 pub enum MarkdownOutputStyle {
51 impl MarkdownOutputStyle {
52 pub fn is_compact(&self) -> bool {
54 MarkdownOutputStyle::Compact => true,
59 pub fn is_fancy(&self) -> bool {
61 MarkdownOutputStyle::Fancy => true,
67 /// A unit struct which has the `fmt::Display` trait implemented. When
68 /// formatted, this struct will emit the HTML corresponding to the rendered
69 /// version of the contained markdown string.
70 // The second parameter is whether we need a shorter version or not.
71 pub struct Markdown<'a>(pub &'a str, pub MarkdownOutputStyle);
72 /// A unit struct like `Markdown`, that renders the markdown with a
73 /// table of contents.
74 pub struct MarkdownWithToc<'a>(pub &'a str);
75 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
76 pub struct MarkdownHtml<'a>(pub &'a str);
78 /// Returns Some(code) if `s` is a line that should be stripped from
79 /// documentation but used in example code. `code` is the portion of
80 /// `s` that should be used in tests. (None for lines that should be
82 fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
83 let trimmed = s.trim();
86 } else if trimmed.starts_with("# ") {
93 /// Returns a new string with all consecutive whitespace collapsed into
96 /// Any leading or trailing whitespace will be trimmed.
97 fn collapse_whitespace(s: &str) -> String {
98 s.split_whitespace().collect::<Vec<_>>().join(" ")
101 // Information about the playground if a URL has been specified, containing an
102 // optional crate name and the URL.
103 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
107 macro_rules! event_loop_break {
108 ($parser:expr, $toc_builder:expr, $shorter:expr, $buf:expr, $escape:expr, $id:expr,
109 $($end_event:pat)|*) => {{
110 fn inner(id: &mut Option<&mut String>, s: &str) {
111 if let Some(ref mut id) = *id {
115 while let Some(event) = $parser.next() {
117 $($end_event)|* => break,
118 Event::Text(ref s) => {
122 $buf.push_str(&format!("{}", Escape(s)));
127 Event::SoftBreak => {
129 if !$buf.is_empty() {
134 looper($parser, &mut $buf, Some(x), $toc_builder, $shorter, $id);
141 struct ParserWrapper<'a> {
143 // The key is the footnote reference. The value is the footnote definition and the id.
144 footnotes: HashMap<String, (String, u16)>,
147 impl<'a> ParserWrapper<'a> {
148 pub fn new(s: &'a str) -> ParserWrapper<'a> {
150 parser: Parser::new_ext(s, pulldown_cmark::OPTION_ENABLE_TABLES |
151 pulldown_cmark::OPTION_ENABLE_FOOTNOTES),
152 footnotes: HashMap::new(),
156 pub fn next(&mut self) -> Option<Event<'a>> {
160 pub fn get_entry(&mut self, key: &str) -> &mut (String, u16) {
161 let new_id = self.footnotes.keys().count() + 1;
162 let key = key.to_owned();
163 self.footnotes.entry(key).or_insert((String::new(), new_id as u16))
167 pub fn render(w: &mut fmt::Formatter,
170 shorter: MarkdownOutputStyle) -> fmt::Result {
171 fn code_block(parser: &mut ParserWrapper, buffer: &mut String, lang: &str) {
173 let mut origtext = String::new();
174 while let Some(event) = parser.next() {
176 Event::End(Tag::CodeBlock(_)) => break,
177 Event::Text(ref s) => {
178 origtext.push_str(s);
183 let origtext = origtext.trim_left();
184 debug!("docblock: ==============\n{:?}\n=======", origtext);
186 let lines = origtext.lines().filter(|l| {
187 stripped_filtered_line(*l).is_none()
189 let text = lines.collect::<Vec<&str>>().join("\n");
190 let block_info = if lang.is_empty() {
191 LangString::all_false()
193 LangString::parse(lang)
195 if !block_info.rust {
196 buffer.push_str(&format!("<pre><code class=\"language-{}\">{}</code></pre>",
200 PLAYGROUND.with(|play| {
201 // insert newline to clearly separate it from the
202 // previous block so we can shorten the html output
204 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
208 let test = origtext.lines().map(|l| {
209 stripped_filtered_line(l).unwrap_or(l)
210 }).collect::<Vec<&str>>().join("\n");
211 let krate = krate.as_ref().map(|s| &**s);
212 let test = test::maketest(&test, krate, false,
213 &Default::default());
214 let channel = if test.contains("#![feature(") {
215 "&version=nightly"
219 // These characters don't need to be escaped in a URI.
220 // FIXME: use a library function for percent encoding.
221 fn dont_escape(c: u8) -> bool {
222 (b'a' <= c && c <= b'z') ||
223 (b'A' <= c && c <= b'Z') ||
224 (b'0' <= c && c <= b'9') ||
225 c == b'-' || c == b'_' || c == b'.' ||
226 c == b'~' || c == b'!' || c == b'\'' ||
227 c == b'(' || c == b')' || c == b'*'
229 let mut test_escaped = String::new();
230 for b in test.bytes() {
232 test_escaped.push(char::from(b));
234 write!(test_escaped, "%{:02X}", b).unwrap();
238 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
239 url, test_escaped, channel
242 buffer.push_str(&highlight::render_with_highlighting(
244 Some("rust-example-rendered"),
246 playground_button.as_ref().map(String::as_str)));
250 fn heading(parser: &mut ParserWrapper, buffer: &mut String,
251 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle, level: i32) {
253 let mut ret = String::new();
254 let mut id = String::new();
255 event_loop_break!(parser, toc_builder, shorter, ret, true, &mut Some(&mut id),
256 Event::End(Tag::Header(_)));
257 ret = ret.trim_right().to_owned();
259 let id = id.chars().filter_map(|c| {
260 if c.is_alphanumeric() || c == '-' || c == '_' {
262 Some(c.to_ascii_lowercase())
266 } else if c.is_whitespace() && c.is_ascii() {
271 }).collect::<String>();
273 let id = derive_id(id);
275 let sec = toc_builder.as_mut().map_or("".to_owned(), |builder| {
276 format!("{} ", builder.push(level as u32, ret.clone(), id.clone()))
280 buffer.push_str(&format!("<h{lvl} id=\"{id}\" class=\"section-header\">\
281 <a href=\"#{id}\">{sec}{}</a></h{lvl}>",
282 ret, lvl = level, id = id, sec = sec));
285 fn inline_code(parser: &mut ParserWrapper, buffer: &mut String,
286 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
287 id: &mut Option<&mut String>) {
288 debug!("InlineCode");
289 let mut content = String::new();
290 event_loop_break!(parser, toc_builder, shorter, content, false, id, Event::End(Tag::Code));
291 buffer.push_str(&format!("<code>{}</code>",
292 Escape(&collapse_whitespace(content.trim_right()))));
295 fn link(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
296 shorter: MarkdownOutputStyle, url: &str, title: &str,
297 id: &mut Option<&mut String>) {
299 let mut content = String::new();
300 event_loop_break!(parser, toc_builder, shorter, content, true, id,
301 Event::End(Tag::Link(_, _)));
302 if title.is_empty() {
303 buffer.push_str(&format!("<a href=\"{}\">{}</a>", url, content));
305 buffer.push_str(&format!("<a href=\"{}\" title=\"{}\">{}</a>",
306 url, Escape(title), content));
310 fn image(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
311 shorter: MarkdownOutputStyle, url: &str, mut title: String,
312 id: &mut Option<&mut String>) {
314 event_loop_break!(parser, toc_builder, shorter, title, true, id,
315 Event::End(Tag::Image(_, _)));
316 buffer.push_str(&format!("<img src=\"{}\" alt=\"{}\">", url, title));
319 fn paragraph(parser: &mut ParserWrapper, buffer: &mut String,
320 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
321 id: &mut Option<&mut String>) {
323 let mut content = String::new();
324 event_loop_break!(parser, toc_builder, shorter, content, true, id,
325 Event::End(Tag::Paragraph));
326 buffer.push_str(&format!("<p>{}</p>", content.trim_right()));
329 fn table_cell(parser: &mut ParserWrapper, buffer: &mut String,
330 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
332 let mut content = String::new();
333 event_loop_break!(parser, toc_builder, shorter, content, true, &mut None,
334 Event::End(Tag::TableHead) |
335 Event::End(Tag::Table(_)) |
336 Event::End(Tag::TableRow) |
337 Event::End(Tag::TableCell));
338 buffer.push_str(&format!("<td>{}</td>", content.trim()));
341 fn table_row(parser: &mut ParserWrapper, buffer: &mut String,
342 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
344 let mut content = String::new();
345 while let Some(event) = parser.next() {
347 Event::End(Tag::TableHead) |
348 Event::End(Tag::Table(_)) |
349 Event::End(Tag::TableRow) => break,
350 Event::Start(Tag::TableCell) => {
351 table_cell(parser, &mut content, toc_builder, shorter);
354 looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
358 buffer.push_str(&format!("<tr>{}</tr>", content));
361 fn table_head(parser: &mut ParserWrapper, buffer: &mut String,
362 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
364 let mut content = String::new();
365 while let Some(event) = parser.next() {
367 Event::End(Tag::TableHead) | Event::End(Tag::Table(_)) => break,
368 Event::Start(Tag::TableCell) => {
369 table_cell(parser, &mut content, toc_builder, shorter);
372 looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
376 if !content.is_empty() {
377 buffer.push_str(&format!("<thead><tr>{}</tr></thead>", content.replace("td>", "th>")));
381 fn table(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
382 shorter: MarkdownOutputStyle) {
384 let mut content = String::new();
385 let mut rows = String::new();
386 while let Some(event) = parser.next() {
388 Event::End(Tag::Table(_)) => break,
389 Event::Start(Tag::TableHead) => {
390 table_head(parser, &mut content, toc_builder, shorter);
392 Event::Start(Tag::TableRow) => {
393 table_row(parser, &mut rows, toc_builder, shorter);
398 buffer.push_str(&format!("<table>{}{}</table>",
400 if shorter.is_compact() || rows.is_empty() {
403 format!("<tbody>{}</tbody>", rows)
407 fn blockquote(parser: &mut ParserWrapper, buffer: &mut String,
408 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
409 debug!("BlockQuote");
410 let mut content = String::new();
411 event_loop_break!(parser, toc_builder, shorter, content, true, &mut None,
412 Event::End(Tag::BlockQuote));
413 buffer.push_str(&format!("<blockquote>{}</blockquote>", content.trim_right()));
416 fn list_item(parser: &mut ParserWrapper, buffer: &mut String,
417 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
419 let mut content = String::new();
420 while let Some(event) = parser.next() {
422 Event::End(Tag::Item) => break,
423 Event::Text(ref s) => {
424 content.push_str(&format!("{}", Escape(s)));
427 looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
430 if shorter.is_compact() {
434 buffer.push_str(&format!("<li>{}</li>", content));
437 fn list(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
438 shorter: MarkdownOutputStyle, is_sorted_list: bool) {
440 let mut content = String::new();
441 while let Some(event) = parser.next() {
443 Event::End(Tag::List(_)) => break,
444 Event::Start(Tag::Item) => {
445 list_item(parser, &mut content, toc_builder, shorter);
448 looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
451 if shorter.is_compact() {
455 buffer.push_str(&format!("<{0}>{1}</{0}>",
456 if is_sorted_list { "ol" } else { "ul" },
460 fn emphasis(parser: &mut ParserWrapper, buffer: &mut String,
461 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
462 id: &mut Option<&mut String>) {
464 let mut content = String::new();
465 event_loop_break!(parser, toc_builder, shorter, content, false, id,
466 Event::End(Tag::Emphasis));
467 buffer.push_str(&format!("<em>{}</em>", content));
470 fn strong(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
471 shorter: MarkdownOutputStyle, id: &mut Option<&mut String>) {
473 let mut content = String::new();
474 event_loop_break!(parser, toc_builder, shorter, content, false, id,
475 Event::End(Tag::Strong));
476 buffer.push_str(&format!("<strong>{}</strong>", content));
479 fn footnote(parser: &mut ParserWrapper, buffer: &mut String,
480 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
481 id: &mut Option<&mut String>) {
482 debug!("FootnoteDefinition");
483 let mut content = String::new();
484 event_loop_break!(parser, toc_builder, shorter, content, true, id,
485 Event::End(Tag::FootnoteDefinition(_)));
486 buffer.push_str(&content);
489 fn rule(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
490 shorter: MarkdownOutputStyle, id: &mut Option<&mut String>) {
492 let mut content = String::new();
493 event_loop_break!(parser, toc_builder, shorter, content, true, id,
494 Event::End(Tag::Rule));
495 buffer.push_str("<hr>");
498 fn looper<'a>(parser: &'a mut ParserWrapper, buffer: &mut String, next_event: Option<Event<'a>>,
499 toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
500 id: &mut Option<&mut String>) -> bool {
501 if let Some(event) = next_event {
503 Event::Start(Tag::CodeBlock(lang)) => {
504 code_block(parser, buffer, &*lang);
506 Event::Start(Tag::Header(level)) => {
507 heading(parser, buffer, toc_builder, shorter, level);
509 Event::Start(Tag::Code) => {
510 inline_code(parser, buffer, toc_builder, shorter, id);
512 Event::Start(Tag::Paragraph) => {
513 paragraph(parser, buffer, toc_builder, shorter, id);
515 Event::Start(Tag::Link(ref url, ref t)) => {
516 link(parser, buffer, toc_builder, shorter, url, t.as_ref(), id);
518 Event::Start(Tag::Image(ref url, ref t)) => {
519 image(parser, buffer, toc_builder, shorter, url, t.as_ref().to_owned(), id);
521 Event::Start(Tag::Table(_)) => {
522 table(parser, buffer, toc_builder, shorter);
524 Event::Start(Tag::BlockQuote) => {
525 blockquote(parser, buffer, toc_builder, shorter);
527 Event::Start(Tag::List(x)) => {
528 list(parser, buffer, toc_builder, shorter, x.is_some());
530 Event::Start(Tag::Emphasis) => {
531 emphasis(parser, buffer, toc_builder, shorter, id);
533 Event::Start(Tag::Strong) => {
534 strong(parser, buffer, toc_builder, shorter, id);
536 Event::Start(Tag::Rule) => {
537 rule(parser, buffer, toc_builder, shorter, id);
539 Event::Start(Tag::FootnoteDefinition(ref def)) => {
540 debug!("FootnoteDefinition");
541 let mut content = String::new();
542 let def = def.as_ref();
543 footnote(parser, &mut content, toc_builder, shorter, id);
544 let entry = parser.get_entry(def);
545 let cur_id = (*entry).1;
546 (*entry).0.push_str(&format!("<li id=\"ref{}\">{} <a href=\"#supref{0}\" \
547 rev=\"footnote\">↩</a></p></li>",
549 if content.ends_with("</p>") {
550 &content[..content.len() - 4]
555 Event::FootnoteReference(ref reference) => {
556 debug!("FootnoteReference");
557 let entry = parser.get_entry(reference.as_ref());
558 buffer.push_str(&format!("<sup id=\"supref{0}\"><a href=\"#ref{0}\">{0}</a>\
562 Event::HardBreak => {
564 if shorter.is_fancy() {
565 buffer.push_str("<br>");
566 } else if !buffer.is_empty() {
570 Event::Html(h) | Event::InlineHtml(h) => {
571 debug!("Html/InlineHtml");
572 buffer.push_str(&*h);
582 let mut toc_builder = if print_toc {
583 Some(TocBuilder::new())
587 let mut buffer = String::new();
588 let mut parser = ParserWrapper::new(s);
590 let next_event = parser.next();
591 if !looper(&mut parser, &mut buffer, next_event, &mut toc_builder, shorter, &mut None) {
595 if !parser.footnotes.is_empty() {
596 let mut v: Vec<_> = parser.footnotes.values().collect();
597 v.sort_by(|a, b| a.1.cmp(&b.1));
598 buffer.push_str(&format!("<div class=\"footnotes\"><hr><ol>{}</ol></div>",
600 .map(|s| s.0.as_str())
604 let mut ret = toc_builder.map_or(Ok(()), |builder| {
605 write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
609 ret = w.write_str(&buffer);
614 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
615 tests.set_position(position);
617 let mut parser = Parser::new(doc);
618 let mut prev_offset = 0;
619 let mut nb_lines = 0;
620 let mut register_header = None;
621 'main: while let Some(event) = parser.next() {
623 Event::Start(Tag::CodeBlock(s)) => {
624 let block_info = if s.is_empty() {
625 LangString::all_false()
627 LangString::parse(&*s)
629 if !block_info.rust {
632 let mut test_s = String::new();
633 let mut offset = None;
635 let event = parser.next();
636 if let Some(event) = event {
638 Event::End(Tag::CodeBlock(_)) => break,
639 Event::Text(ref s) => {
641 if offset.is_none() {
642 offset = Some(parser.get_offset());
651 let offset = offset.unwrap_or(0);
652 let lines = test_s.lines().map(|l| {
653 stripped_filtered_line(l).unwrap_or(l)
655 let text = lines.collect::<Vec<&str>>().join("\n");
656 nb_lines += doc[prev_offset..offset].lines().count();
657 let line = tests.get_line() + (nb_lines - 1);
658 let filename = tests.get_filename();
659 tests.add_test(text.to_owned(),
660 block_info.should_panic, block_info.no_run,
661 block_info.ignore, block_info.test_harness,
662 block_info.compile_fail, block_info.error_codes,
664 prev_offset = offset;
666 Event::Start(Tag::Header(level)) => {
667 register_header = Some(level as u32);
669 Event::Text(ref s) if register_header.is_some() => {
670 let level = register_header.unwrap();
672 tests.register_header("", level);
674 tests.register_header(s, level);
676 register_header = None;
683 #[derive(Eq, PartialEq, Clone, Debug)]
692 error_codes: Vec<String>,
696 fn all_false() -> LangString {
698 original: String::new(),
702 rust: true, // NB This used to be `notrust = false`
705 error_codes: Vec::new(),
709 fn parse(string: &str) -> LangString {
710 let mut seen_rust_tags = false;
711 let mut seen_other_tags = false;
712 let mut data = LangString::all_false();
713 let mut allow_compile_fail = false;
714 let mut allow_error_code_check = false;
715 if UnstableFeatures::from_environment().is_nightly_build() {
716 allow_compile_fail = true;
717 allow_error_code_check = true;
720 data.original = string.to_owned();
721 let tokens = string.split(|c: char|
722 !(c == '_' || c == '-' || c.is_alphanumeric())
725 for token in tokens {
728 "should_panic" => { data.should_panic = true; seen_rust_tags = true; },
729 "no_run" => { data.no_run = true; seen_rust_tags = true; },
730 "ignore" => { data.ignore = true; seen_rust_tags = true; },
731 "rust" => { data.rust = true; seen_rust_tags = true; },
732 "test_harness" => { data.test_harness = true; seen_rust_tags = true; },
733 "compile_fail" if allow_compile_fail => {
734 data.compile_fail = true;
735 seen_rust_tags = true;
738 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
739 if let Ok(_) = x[1..].parse::<u32>() {
740 data.error_codes.push(x.to_owned());
741 seen_rust_tags = true;
743 seen_other_tags = true;
746 _ => { seen_other_tags = true }
750 data.rust &= !seen_other_tags || seen_rust_tags;
756 impl<'a> fmt::Display for Markdown<'a> {
757 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
758 let Markdown(md, shorter) = *self;
759 // This is actually common enough to special-case
760 if md.is_empty() { return Ok(()) }
761 render(fmt, md, false, shorter)
765 impl<'a> fmt::Display for MarkdownWithToc<'a> {
766 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
767 let MarkdownWithToc(md) = *self;
768 render(fmt, md, true, MarkdownOutputStyle::Fancy)
772 impl<'a> fmt::Display for MarkdownHtml<'a> {
773 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
774 let MarkdownHtml(md) = *self;
775 // This is actually common enough to special-case
776 if md.is_empty() { return Ok(()) }
777 render(fmt, md, false, MarkdownOutputStyle::Fancy)
781 pub fn plain_summary_line(md: &str) -> String {
782 struct ParserWrapper<'a> {
788 impl<'a> Iterator for ParserWrapper<'a> {
791 fn next(&mut self) -> Option<String> {
792 let next_event = self.inner.next();
793 if next_event.is_none() {
796 let next_event = next_event.unwrap();
797 let (ret, is_in) = match next_event {
798 Event::Start(Tag::Paragraph) => (None, 1),
799 Event::Start(Tag::Link(_, ref t)) if !self.is_first => {
800 (Some(t.as_ref().to_owned()), 1)
802 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
803 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
804 Event::Start(Tag::Header(_)) => (None, 1),
805 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
806 Event::End(Tag::Link(_, ref t)) => (Some(t.as_ref().to_owned()), -1),
807 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
810 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
814 self.is_first = false;
821 let mut s = String::with_capacity(md.len() * 3 / 2);
822 let mut p = ParserWrapper {
823 inner: Parser::new(md),
827 while let Some(t) = p.next() {
837 use super::{LangString, Markdown, MarkdownHtml, MarkdownOutputStyle};
838 use super::plain_summary_line;
839 use html::render::reset_ids;
842 fn test_lang_string_parse() {
844 should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
845 compile_fail: bool, error_codes: Vec<String>) {
846 assert_eq!(LangString::parse(s), LangString {
847 should_panic: should_panic,
851 test_harness: test_harness,
852 compile_fail: compile_fail,
853 error_codes: error_codes,
854 original: s.to_owned(),
858 // marker | should_panic| no_run| ignore| rust | test_harness| compile_fail
860 t("", false, false, false, true, false, false, Vec::new());
861 t("rust", false, false, false, true, false, false, Vec::new());
862 t("sh", false, false, false, false, false, false, Vec::new());
863 t("ignore", false, false, true, true, false, false, Vec::new());
864 t("should_panic", true, false, false, true, false, false, Vec::new());
865 t("no_run", false, true, false, true, false, false, Vec::new());
866 t("test_harness", false, false, false, true, true, false, Vec::new());
867 t("compile_fail", false, true, false, true, false, true, Vec::new());
868 t("{.no_run .example}", false, true, false, true, false, false, Vec::new());
869 t("{.sh .should_panic}", true, false, false, true, false, false, Vec::new());
870 t("{.example .rust}", false, false, false, true, false, false, Vec::new());
871 t("{.test_harness .rust}", false, false, false, true, true, false, Vec::new());
876 let markdown = "# title";
877 format!("{}", Markdown(markdown, MarkdownOutputStyle::Fancy));
883 fn t(input: &str, expect: &str) {
884 let output = format!("{}", Markdown(input, MarkdownOutputStyle::Fancy));
885 assert_eq!(output, expect, "original: {}", input);
889 t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
890 <a href=\"#foo-bar\">Foo bar</a></h1>");
891 t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
892 header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
893 t("### **Foo** *bar* baz!?!& -_qux_-%",
894 "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
895 <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
896 <em>bar</em> baz!?!& -<em>qux</em>-%</a></h3>");
897 t("#### **Foo?** & \\*bar?!* _`baz`_ ❤ #qux",
898 "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
899 <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> & *bar?!* \
900 <em><code>baz</code></em> ❤ #qux</a></h4>");
904 fn test_header_ids_multiple_blocks() {
905 fn t(input: &str, expect: &str) {
906 let output = format!("{}", Markdown(input, MarkdownOutputStyle::Fancy));
907 assert_eq!(output, expect, "original: {}", input);
911 t("# Example", "<h1 id=\"example\" class=\"section-header\">\
912 <a href=\"#example\">Example</a></h1>");
913 t("# Panics", "<h1 id=\"panics\" class=\"section-header\">\
914 <a href=\"#panics\">Panics</a></h1>");
915 t("# Example", "<h1 id=\"example-1\" class=\"section-header\">\
916 <a href=\"#example-1\">Example</a></h1>");
917 t("# Main", "<h1 id=\"main-1\" class=\"section-header\">\
918 <a href=\"#main-1\">Main</a></h1>");
919 t("# Example", "<h1 id=\"example-2\" class=\"section-header\">\
920 <a href=\"#example-2\">Example</a></h1>");
921 t("# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
922 <a href=\"#panics-1\">Panics</a></h1>");
930 fn test_plain_summary_line() {
931 fn t(input: &str, expect: &str) {
932 let output = plain_summary_line(input);
933 assert_eq!(output, expect, "original: {}", input);
936 t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
937 t("code `let x = i32;` ...", "code `let x = i32;` ...");
938 t("type `Type<'static>` ...", "type `Type<'static>` ...");
939 t("# top header", "top header");
940 t("## header", "header");
944 fn test_markdown_html_escape() {
945 fn t(input: &str, expect: &str) {
946 let output = format!("{}", MarkdownHtml(input));
947 assert_eq!(output, expect, "original: {}", input);
950 t("`Struct<'a, T>`", "<p><code>Struct<'a, T></code></p>");
951 t("Struct<'a, T>", "<p>Struct<'a, T></p>");