]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
Rollup merge of #40703 - GuillaumeGomez:pointer-docs, r=steveklabnik
[rust.git] / src / librustdoc / html / markdown.rs
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.
4 //
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.
10
11 //! Markdown formatting for rustdoc
12 //!
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:
17 //!
18 //! ```rust,ignore
19 //! use rustdoc::html::markdown::{Markdown, MarkdownOutputStyle};
20 //!
21 //! let s = "My *markdown* _text_";
22 //! let html = format!("{}", Markdown(s, MarkdownOutputStyle::Fancy));
23 //! // ... something using html
24 //! ```
25
26 #![allow(non_camel_case_types)]
27
28 use std::ascii::AsciiExt;
29 use std::cell::RefCell;
30 use std::default::Default;
31 use std::fmt::{self, Write};
32 use std::str;
33 use syntax::feature_gate::UnstableFeatures;
34 use syntax::codemap::Span;
35
36 use html::render::derive_id;
37 use html::toc::TocBuilder;
38 use html::highlight;
39 use html::escape::Escape;
40 use test;
41
42 use pulldown_cmark::{self, Event, Parser, Tag};
43
44 #[derive(Copy, Clone)]
45 pub enum MarkdownOutputStyle {
46     Compact,
47     Fancy,
48 }
49
50 impl MarkdownOutputStyle {
51     pub fn is_compact(&self) -> bool {
52         match *self {
53             MarkdownOutputStyle::Compact => true,
54             _ => false,
55         }
56     }
57
58     pub fn is_fancy(&self) -> bool {
59         match *self {
60             MarkdownOutputStyle::Fancy => true,
61             _ => false,
62         }
63     }
64 }
65
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);
76
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
80 /// left as-is.)
81 fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
82     let trimmed = s.trim();
83     if trimmed == "#" {
84         Some("")
85     } else if trimmed.starts_with("# ") {
86         Some(&trimmed[2..])
87     } else {
88         None
89     }
90 }
91
92 /// Returns a new string with all consecutive whitespace collapsed into
93 /// single spaces.
94 ///
95 /// Any leading or trailing whitespace will be trimmed.
96 fn collapse_whitespace(s: &str) -> String {
97     s.split_whitespace().collect::<Vec<_>>().join(" ")
98 }
99
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)>> = {
103     RefCell::new(None)
104 });
105
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 {
111                 id.push_str(s);
112             }
113         }
114         while let Some(event) = $parser.next() {
115             match event {
116                 $($end_event)|* => break,
117                 Event::Text(ref s) => {
118                     inner($id, s);
119                     if $escape {
120                         $buf.push_str(&format!("{}", Escape(s)));
121                     } else {
122                         $buf.push_str(s);
123                     }
124                 }
125                 Event::SoftBreak | Event::HardBreak if !$buf.is_empty() => {
126                     $buf.push(' ');
127                 }
128                 x => {
129                     looper($parser, &mut $buf, Some(x), $toc_builder, $shorter, $id);
130                 }
131             }
132         }
133     }}
134 }
135
136 pub fn render(w: &mut fmt::Formatter,
137               s: &str,
138               print_toc: bool,
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() {
143             match event {
144                 Event::End(Tag::CodeBlock(_)) => break,
145                 Event::Text(ref s) => {
146                     origtext.push_str(s);
147                 }
148                 _ => {}
149             }
150         }
151         let origtext = origtext.trim_left();
152         debug!("docblock: ==============\n{:?}\n=======", origtext);
153
154         let lines = origtext.lines().filter(|l| {
155             stripped_filtered_line(*l).is_none()
156         });
157         let text = lines.collect::<Vec<&str>>().join("\n");
158         let block_info = if lang.is_empty() {
159             LangString::all_false()
160         } else {
161             LangString::parse(lang)
162         };
163         if !block_info.rust {
164             buffer.push_str(&format!("<pre><code class=\"language-{}\">{}</code></pre>",
165                             lang, text));
166             return
167         }
168         PLAYGROUND.with(|play| {
169             // insert newline to clearly separate it from the
170             // previous block so we can shorten the html output
171             buffer.push('\n');
172             let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
173                 if url.is_empty() {
174                     return None;
175                 }
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                     "&amp;version=nightly"
184                 } else {
185                     ""
186                 };
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'*'
196                 }
197                 let mut test_escaped = String::new();
198                 for b in test.bytes() {
199                     if dont_escape(b) {
200                         test_escaped.push(char::from(b));
201                     } else {
202                         write!(test_escaped, "%{:02X}", b).unwrap();
203                     }
204                 }
205                 Some(format!(
206                     r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
207                     url, test_escaped, channel
208                 ))
209             });
210             buffer.push_str(&highlight::render_with_highlighting(
211                             &text,
212                             Some("rust-example-rendered"),
213                             None,
214                             playground_button.as_ref().map(String::as_str)));
215         });
216     }
217
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();
225
226         let id = id.chars().filter_map(|c| {
227             if c.is_alphanumeric() || c == '-' || c == '_' {
228                 if c.is_ascii() {
229                     Some(c.to_ascii_lowercase())
230                 } else {
231                     Some(c)
232                 }
233             } else if c.is_whitespace() && c.is_ascii() {
234                 Some('-')
235             } else {
236                 None
237             }
238         }).collect::<String>();
239
240         let id = derive_id(id);
241
242         let sec = toc_builder.as_mut().map_or("".to_owned(), |builder| {
243             format!("{} ", builder.push(level as u32, ret.clone(), id.clone()))
244         });
245
246         // Render the HTML
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));
250     }
251
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()))));
258     }
259
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));
266     }
267
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()));
274     }
275
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()));
285     }
286
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() {
291             match event {
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);
297                 }
298                 x => {
299                     looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
300                 }
301             }
302         }
303         buffer.push_str(&format!("<tr>{}</tr>", content));
304     }
305
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() {
310             match event {
311                 Event::End(Tag::TableHead) | Event::End(Tag::Table(_)) => break,
312                 Event::Start(Tag::TableCell) => {
313                     table_cell(parser, &mut content, toc_builder, shorter);
314                 }
315                 x => {
316                     looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
317                 }
318             }
319         }
320         if !content.is_empty() {
321             buffer.push_str(&format!("<thead><tr>{}</tr></thead>", content.replace("td>", "th>")));
322         }
323     }
324
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() {
330             match event {
331                 Event::End(Tag::Table(_)) => break,
332                 Event::Start(Tag::TableHead) => {
333                     table_head(parser, &mut content, toc_builder, shorter);
334                 }
335                 Event::Start(Tag::TableRow) => {
336                     table_row(parser, &mut rows, toc_builder, shorter);
337                 }
338                 _ => {}
339             }
340         }
341         buffer.push_str(&format!("<table>{}{}</table>",
342                                  content,
343                                  if shorter.is_compact() || rows.is_empty() {
344                                      String::new()
345                                  } else {
346                                      format!("<tbody>{}</tbody>", rows)
347                                  }));
348     }
349
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()));
356     }
357
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() {
362             match event {
363                 Event::End(Tag::Item) => break,
364                 Event::Text(ref s) => {
365                     content.push_str(&format!("{}", Escape(s)));
366                 }
367                 x => {
368                     looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
369                 }
370             }
371         }
372         buffer.push_str(&format!("<li>{}</li>", content));
373     }
374
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() {
379             match event {
380                 Event::End(Tag::List(_)) => break,
381                 Event::Start(Tag::Item) => {
382                     list_item(parser, &mut content, toc_builder, shorter);
383                 }
384                 x => {
385                     looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
386                 }
387             }
388         }
389         buffer.push_str(&format!("<ul>{}</ul>", content));
390     }
391
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));
398     }
399
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));
406     }
407
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 {
412             match event {
413                 Event::Start(Tag::CodeBlock(lang)) => {
414                     code_block(parser, buffer, &*lang);
415                 }
416                 Event::Start(Tag::Header(level)) => {
417                     heading(parser, buffer, toc_builder, shorter, level);
418                 }
419                 Event::Start(Tag::Code) => {
420                     inline_code(parser, buffer, toc_builder, shorter, id);
421                 }
422                 Event::Start(Tag::Paragraph) => {
423                     paragraph(parser, buffer, toc_builder, shorter, id);
424                 }
425                 Event::Start(Tag::Link(ref url, ref t)) => {
426                     link(parser, buffer, toc_builder, shorter, url, t.as_ref().to_owned(), id);
427                 }
428                 Event::Start(Tag::Table(_)) => {
429                     table(parser, buffer, toc_builder, shorter);
430                 }
431                 Event::Start(Tag::BlockQuote) => {
432                     blockquote(parser, buffer, toc_builder, shorter);
433                 }
434                 Event::Start(Tag::List(_)) => {
435                     list(parser, buffer, toc_builder, shorter);
436                 }
437                 Event::Start(Tag::Emphasis) => {
438                     emphasis(parser, buffer, toc_builder, shorter, id);
439                 }
440                 Event::Start(Tag::Strong) => {
441                     strong(parser, buffer, toc_builder, shorter, id);
442                 }
443                 Event::Html(h) | Event::InlineHtml(h) => {
444                     buffer.push_str(&*h);
445                 }
446                 _ => {}
447             }
448             shorter.is_fancy()
449         } else {
450             false
451         }
452     }
453
454     let mut toc_builder = if print_toc {
455         Some(TocBuilder::new())
456     } else {
457         None
458     };
459     let mut buffer = String::new();
460     let mut parser = Parser::new_ext(s, pulldown_cmark::OPTION_ENABLE_TABLES);
461     loop {
462         let next_event = parser.next();
463         if !looper(&mut parser, &mut buffer, next_event, &mut toc_builder, shorter, &mut None) {
464             break
465         }
466     }
467     let mut ret = toc_builder.map_or(Ok(()), |builder| {
468         write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
469     });
470
471     if ret.is_ok() {
472         ret = w.write_str(&buffer);
473     }
474     ret
475 }
476
477 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
478     tests.set_position(position);
479
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() {
485         match event {
486             Event::Start(Tag::CodeBlock(s)) => {
487                 let block_info = if s.is_empty() {
488                     LangString::all_false()
489                 } else {
490                     LangString::parse(&*s)
491                 };
492                 if !block_info.rust {
493                     continue
494                 }
495                 let mut test_s = String::new();
496                 let mut offset = None;
497                 loop {
498                     let event = parser.next();
499                     if let Some(event) = event {
500                         match event {
501                             Event::End(Tag::CodeBlock(_)) => break,
502                             Event::Text(ref s) => {
503                                 test_s.push_str(s);
504                                 if offset.is_none() {
505                                     offset = Some(parser.get_offset());
506                                 }
507                             }
508                             _ => {}
509                         }
510                     } else {
511                         break 'main;
512                     }
513                 }
514                 let offset = offset.unwrap_or(0);
515                 let lines = test_s.lines().map(|l| {
516                     stripped_filtered_line(l).unwrap_or(l)
517                 });
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,
526                                line, filename);
527                 prev_offset = offset;
528             }
529             Event::Start(Tag::Header(level)) => {
530                 register_header = Some(level as u32);
531             }
532             Event::Text(ref s) if register_header.is_some() => {
533                 let level = register_header.unwrap();
534                 if s.is_empty() {
535                     tests.register_header("", level);
536                 } else {
537                     tests.register_header(s, level);
538                 }
539                 register_header = None;
540             }
541             _ => {}
542         }
543     }
544 }
545
546 #[derive(Eq, PartialEq, Clone, Debug)]
547 struct LangString {
548     original: String,
549     should_panic: bool,
550     no_run: bool,
551     ignore: bool,
552     rust: bool,
553     test_harness: bool,
554     compile_fail: bool,
555     error_codes: Vec<String>,
556 }
557
558 impl LangString {
559     fn all_false() -> LangString {
560         LangString {
561             original: String::new(),
562             should_panic: false,
563             no_run: false,
564             ignore: false,
565             rust: true,  // NB This used to be `notrust = false`
566             test_harness: false,
567             compile_fail: false,
568             error_codes: Vec::new(),
569         }
570     }
571
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;
581         }
582
583         data.original = string.to_owned();
584         let tokens = string.split(|c: char|
585             !(c == '_' || c == '-' || c.is_alphanumeric())
586         );
587
588         for token in tokens {
589             match token {
590                 "" => {},
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;
599                     data.no_run = true;
600                 }
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;
605                     } else {
606                         seen_other_tags = true;
607                     }
608                 }
609                 _ => { seen_other_tags = true }
610             }
611         }
612
613         data.rust &= !seen_other_tags || seen_rust_tags;
614
615         data
616     }
617 }
618
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)
625     }
626 }
627
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)
632     }
633 }
634
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)
641     }
642 }
643
644 pub fn plain_summary_line(md: &str) -> String {
645     struct ParserWrapper<'a> {
646         inner: Parser<'a>,
647         is_in: isize,
648         is_first: bool,
649     }
650
651     impl<'a> Iterator for ParserWrapper<'a> {
652         type Item = String;
653
654         fn next(&mut self) -> Option<String> {
655             let next_event = self.inner.next();
656             if next_event.is_none() {
657                 return None
658             }
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)
664                 }
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),
671                 _ => (None, 0),
672             };
673             if is_in > 0 || (is_in < 0 && self.is_in > 0) {
674                 self.is_in += is_in;
675             }
676             if ret.is_some() {
677                 self.is_first = false;
678                 ret
679             } else {
680                 Some(String::new())
681             }
682         }
683     }
684     let mut s = String::with_capacity(md.len() * 3 / 2);
685     let mut p = ParserWrapper {
686         inner: Parser::new(md),
687         is_in: 0,
688         is_first: true,
689     };
690     while let Some(t) = p.next() {
691         if !t.is_empty() {
692             s.push_str(&t);
693         }
694     }
695     s
696 }
697
698 #[cfg(test)]
699 mod tests {
700     use super::{LangString, Markdown, MarkdownHtml, MarkdownOutputStyle};
701     use super::plain_summary_line;
702     use html::render::reset_ids;
703
704     #[test]
705     fn test_lang_string_parse() {
706         fn t(s: &str,
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,
711                 no_run: no_run,
712                 ignore: ignore,
713                 rust: rust,
714                 test_harness: test_harness,
715                 compile_fail: compile_fail,
716                 error_codes: error_codes,
717                 original: s.to_owned(),
718             })
719         }
720
721         // marker                | should_panic| no_run| ignore| rust | test_harness| compile_fail
722         //                       | error_codes
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());
735     }
736
737     #[test]
738     fn issue_17736() {
739         let markdown = "# title";
740         format!("{}", Markdown(markdown, MarkdownOutputStyle::Fancy));
741         reset_ids(true);
742     }
743
744     #[test]
745     fn test_header() {
746         fn t(input: &str, expect: &str) {
747             let output = format!("{}", Markdown(input, MarkdownOutputStyle::Fancy));
748             assert_eq!(output, expect, "original: {}", input);
749             reset_ids(true);
750         }
751
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!?!&amp; -<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> &amp; *bar?!*  \
763           <em><code>baz</code></em> ❤ #qux</a></h4>");
764     }
765
766     #[test]
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);
771         }
772
773         let test = || {
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>");
786         };
787         test();
788         reset_ids(true);
789         test();
790     }
791
792     #[test]
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);
797         }
798
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");
804     }
805
806     #[test]
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);
811         }
812
813         t("`Struct<'a, T>`", "<p><code>Struct&lt;&#39;a, T&gt;</code></p>");
814         t("Struct<'a, T>", "<p>Struct&lt;&#39;a, T&gt;</p>");
815     }
816 }