]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
ae28e5a0923ead24ca3e4c8b5f705a21024137c8
[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 //! ```
19 //! #![feature(rustc_private)]
20 //!
21 //! use rustdoc::html::markdown::Markdown;
22 //!
23 //! let s = "My *markdown* _text_";
24 //! let html = format!("{}", Markdown(s));
25 //! // ... something using html
26 //! ```
27
28 #![allow(non_camel_case_types)]
29
30 use std::cell::RefCell;
31 use std::collections::{HashMap, VecDeque};
32 use std::default::Default;
33 use std::fmt::{self, Write};
34 use std::str;
35 use syntax::feature_gate::UnstableFeatures;
36 use syntax::codemap::Span;
37
38 use html::render::derive_id;
39 use html::toc::TocBuilder;
40 use html::highlight;
41 use test;
42
43 use pulldown_cmark::{html, Event, Tag, Parser};
44 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
45
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)]);
58
59 /// Controls whether a line will be hidden or shown in HTML output.
60 ///
61 /// All lines are used in documentation tests.
62 enum Line<'a> {
63     Hidden(&'a str),
64     Shown(&'a str),
65 }
66
67 impl<'a> Line<'a> {
68     fn for_html(self) -> Option<&'a str> {
69         match self {
70             Line::Shown(l) => Some(l),
71             Line::Hidden(_) => None,
72         }
73     }
74
75     fn for_code(self) -> &'a str {
76         match self {
77             Line::Shown(l) |
78             Line::Hidden(l) => l,
79         }
80     }
81 }
82
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("# ") {
93         // # text
94         Line::Hidden(&trimmed[2..])
95     } else if trimmed == "#" {
96         // We cannot handle '#text' because it could be #[attr].
97         Line::Hidden("")
98     } else {
99         Line::Shown(s)
100     }
101 }
102
103 /// Convert chars from a title for an id.
104 ///
105 /// "Hello, world!" -> "hello-world"
106 fn slugify(c: char) -> Option<char> {
107     if c.is_alphanumeric() || c == '-' || c == '_' {
108         if c.is_ascii() {
109             Some(c.to_ascii_lowercase())
110         } else {
111             Some(c)
112         }
113     } else if c.is_whitespace() && c.is_ascii() {
114         Some('-')
115     } else {
116         None
117     }
118 }
119
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)>> = {
123     RefCell::new(None)
124 });
125
126 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
127 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
128     inner: I,
129 }
130
131 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
132     fn new(iter: I) -> Self {
133         CodeBlocks {
134             inner: iter,
135         }
136     }
137 }
138
139 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
140     type Item = Event<'a>;
141
142     fn next(&mut self) -> Option<Self::Item> {
143         let event = self.inner.next();
144         let compile_fail;
145         let ignore;
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)));
150             }
151             compile_fail = parse_result.compile_fail;
152             ignore = parse_result.ignore;
153         } else {
154             return event;
155         }
156
157         let mut origtext = String::new();
158         for event in &mut self.inner {
159             match event {
160                 Event::End(Tag::CodeBlock(..)) => break,
161                 Event::Text(ref s) => {
162                     origtext.push_str(s);
163                 }
164                 _ => {}
165             }
166         }
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)| {
174                 if url.is_empty() {
175                     return None;
176                 }
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                     "&amp;version=nightly"
185                 } else {
186                     ""
187                 };
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'*'
197                 }
198                 let mut test_escaped = String::new();
199                 for b in test.bytes() {
200                     if dont_escape(b) {
201                         test_escaped.push(char::from(b));
202                     } else {
203                         write!(test_escaped, "%{:02X}", b).unwrap();
204                     }
205                 }
206                 Some(format!(
207                     r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
208                     url, test_escaped, channel
209                 ))
210             });
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"))
215             } else {
216                 None
217             };
218             s.push_str(&highlight::render_with_highlighting(
219                         &text,
220                         Some(&format!("rust-example-rendered{}",
221                                       if ignore { " ignore" }
222                                       else if compile_fail { " compile_fail" }
223                                       else { "" })),
224                         None,
225                         playground_button.as_ref().map(String::as_str),
226                         tooltip));
227             Some(Event::Html(s.into()))
228         })
229     }
230 }
231
232 /// Make headings links with anchor ids and build up TOC.
233 struct LinkReplacer<'a, 'b, I: Iterator<Item = Event<'a>>> {
234     inner: I,
235     links: &'b [(String, String)]
236 }
237
238 impl<'a, 'b, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, 'b, I> {
239     fn new(iter: I, links: &'b [(String, String)]) -> Self {
240         LinkReplacer {
241             inner: iter,
242             links
243         }
244     }
245 }
246
247 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, 'b, I> {
248     type Item = Event<'a>;
249
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)
254             {
255                 Some(Event::Start(Tag::Link(replace.to_owned().into(), text)))
256             } else {
257                 Some(Event::Start(Tag::Link(dest, text)))
258             }
259         } else {
260             event
261         }
262     }
263 }
264
265 /// Make headings links with anchor ids and build up TOC.
266 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
267     inner: I,
268     toc: Option<&'b mut TocBuilder>,
269     buf: VecDeque<Event<'a>>,
270 }
271
272 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
273     fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
274         HeadingLinks {
275             inner: iter,
276             toc,
277             buf: VecDeque::new(),
278         }
279     }
280 }
281
282 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
283     type Item = Event<'a>;
284
285     fn next(&mut self) -> Option<Self::Item> {
286         if let Some(e) = self.buf.pop_front() {
287             return Some(e);
288         }
289
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 {
294                 match event {
295                     Event::End(Tag::Header(..)) => break,
296                     Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
297                     _ => {},
298                 }
299                 self.buf.push_back(event);
300             }
301             let id = derive_id(id);
302
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()));
308             }
309
310             self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
311
312             let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
313                                       <a href=\"#{id}\">",
314                                      id = id,
315                                      level = level);
316             return Some(Event::InlineHtml(start_tags.into()));
317         }
318         event
319     }
320 }
321
322 /// Extracts just the first paragraph.
323 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
324     inner: I,
325     started: bool,
326     depth: u32,
327 }
328
329 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
330     fn new(iter: I) -> Self {
331         SummaryLine {
332             inner: iter,
333             started: false,
334             depth: 0,
335         }
336     }
337 }
338
339 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
340     type Item = Event<'a>;
341
342     fn next(&mut self) -> Option<Self::Item> {
343         if self.started && self.depth == 0 {
344             return None;
345         }
346         if !self.started {
347             self.started = true;
348         }
349         let event = self.inner.next();
350         match event {
351             Some(Event::Start(..)) => self.depth += 1,
352             Some(Event::End(..)) => self.depth -= 1,
353             _ => {}
354         }
355         event
356     }
357 }
358
359 /// Moves all footnote definitions to the end and add back links to the
360 /// references.
361 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
362     inner: I,
363     footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
364 }
365
366 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
367     fn new(iter: I) -> Self {
368         Footnotes {
369             inner: iter,
370             footnotes: HashMap::new(),
371         }
372     }
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))
377     }
378 }
379
380 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
381     type Item = Event<'a>;
382
383     fn next(&mut self) -> Option<Self::Item> {
384         loop {
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}\
389                                              </a></sup>",
390                                             (*entry).1);
391                     return Some(Event::Html(reference.into()));
392                 }
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 {
397                             break;
398                         }
399                         content.push(event);
400                     }
401                     let entry = self.get_entry(&def);
402                     (*entry).0 = content;
403                 }
404                 Some(e) => return Some(e),
405                 None => {
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() {
414                                 content.pop();
415                                 is_paragraph = true;
416                             }
417                             html::push_html(&mut ret, content.into_iter());
418                             write!(ret,
419                                    "&nbsp;<a href=\"#fnref{}\" rev=\"footnote\">↩</a>",
420                                    id).unwrap();
421                             if is_paragraph {
422                                 ret.push_str("</p>");
423                             }
424                             ret.push_str("</li>");
425                         }
426                         ret.push_str("</ol></div>");
427                         return Some(Event::Html(ret.into()));
428                     } else {
429                         return None;
430                     }
431                 }
432             }
433         }
434     }
435 }
436
437 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
438     tests.set_position(position);
439
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() {
445         match event {
446             Event::Start(Tag::CodeBlock(s)) => {
447                 let block_info = if s.is_empty() {
448                     LangString::all_false()
449                 } else {
450                     LangString::parse(&*s)
451                 };
452                 if !block_info.rust {
453                     continue
454                 }
455                 let mut test_s = String::new();
456                 let mut offset = None;
457                 loop {
458                     let event = parser.next();
459                     if let Some(event) = event {
460                         match event {
461                             Event::End(Tag::CodeBlock(_)) => break,
462                             Event::Text(ref s) => {
463                                 test_s.push_str(s);
464                                 if offset.is_none() {
465                                     offset = Some(parser.get_offset());
466                                 }
467                             }
468                             _ => {}
469                         }
470                     } else {
471                         break 'main;
472                     }
473                 }
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;
486                 } else {
487                     break;
488                 }
489             }
490             Event::Start(Tag::Header(level)) => {
491                 register_header = Some(level as u32);
492             }
493             Event::Text(ref s) if register_header.is_some() => {
494                 let level = register_header.unwrap();
495                 if s.is_empty() {
496                     tests.register_header("", level);
497                 } else {
498                     tests.register_header(s, level);
499                 }
500                 register_header = None;
501             }
502             _ => {}
503         }
504     }
505 }
506
507 #[derive(Eq, PartialEq, Clone, Debug)]
508 struct LangString {
509     original: String,
510     should_panic: bool,
511     no_run: bool,
512     ignore: bool,
513     rust: bool,
514     test_harness: bool,
515     compile_fail: bool,
516     error_codes: Vec<String>,
517     allow_fail: bool,
518 }
519
520 impl LangString {
521     fn all_false() -> LangString {
522         LangString {
523             original: String::new(),
524             should_panic: false,
525             no_run: false,
526             ignore: false,
527             rust: true,  // NB This used to be `notrust = false`
528             test_harness: false,
529             compile_fail: false,
530             error_codes: Vec::new(),
531             allow_fail: false,
532         }
533     }
534
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;
542         }
543
544         data.original = string.to_owned();
545         let tokens = string.split(|c: char|
546             !(c == '_' || c == '-' || c.is_alphanumeric())
547         );
548
549         for token in tokens {
550             match token.trim() {
551                 "" => {},
552                 "should_panic" => {
553                     data.should_panic = true;
554                     seen_rust_tags = seen_other_tags == false;
555                 }
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; }
560                 "test_harness" => {
561                     data.test_harness = true;
562                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
563                 }
564                 "compile_fail" => {
565                     data.compile_fail = true;
566                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
567                     data.no_run = true;
568                 }
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;
573                     } else {
574                         seen_other_tags = true;
575                     }
576                 }
577                 _ => { seen_other_tags = true }
578             }
579         }
580
581         data.rust &= !seen_other_tags || seen_rust_tags;
582
583         data
584     }
585 }
586
587 impl<'a> fmt::Display for Markdown<'a> {
588     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
589         let Markdown(md, links) = *self;
590
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);
596
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()))
600             } else {
601                 None
602             }
603         };
604
605         let p = Parser::new_with_broken_link_callback(md, opts, Some(&replacer));
606
607         let mut s = String::with_capacity(md.len() * 3 / 2);
608
609         html::push_html(&mut s,
610                         Footnotes::new(
611                             CodeBlocks::new(
612                                 LinkReplacer::new(
613                                     HeadingLinks::new(p, None),
614                                     links))));
615
616         fmt.write_str(&s)
617     }
618 }
619
620 impl<'a> fmt::Display for MarkdownWithToc<'a> {
621     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
622         let MarkdownWithToc(md) = *self;
623
624         let mut opts = Options::empty();
625         opts.insert(OPTION_ENABLE_TABLES);
626         opts.insert(OPTION_ENABLE_FOOTNOTES);
627
628         let p = Parser::new_ext(md, opts);
629
630         let mut s = String::with_capacity(md.len() * 3 / 2);
631
632         let mut toc = TocBuilder::new();
633
634         html::push_html(&mut s,
635                         Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, Some(&mut toc)))));
636
637         write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
638
639         fmt.write_str(&s)
640     }
641 }
642
643 impl<'a> fmt::Display for MarkdownHtml<'a> {
644     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
645         let MarkdownHtml(md) = *self;
646
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);
652
653         let p = Parser::new_ext(md, opts);
654
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),
658             _ => event
659         });
660
661         let mut s = String::with_capacity(md.len() * 3 / 2);
662
663         html::push_html(&mut s,
664                         Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
665
666         fmt.write_str(&s)
667     }
668 }
669
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(()) }
675
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()))
679             } else {
680                 None
681             }
682         };
683
684         let p = Parser::new_with_broken_link_callback(md, Options::empty(),
685                                                       Some(&replacer));
686
687         let mut s = String::new();
688
689         html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
690
691         fmt.write_str(&s)
692     }
693 }
694
695 pub fn plain_summary_line(md: &str) -> String {
696     struct ParserWrapper<'a> {
697         inner: Parser<'a>,
698         is_in: isize,
699         is_first: bool,
700     }
701
702     impl<'a> Iterator for ParserWrapper<'a> {
703         type Item = String;
704
705         fn next(&mut self) -> Option<String> {
706             let next_event = self.inner.next();
707             if next_event.is_none() {
708                 return None
709             }
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),
718                 _ => (None, 0),
719             };
720             if is_in > 0 || (is_in < 0 && self.is_in > 0) {
721                 self.is_in += is_in;
722             }
723             if ret.is_some() {
724                 self.is_first = false;
725                 ret
726             } else {
727                 Some(String::new())
728             }
729         }
730     }
731     let mut s = String::with_capacity(md.len() * 3 / 2);
732     let mut p = ParserWrapper {
733         inner: Parser::new(md),
734         is_in: 0,
735         is_first: true,
736     };
737     while let Some(t) = p.next() {
738         if !t.is_empty() {
739             s.push_str(&t);
740         }
741     }
742     s
743 }
744
745 pub fn markdown_links(md: &str) -> Vec<String> {
746     if md.is_empty() {
747         return vec![];
748     }
749
750     let mut opts = Options::empty();
751     opts.insert(OPTION_ENABLE_TABLES);
752     opts.insert(OPTION_ENABLE_FOOTNOTES);
753
754     let mut links = vec![];
755     let shortcut_links = RefCell::new(vec![]);
756
757     {
758         let push = |_: &str, s: &str| {
759             shortcut_links.borrow_mut().push(s.to_owned());
760             None
761         };
762         let p = Parser::new_with_broken_link_callback(md, opts,
763             Some(&push));
764
765         let iter = Footnotes::new(HeadingLinks::new(p, None));
766
767         for ev in iter {
768             if let Event::Start(Tag::Link(dest, _)) = ev {
769                 debug!("found link: {}", dest);
770                 links.push(dest.into_owned());
771             }
772         }
773     }
774
775     let mut shortcut_links = shortcut_links.into_inner();
776     links.extend(shortcut_links.drain(..));
777
778     links
779 }
780
781 #[cfg(test)]
782 mod tests {
783     use super::{LangString, Markdown, MarkdownHtml};
784     use super::plain_summary_line;
785     use html::render::reset_ids;
786
787     #[test]
788     fn test_lang_string_parse() {
789         fn t(s: &str,
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 {
793                 should_panic,
794                 no_run,
795                 ignore,
796                 rust,
797                 test_harness,
798                 compile_fail,
799                 error_codes,
800                 original: s.to_owned(),
801                 allow_fail,
802             })
803         }
804
805         fn v() -> Vec<String> {
806             Vec::new()
807         }
808
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());
826     }
827
828     #[test]
829     fn issue_17736() {
830         let markdown = "# title";
831         format!("{}", Markdown(markdown, &[]));
832         reset_ids(true);
833     }
834
835     #[test]
836     fn test_header() {
837         fn t(input: &str, expect: &str) {
838             let output = format!("{}", Markdown(input, &[]));
839             assert_eq!(output, expect, "original: {}", input);
840             reset_ids(true);
841         }
842
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!?!&amp; -<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> &amp; *bar?!*  \
854           <em><code>baz</code></em> ❤ #qux</a></h4>");
855     }
856
857     #[test]
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);
862         }
863
864         let test = || {
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>");
877         };
878         test();
879         reset_ids(true);
880         test();
881     }
882
883     #[test]
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);
888         }
889
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");
896     }
897
898     #[test]
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);
903         }
904
905         t("`Struct<'a, T>`", "<p><code>Struct&lt;'a, T&gt;</code></p>\n");
906         t("Struct<'a, T>", "<p>Struct&lt;'a, T&gt;</p>\n");
907         t("Struct<br>", "<p>Struct&lt;br&gt;</p>\n");
908     }
909 }