]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
86657aa000b0daff87f9aa1d39fdacb998067c95
[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::{RenderType, Markdown};
22 //!
23 //! let s = "My *markdown* _text_";
24 //! let html = format!("{}", Markdown(s, RenderType::Pulldown));
25 //! // ... something using html
26 //! ```
27
28 #![allow(non_camel_case_types)]
29
30 use libc;
31 use std::slice;
32
33 use std::cell::RefCell;
34 use std::collections::{HashMap, VecDeque};
35 use std::default::Default;
36 use std::fmt::{self, Write};
37 use std::str;
38 use syntax::feature_gate::UnstableFeatures;
39 use syntax::codemap::Span;
40
41 use html::render::derive_id;
42 use html::toc::TocBuilder;
43 use html::highlight;
44 use html::escape::Escape;
45 use test;
46
47 use pulldown_cmark::{html, Event, Tag, Parser};
48 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
49
50 #[derive(PartialEq, Debug, Clone, Copy)]
51 pub enum RenderType {
52     Hoedown,
53     Pulldown,
54 }
55
56 /// A unit struct which has the `fmt::Display` trait implemented. When
57 /// formatted, this struct will emit the HTML corresponding to the rendered
58 /// version of the contained markdown string.
59 /// The second parameter is a list of link replacements
60 // The third parameter is whether we need a shorter version or not.
61 pub struct Markdown<'a>(pub &'a str, pub &'a [(String, String)], pub RenderType);
62 /// A unit struct like `Markdown`, that renders the markdown with a
63 /// table of contents.
64 pub struct MarkdownWithToc<'a>(pub &'a str, pub RenderType);
65 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
66 pub struct MarkdownHtml<'a>(pub &'a str, pub RenderType);
67 /// A unit struct like `Markdown`, that renders only the first paragraph.
68 pub struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [(String, String)]);
69
70 /// Controls whether a line will be hidden or shown in HTML output.
71 ///
72 /// All lines are used in documentation tests.
73 enum Line<'a> {
74     Hidden(&'a str),
75     Shown(&'a str),
76 }
77
78 impl<'a> Line<'a> {
79     fn for_html(self) -> Option<&'a str> {
80         match self {
81             Line::Shown(l) => Some(l),
82             Line::Hidden(_) => None,
83         }
84     }
85
86     fn for_code(self) -> &'a str {
87         match self {
88             Line::Shown(l) |
89             Line::Hidden(l) => l,
90         }
91     }
92 }
93
94 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
95 // have no easy way of removing a potential single space after the hashes, which
96 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
97 // order to fix it we'd have to iterate to find the first non-# character, and
98 // then reallocate to remove it; which would make us return a String.
99 fn map_line(s: &str) -> Line {
100     let trimmed = s.trim();
101     if trimmed.starts_with("##") {
102         Line::Shown(&trimmed[1..])
103     } else if trimmed.starts_with("# ") {
104         // # text
105         Line::Hidden(&trimmed[2..])
106     } else if trimmed == "#" {
107         // We cannot handle '#text' because it could be #[attr].
108         Line::Hidden("")
109     } else {
110         Line::Shown(s)
111     }
112 }
113
114 /// Returns a new string with all consecutive whitespace collapsed into
115 /// single spaces.
116 ///
117 /// Any leading or trailing whitespace will be trimmed.
118 fn collapse_whitespace(s: &str) -> String {
119     s.split_whitespace().collect::<Vec<_>>().join(" ")
120 }
121
122 /// Convert chars from a title for an id.
123 ///
124 /// "Hello, world!" -> "hello-world"
125 fn slugify(c: char) -> Option<char> {
126     if c.is_alphanumeric() || c == '-' || c == '_' {
127         if c.is_ascii() {
128             Some(c.to_ascii_lowercase())
129         } else {
130             Some(c)
131         }
132     } else if c.is_whitespace() && c.is_ascii() {
133         Some('-')
134     } else {
135         None
136     }
137 }
138
139 // Information about the playground if a URL has been specified, containing an
140 // optional crate name and the URL.
141 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
142     RefCell::new(None)
143 });
144
145 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
146 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
147     inner: I,
148 }
149
150 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
151     fn new(iter: I) -> Self {
152         CodeBlocks {
153             inner: iter,
154         }
155     }
156 }
157
158 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
159     type Item = Event<'a>;
160
161     fn next(&mut self) -> Option<Self::Item> {
162         let event = self.inner.next();
163         let compile_fail;
164         let ignore;
165         if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
166             let parse_result = LangString::parse(&lang);
167             if !parse_result.rust {
168                 return Some(Event::Start(Tag::CodeBlock(lang)));
169             }
170             compile_fail = parse_result.compile_fail;
171             ignore = parse_result.ignore;
172         } else {
173             return event;
174         }
175
176         let mut origtext = String::new();
177         for event in &mut self.inner {
178             match event {
179                 Event::End(Tag::CodeBlock(..)) => break,
180                 Event::Text(ref s) => {
181                     origtext.push_str(s);
182                 }
183                 _ => {}
184             }
185         }
186         let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
187         let text = lines.collect::<Vec<&str>>().join("\n");
188         PLAYGROUND.with(|play| {
189             // insert newline to clearly separate it from the
190             // previous block so we can shorten the html output
191             let mut s = String::from("\n");
192             let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
193                 if url.is_empty() {
194                     return None;
195                 }
196                 let test = origtext.lines()
197                     .map(|l| map_line(l).for_code())
198                     .collect::<Vec<&str>>().join("\n");
199                 let krate = krate.as_ref().map(|s| &**s);
200                 let (test, _) = test::make_test(&test, krate, false,
201                                            &Default::default());
202                 let channel = if test.contains("#![feature(") {
203                     "&amp;version=nightly"
204                 } else {
205                     ""
206                 };
207                 // These characters don't need to be escaped in a URI.
208                 // FIXME: use a library function for percent encoding.
209                 fn dont_escape(c: u8) -> bool {
210                     (b'a' <= c && c <= b'z') ||
211                     (b'A' <= c && c <= b'Z') ||
212                     (b'0' <= c && c <= b'9') ||
213                     c == b'-' || c == b'_' || c == b'.' ||
214                     c == b'~' || c == b'!' || c == b'\'' ||
215                     c == b'(' || c == b')' || c == b'*'
216                 }
217                 let mut test_escaped = String::new();
218                 for b in test.bytes() {
219                     if dont_escape(b) {
220                         test_escaped.push(char::from(b));
221                     } else {
222                         write!(test_escaped, "%{:02X}", b).unwrap();
223                     }
224                 }
225                 Some(format!(
226                     r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
227                     url, test_escaped, channel
228                 ))
229             });
230             let tooltip = if ignore {
231                 Some(("This example is not tested", "ignore"))
232             } else if compile_fail {
233                 Some(("This example deliberately fails to compile", "compile_fail"))
234             } else {
235                 None
236             };
237             s.push_str(&highlight::render_with_highlighting(
238                         &text,
239                         Some(&format!("rust-example-rendered{}",
240                                       if ignore { " ignore" }
241                                       else if compile_fail { " compile_fail" }
242                                       else { "" })),
243                         None,
244                         playground_button.as_ref().map(String::as_str),
245                         tooltip));
246             Some(Event::Html(s.into()))
247         })
248     }
249 }
250
251 /// Make headings links with anchor ids and build up TOC.
252 struct LinkReplacer<'a, 'b, I: Iterator<Item = Event<'a>>> {
253     inner: I,
254     links: &'b [(String, String)]
255 }
256
257 impl<'a, 'b, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, 'b, I> {
258     fn new(iter: I, links: &'b [(String, String)]) -> Self {
259         LinkReplacer {
260             inner: iter,
261             links
262         }
263     }
264 }
265
266 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, 'b, I> {
267     type Item = Event<'a>;
268
269     fn next(&mut self) -> Option<Self::Item> {
270         let event = self.inner.next();
271         if let Some(Event::Start(Tag::Link(dest, text))) = event {
272             if let Some(&(_, ref replace)) = self.links.into_iter().find(|link| &*link.0 == &*dest)
273             {
274                 Some(Event::Start(Tag::Link(replace.to_owned().into(), text)))
275             } else {
276                 Some(Event::Start(Tag::Link(dest, text)))
277             }
278         } else {
279             event
280         }
281     }
282 }
283
284 /// Make headings links with anchor ids and build up TOC.
285 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
286     inner: I,
287     toc: Option<&'b mut TocBuilder>,
288     buf: VecDeque<Event<'a>>,
289 }
290
291 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
292     fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
293         HeadingLinks {
294             inner: iter,
295             toc,
296             buf: VecDeque::new(),
297         }
298     }
299 }
300
301 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
302     type Item = Event<'a>;
303
304     fn next(&mut self) -> Option<Self::Item> {
305         if let Some(e) = self.buf.pop_front() {
306             return Some(e);
307         }
308
309         let event = self.inner.next();
310         if let Some(Event::Start(Tag::Header(level))) = event {
311             let mut id = String::new();
312             for event in &mut self.inner {
313                 match event {
314                     Event::End(Tag::Header(..)) => break,
315                     Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
316                     _ => {},
317                 }
318                 self.buf.push_back(event);
319             }
320             let id = derive_id(id);
321
322             if let Some(ref mut builder) = self.toc {
323                 let mut html_header = String::new();
324                 html::push_html(&mut html_header, self.buf.iter().cloned());
325                 let sec = builder.push(level as u32, html_header, id.clone());
326                 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
327             }
328
329             self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
330
331             let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
332                                       <a href=\"#{id}\">",
333                                      id = id,
334                                      level = level);
335             return Some(Event::InlineHtml(start_tags.into()));
336         }
337         event
338     }
339 }
340
341 /// Extracts just the first paragraph.
342 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
343     inner: I,
344     started: bool,
345     depth: u32,
346 }
347
348 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
349     fn new(iter: I) -> Self {
350         SummaryLine {
351             inner: iter,
352             started: false,
353             depth: 0,
354         }
355     }
356 }
357
358 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
359     type Item = Event<'a>;
360
361     fn next(&mut self) -> Option<Self::Item> {
362         if self.started && self.depth == 0 {
363             return None;
364         }
365         if !self.started {
366             self.started = true;
367         }
368         let event = self.inner.next();
369         match event {
370             Some(Event::Start(..)) => self.depth += 1,
371             Some(Event::End(..)) => self.depth -= 1,
372             _ => {}
373         }
374         event
375     }
376 }
377
378 /// Moves all footnote definitions to the end and add back links to the
379 /// references.
380 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
381     inner: I,
382     footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
383 }
384
385 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
386     fn new(iter: I) -> Self {
387         Footnotes {
388             inner: iter,
389             footnotes: HashMap::new(),
390         }
391     }
392     fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
393         let new_id = self.footnotes.keys().count() + 1;
394         let key = key.to_owned();
395         self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
396     }
397 }
398
399 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
400     type Item = Event<'a>;
401
402     fn next(&mut self) -> Option<Self::Item> {
403         loop {
404             match self.inner.next() {
405                 Some(Event::FootnoteReference(ref reference)) => {
406                     let entry = self.get_entry(&reference);
407                     let reference = format!("<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}\
408                                              </a></sup>",
409                                             (*entry).1);
410                     return Some(Event::Html(reference.into()));
411                 }
412                 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
413                     let mut content = Vec::new();
414                     for event in &mut self.inner {
415                         if let Event::End(Tag::FootnoteDefinition(..)) = event {
416                             break;
417                         }
418                         content.push(event);
419                     }
420                     let entry = self.get_entry(&def);
421                     (*entry).0 = content;
422                 }
423                 Some(e) => return Some(e),
424                 None => {
425                     if !self.footnotes.is_empty() {
426                         let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
427                         v.sort_by(|a, b| a.1.cmp(&b.1));
428                         let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
429                         for (mut content, id) in v {
430                             write!(ret, "<li id=\"fn{}\">", id).unwrap();
431                             let mut is_paragraph = false;
432                             if let Some(&Event::End(Tag::Paragraph)) = content.last() {
433                                 content.pop();
434                                 is_paragraph = true;
435                             }
436                             html::push_html(&mut ret, content.into_iter());
437                             write!(ret,
438                                    "&nbsp;<a href=\"#fnref{}\" rev=\"footnote\">↩</a>",
439                                    id).unwrap();
440                             if is_paragraph {
441                                 ret.push_str("</p>");
442                             }
443                             ret.push_str("</li>");
444                         }
445                         ret.push_str("</ol></div>");
446                         return Some(Event::Html(ret.into()));
447                     } else {
448                         return None;
449                     }
450                 }
451             }
452         }
453     }
454 }
455
456 const DEF_OUNIT: libc::size_t = 64;
457 const HOEDOWN_EXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 11;
458 const HOEDOWN_EXT_TABLES: libc::c_uint = 1 << 0;
459 const HOEDOWN_EXT_FENCED_CODE: libc::c_uint = 1 << 1;
460 const HOEDOWN_EXT_AUTOLINK: libc::c_uint = 1 << 3;
461 const HOEDOWN_EXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
462 const HOEDOWN_EXT_SUPERSCRIPT: libc::c_uint = 1 << 8;
463 const HOEDOWN_EXT_FOOTNOTES: libc::c_uint = 1 << 2;
464 const HOEDOWN_HTML_ESCAPE: libc::c_uint = 1 << 1;
465
466 const HOEDOWN_EXTENSIONS: libc::c_uint =
467     HOEDOWN_EXT_NO_INTRA_EMPHASIS | HOEDOWN_EXT_TABLES |
468     HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_AUTOLINK |
469     HOEDOWN_EXT_STRIKETHROUGH | HOEDOWN_EXT_SUPERSCRIPT |
470     HOEDOWN_EXT_FOOTNOTES;
471
472 enum hoedown_document {}
473
474 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
475                                  *const hoedown_buffer, *const hoedown_renderer_data,
476                                  libc::size_t);
477
478 type blockquotefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
479                                   *const hoedown_renderer_data, libc::size_t);
480
481 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
482                               libc::c_int, *const hoedown_renderer_data,
483                               libc::size_t);
484
485 type blockhtmlfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
486                                  *const hoedown_renderer_data, libc::size_t);
487
488 type codespanfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
489                                 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
490
491 type linkfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
492                              *const hoedown_buffer, *const hoedown_buffer,
493                              *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
494
495 type entityfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
496                                *const hoedown_renderer_data, libc::size_t);
497
498 type normaltextfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
499                                   *const hoedown_renderer_data, libc::size_t);
500
501 #[repr(C)]
502 struct hoedown_renderer_data {
503     opaque: *mut libc::c_void,
504 }
505
506 #[repr(C)]
507 struct hoedown_renderer {
508     opaque: *mut libc::c_void,
509
510     blockcode: Option<blockcodefn>,
511     blockquote: Option<blockquotefn>,
512     header: Option<headerfn>,
513
514     other_block_level_callbacks: [libc::size_t; 11],
515
516     blockhtml: Option<blockhtmlfn>,
517
518     /* span level callbacks - NULL or return 0 prints the span verbatim */
519     autolink: libc::size_t, // unused
520     codespan: Option<codespanfn>,
521     other_span_level_callbacks_1: [libc::size_t; 7],
522     link: Option<linkfn>,
523     other_span_level_callbacks_2: [libc::size_t; 6],
524
525     /* low level callbacks - NULL copies input directly into the output */
526     entity: Option<entityfn>,
527     normal_text: Option<normaltextfn>,
528
529     /* header and footer */
530     other_callbacks: [libc::size_t; 2],
531 }
532
533 #[repr(C)]
534 struct hoedown_html_renderer_state {
535     opaque: *mut libc::c_void,
536     toc_data: html_toc_data,
537     flags: libc::c_uint,
538     link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
539                                           *const hoedown_buffer,
540                                           *const hoedown_renderer_data)>,
541 }
542
543 #[repr(C)]
544 struct html_toc_data {
545     header_count: libc::c_int,
546     current_level: libc::c_int,
547     level_offset: libc::c_int,
548     nesting_level: libc::c_int,
549 }
550
551 #[repr(C)]
552 struct hoedown_buffer {
553     data: *const u8,
554     size: libc::size_t,
555     asize: libc::size_t,
556     unit: libc::size_t,
557 }
558
559 struct MyOpaque {
560     dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
561                            *const hoedown_buffer, *const hoedown_renderer_data,
562                            libc::size_t),
563     toc_builder: Option<TocBuilder>,
564     links: Option<Vec<String>>,
565 }
566
567 extern {
568     fn hoedown_html_renderer_new(render_flags: libc::c_uint,
569                                  nesting_level: libc::c_int)
570         -> *mut hoedown_renderer;
571     fn hoedown_html_renderer_free(renderer: *mut hoedown_renderer);
572
573     fn hoedown_document_new(rndr: *const hoedown_renderer,
574                             extensions: libc::c_uint,
575                             max_nesting: libc::size_t) -> *mut hoedown_document;
576     fn hoedown_document_render(doc: *mut hoedown_document,
577                                ob: *mut hoedown_buffer,
578                                document: *const u8,
579                                doc_size: libc::size_t);
580     fn hoedown_document_free(md: *mut hoedown_document);
581
582     fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer;
583     fn hoedown_buffer_free(b: *mut hoedown_buffer);
584     fn hoedown_buffer_put(b: *mut hoedown_buffer, c: *const u8, len: libc::size_t);
585 }
586
587 impl hoedown_buffer {
588     fn as_bytes(&self) -> &[u8] {
589         unsafe { slice::from_raw_parts(self.data, self.size as usize) }
590     }
591 }
592
593 extern fn hoedown_block(ob: *mut hoedown_buffer, orig_text: *const hoedown_buffer,
594                         lang: *const hoedown_buffer, data: *const hoedown_renderer_data,
595                         line: libc::size_t) {
596     unsafe {
597         if orig_text.is_null() { return }
598
599         let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
600         let my_opaque: &MyOpaque = &*((*opaque).opaque as *const MyOpaque);
601         let text = (*orig_text).as_bytes();
602         let origtext = str::from_utf8(text).unwrap();
603         let origtext = origtext.trim_left();
604         debug!("docblock: ==============\n{:?}\n=======", text);
605         let mut compile_fail = false;
606         let mut ignore = false;
607
608         let rendered = if lang.is_null() || origtext.is_empty() {
609             false
610         } else {
611             let rlang = (*lang).as_bytes();
612             let rlang = str::from_utf8(rlang).unwrap();
613             let parse_result = LangString::parse(rlang);
614             compile_fail = parse_result.compile_fail;
615             ignore = parse_result.ignore;
616             if !parse_result.rust {
617                 (my_opaque.dfltblk)(ob, orig_text, lang,
618                                     opaque as *const hoedown_renderer_data,
619                                     line);
620                 true
621             } else {
622                 false
623             }
624         };
625
626         let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
627         let text = lines.collect::<Vec<&str>>().join("\n");
628         if rendered { return }
629         PLAYGROUND.with(|play| {
630             // insert newline to clearly separate it from the
631             // previous block so we can shorten the html output
632             let mut s = String::from("\n");
633             let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
634                 if url.is_empty() {
635                     return None;
636                 }
637                 let test = origtext.lines()
638                     .map(|l| map_line(l).for_code())
639                     .collect::<Vec<&str>>().join("\n");
640                 let krate = krate.as_ref().map(|s| &**s);
641                 let (test, _) = test::make_test(&test, krate, false,
642                                                 &Default::default());
643                 let channel = if test.contains("#![feature(") {
644                     "&amp;version=nightly"
645                 } else {
646                     ""
647                 };
648                 // These characters don't need to be escaped in a URI.
649                 // FIXME: use a library function for percent encoding.
650                 fn dont_escape(c: u8) -> bool {
651                     (b'a' <= c && c <= b'z') ||
652                     (b'A' <= c && c <= b'Z') ||
653                     (b'0' <= c && c <= b'9') ||
654                     c == b'-' || c == b'_' || c == b'.' ||
655                     c == b'~' || c == b'!' || c == b'\'' ||
656                     c == b'(' || c == b')' || c == b'*'
657                 }
658                 let mut test_escaped = String::new();
659                 for b in test.bytes() {
660                     if dont_escape(b) {
661                         test_escaped.push(char::from(b));
662                     } else {
663                         write!(test_escaped, "%{:02X}", b).unwrap();
664                     }
665                 }
666                 Some(format!(
667                     r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
668                     url, test_escaped, channel
669                 ))
670             });
671             let tooltip = if ignore {
672                 Some(("This example is not tested", "ignore"))
673             } else if compile_fail {
674                 Some(("This example deliberately fails to compile", "compile_fail"))
675             } else {
676                 None
677             };
678             s.push_str(&highlight::render_with_highlighting(
679                            &text,
680                            Some(&format!("rust-example-rendered{}",
681                                          if ignore { " ignore" }
682                                          else if compile_fail { " compile_fail" }
683                                          else { "" })),
684                            None,
685                            playground_button.as_ref().map(String::as_str),
686                            tooltip));
687             hoedown_buffer_put(ob, s.as_ptr(), s.len());
688         })
689     }
690 }
691
692 extern fn hoedown_header(ob: *mut hoedown_buffer, text: *const hoedown_buffer,
693                          level: libc::c_int, data: *const hoedown_renderer_data,
694                          _: libc::size_t) {
695     // hoedown does this, we may as well too
696     unsafe { hoedown_buffer_put(ob, "\n".as_ptr(), 1); }
697
698     // Extract the text provided
699     let s = if text.is_null() {
700         "".to_owned()
701     } else {
702         let s = unsafe { (*text).as_bytes() };
703         str::from_utf8(&s).unwrap().to_owned()
704     };
705
706     // Discard '<em>', '<code>' tags and some escaped characters,
707     // transform the contents of the header into a hyphenated string
708     // without non-alphanumeric characters other than '-' and '_'.
709     //
710     // This is a terrible hack working around how hoedown gives us rendered
711     // html for text rather than the raw text.
712     let mut id = s.clone();
713     let repl_sub = vec!["<em>", "</em>", "<code>", "</code>",
714                         "<strong>", "</strong>",
715                         "&lt;", "&gt;", "&amp;", "&#39;", "&quot;"];
716     for sub in repl_sub {
717         id = id.replace(sub, "");
718     }
719     let id = id.chars().filter_map(|c| {
720         if c.is_alphanumeric() || c == '-' || c == '_' {
721             if c.is_ascii() {
722                 Some(c.to_ascii_lowercase())
723             } else {
724                 Some(c)
725             }
726         } else if c.is_whitespace() && c.is_ascii() {
727             Some('-')
728         } else {
729             None
730         }
731     }).collect::<String>();
732
733     let opaque = unsafe { (*data).opaque as *mut hoedown_html_renderer_state };
734     let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
735
736     let id = derive_id(id);
737
738     let sec = opaque.toc_builder.as_mut().map_or("".to_owned(), |builder| {
739         format!("{} ", builder.push(level as u32, s.clone(), id.clone()))
740     });
741
742     // Render the HTML
743     let text = format!("<h{lvl} id='{id}' class='section-header'>\
744                        <a href='#{id}'>{sec}{}</a></h{lvl}>",
745                        s, lvl = level, id = id, sec = sec);
746
747     unsafe { hoedown_buffer_put(ob, text.as_ptr(), text.len()); }
748 }
749
750 extern fn hoedown_codespan(
751     ob: *mut hoedown_buffer,
752     text: *const hoedown_buffer,
753     _: *const hoedown_renderer_data,
754     _: libc::size_t
755 ) -> libc::c_int {
756     let content = if text.is_null() {
757         "".to_owned()
758     } else {
759         let bytes = unsafe { (*text).as_bytes() };
760         let s = str::from_utf8(bytes).unwrap();
761         collapse_whitespace(s)
762     };
763
764     let content = format!("<code>{}</code>", Escape(&content));
765     unsafe {
766         hoedown_buffer_put(ob, content.as_ptr(), content.len());
767     }
768     // Return anything except 0, which would mean "also print the code span verbatim".
769     1
770 }
771
772 pub fn render(w: &mut fmt::Formatter,
773               s: &str,
774               print_toc: bool,
775               html_flags: libc::c_uint) -> fmt::Result {
776
777     unsafe {
778         let ob = hoedown_buffer_new(DEF_OUNIT);
779         let renderer = hoedown_html_renderer_new(html_flags, 0);
780         let mut opaque = MyOpaque {
781             dfltblk: (*renderer).blockcode.unwrap(),
782             toc_builder: if print_toc {Some(TocBuilder::new())} else {None},
783             links: None,
784         };
785         (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
786                 = &mut opaque as *mut _ as *mut libc::c_void;
787         (*renderer).blockcode = Some(hoedown_block);
788         (*renderer).header = Some(hoedown_header);
789         (*renderer).codespan = Some(hoedown_codespan);
790
791         let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
792         hoedown_document_render(document, ob, s.as_ptr(),
793                                 s.len() as libc::size_t);
794         hoedown_document_free(document);
795
796         hoedown_html_renderer_free(renderer);
797
798         let mut ret = opaque.toc_builder.map_or(Ok(()), |builder| {
799             write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
800         });
801
802         if ret.is_ok() {
803             let buf = (*ob).as_bytes();
804             ret = w.write_str(str::from_utf8(buf).unwrap());
805         }
806         hoedown_buffer_free(ob);
807         ret
808     }
809 }
810
811 pub fn old_find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
812     extern fn block(_ob: *mut hoedown_buffer,
813                     text: *const hoedown_buffer,
814                     lang: *const hoedown_buffer,
815                     data: *const hoedown_renderer_data,
816                     line: libc::size_t) {
817         unsafe {
818             if text.is_null() { return }
819             let block_info = if lang.is_null() {
820                 LangString::all_false()
821             } else {
822                 let lang = (*lang).as_bytes();
823                 let s = str::from_utf8(lang).unwrap();
824                 LangString::parse(s)
825             };
826             if !block_info.rust { return }
827             let text = (*text).as_bytes();
828             let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
829             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
830             let text = str::from_utf8(text).unwrap();
831             let lines = text.lines().map(|l| map_line(l).for_code());
832             let text = lines.collect::<Vec<&str>>().join("\n");
833             let filename = tests.get_filename();
834
835             if tests.render_type == RenderType::Hoedown {
836                 let line = tests.get_line() + line;
837                 tests.add_test(text.to_owned(),
838                                block_info.should_panic, block_info.no_run,
839                                block_info.ignore, block_info.test_harness,
840                                block_info.compile_fail, block_info.error_codes,
841                                line, filename, block_info.allow_fail);
842             } else {
843                 tests.add_old_test(text, filename);
844             }
845         }
846     }
847
848     extern fn header(_ob: *mut hoedown_buffer,
849                      text: *const hoedown_buffer,
850                      level: libc::c_int, data: *const hoedown_renderer_data,
851                      _: libc::size_t) {
852         unsafe {
853             let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
854             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
855             if text.is_null() {
856                 tests.register_header("", level as u32);
857             } else {
858                 let text = (*text).as_bytes();
859                 let text = str::from_utf8(text).unwrap();
860                 tests.register_header(text, level as u32);
861             }
862         }
863     }
864
865     tests.set_position(position);
866     unsafe {
867         let ob = hoedown_buffer_new(DEF_OUNIT);
868         let renderer = hoedown_html_renderer_new(0, 0);
869         (*renderer).blockcode = Some(block);
870         (*renderer).header = Some(header);
871         (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
872                 = tests as *mut _ as *mut libc::c_void;
873
874         let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
875         hoedown_document_render(document, ob, doc.as_ptr(),
876                                 doc.len() as libc::size_t);
877         hoedown_document_free(document);
878
879         hoedown_html_renderer_free(renderer);
880         hoedown_buffer_free(ob);
881     }
882 }
883
884 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
885     tests.set_position(position);
886
887     let mut parser = Parser::new(doc);
888     let mut prev_offset = 0;
889     let mut nb_lines = 0;
890     let mut register_header = None;
891     'main: while let Some(event) = parser.next() {
892         match event {
893             Event::Start(Tag::CodeBlock(s)) => {
894                 let block_info = if s.is_empty() {
895                     LangString::all_false()
896                 } else {
897                     LangString::parse(&*s)
898                 };
899                 if !block_info.rust {
900                     continue
901                 }
902                 let mut test_s = String::new();
903                 let mut offset = None;
904                 loop {
905                     let event = parser.next();
906                     if let Some(event) = event {
907                         match event {
908                             Event::End(Tag::CodeBlock(_)) => break,
909                             Event::Text(ref s) => {
910                                 test_s.push_str(s);
911                                 if offset.is_none() {
912                                     offset = Some(parser.get_offset());
913                                 }
914                             }
915                             _ => {}
916                         }
917                     } else {
918                         break 'main;
919                     }
920                 }
921                 let offset = offset.unwrap_or(0);
922                 let lines = test_s.lines().map(|l| map_line(l).for_code());
923                 let text = lines.collect::<Vec<&str>>().join("\n");
924                 nb_lines += doc[prev_offset..offset].lines().count();
925                 let line = tests.get_line() + (nb_lines - 1);
926                 let filename = tests.get_filename();
927                 tests.add_test(text.to_owned(),
928                                block_info.should_panic, block_info.no_run,
929                                block_info.ignore, block_info.test_harness,
930                                block_info.compile_fail, block_info.error_codes,
931                                line, filename, block_info.allow_fail);
932                 prev_offset = offset;
933             }
934             Event::Start(Tag::Header(level)) => {
935                 register_header = Some(level as u32);
936             }
937             Event::Text(ref s) if register_header.is_some() => {
938                 let level = register_header.unwrap();
939                 if s.is_empty() {
940                     tests.register_header("", level);
941                 } else {
942                     tests.register_header(s, level);
943                 }
944                 register_header = None;
945             }
946             _ => {}
947         }
948     }
949 }
950
951 #[derive(Eq, PartialEq, Clone, Debug)]
952 struct LangString {
953     original: String,
954     should_panic: bool,
955     no_run: bool,
956     ignore: bool,
957     rust: bool,
958     test_harness: bool,
959     compile_fail: bool,
960     error_codes: Vec<String>,
961     allow_fail: bool,
962 }
963
964 impl LangString {
965     fn all_false() -> LangString {
966         LangString {
967             original: String::new(),
968             should_panic: false,
969             no_run: false,
970             ignore: false,
971             rust: true,  // NB This used to be `notrust = false`
972             test_harness: false,
973             compile_fail: false,
974             error_codes: Vec::new(),
975             allow_fail: false,
976         }
977     }
978
979     fn parse(string: &str) -> LangString {
980         let mut seen_rust_tags = false;
981         let mut seen_other_tags = false;
982         let mut data = LangString::all_false();
983         let mut allow_error_code_check = false;
984         if UnstableFeatures::from_environment().is_nightly_build() {
985             allow_error_code_check = true;
986         }
987
988         data.original = string.to_owned();
989         let tokens = string.split(|c: char|
990             !(c == '_' || c == '-' || c.is_alphanumeric())
991         );
992
993         for token in tokens {
994             match token.trim() {
995                 "" => {},
996                 "should_panic" => {
997                     data.should_panic = true;
998                     seen_rust_tags = seen_other_tags == false;
999                 }
1000                 "no_run" => { data.no_run = true; seen_rust_tags = !seen_other_tags; }
1001                 "ignore" => { data.ignore = true; seen_rust_tags = !seen_other_tags; }
1002                 "allow_fail" => { data.allow_fail = true; seen_rust_tags = !seen_other_tags; }
1003                 "rust" => { data.rust = true; seen_rust_tags = true; }
1004                 "test_harness" => {
1005                     data.test_harness = true;
1006                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
1007                 }
1008                 "compile_fail" => {
1009                     data.compile_fail = true;
1010                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
1011                     data.no_run = true;
1012                 }
1013                 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
1014                     if let Ok(_) = x[1..].parse::<u32>() {
1015                         data.error_codes.push(x.to_owned());
1016                         seen_rust_tags = !seen_other_tags || seen_rust_tags;
1017                     } else {
1018                         seen_other_tags = true;
1019                     }
1020                 }
1021                 _ => { seen_other_tags = true }
1022             }
1023         }
1024
1025         data.rust &= !seen_other_tags || seen_rust_tags;
1026
1027         data
1028     }
1029 }
1030
1031 impl<'a> fmt::Display for Markdown<'a> {
1032     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1033         let Markdown(md, links, render_type) = *self;
1034
1035         // This is actually common enough to special-case
1036         if md.is_empty() { return Ok(()) }
1037         if render_type == RenderType::Hoedown {
1038             render(fmt, md, false, 0)
1039         } else {
1040             let mut opts = Options::empty();
1041             opts.insert(OPTION_ENABLE_TABLES);
1042             opts.insert(OPTION_ENABLE_FOOTNOTES);
1043
1044             let p = Parser::new_ext(md, opts);
1045
1046             let mut s = String::with_capacity(md.len() * 3 / 2);
1047
1048             html::push_html(&mut s,
1049                             Footnotes::new(
1050                                 CodeBlocks::new(
1051                                     LinkReplacer::new(
1052                                         HeadingLinks::new(p, None),
1053                                         links))));
1054
1055             fmt.write_str(&s)
1056         }
1057     }
1058 }
1059
1060 impl<'a> fmt::Display for MarkdownWithToc<'a> {
1061     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1062         let MarkdownWithToc(md, render_type) = *self;
1063
1064         if render_type == RenderType::Hoedown {
1065             render(fmt, md, true, 0)
1066         } else {
1067             let mut opts = Options::empty();
1068             opts.insert(OPTION_ENABLE_TABLES);
1069             opts.insert(OPTION_ENABLE_FOOTNOTES);
1070
1071             let p = Parser::new_ext(md, opts);
1072
1073             let mut s = String::with_capacity(md.len() * 3 / 2);
1074
1075             let mut toc = TocBuilder::new();
1076
1077             html::push_html(&mut s,
1078                             Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, Some(&mut toc)))));
1079
1080             write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
1081
1082             fmt.write_str(&s)
1083         }
1084     }
1085 }
1086
1087 impl<'a> fmt::Display for MarkdownHtml<'a> {
1088     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1089         let MarkdownHtml(md, render_type) = *self;
1090
1091         // This is actually common enough to special-case
1092         if md.is_empty() { return Ok(()) }
1093         if render_type == RenderType::Hoedown {
1094             render(fmt, md, false, HOEDOWN_HTML_ESCAPE)
1095         } else {
1096             let mut opts = Options::empty();
1097             opts.insert(OPTION_ENABLE_TABLES);
1098             opts.insert(OPTION_ENABLE_FOOTNOTES);
1099
1100             let p = Parser::new_ext(md, opts);
1101
1102             // Treat inline HTML as plain text.
1103             let p = p.map(|event| match event {
1104                 Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
1105                 _ => event
1106             });
1107
1108             let mut s = String::with_capacity(md.len() * 3 / 2);
1109
1110             html::push_html(&mut s,
1111                             Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
1112
1113             fmt.write_str(&s)
1114         }
1115     }
1116 }
1117
1118 impl<'a> fmt::Display for MarkdownSummaryLine<'a> {
1119     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1120         let MarkdownSummaryLine(md, links) = *self;
1121         // This is actually common enough to special-case
1122         if md.is_empty() { return Ok(()) }
1123
1124         let p = Parser::new(md);
1125
1126         let mut s = String::new();
1127
1128         html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1129
1130         fmt.write_str(&s)
1131     }
1132 }
1133
1134 pub fn plain_summary_line(md: &str) -> String {
1135     struct ParserWrapper<'a> {
1136         inner: Parser<'a>,
1137         is_in: isize,
1138         is_first: bool,
1139     }
1140
1141     impl<'a> Iterator for ParserWrapper<'a> {
1142         type Item = String;
1143
1144         fn next(&mut self) -> Option<String> {
1145             let next_event = self.inner.next();
1146             if next_event.is_none() {
1147                 return None
1148             }
1149             let next_event = next_event.unwrap();
1150             let (ret, is_in) = match next_event {
1151                 Event::Start(Tag::Paragraph) => (None, 1),
1152                 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
1153                 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
1154                 Event::Start(Tag::Header(_)) => (None, 1),
1155                 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
1156                 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
1157                 _ => (None, 0),
1158             };
1159             if is_in > 0 || (is_in < 0 && self.is_in > 0) {
1160                 self.is_in += is_in;
1161             }
1162             if ret.is_some() {
1163                 self.is_first = false;
1164                 ret
1165             } else {
1166                 Some(String::new())
1167             }
1168         }
1169     }
1170     let mut s = String::with_capacity(md.len() * 3 / 2);
1171     let mut p = ParserWrapper {
1172         inner: Parser::new(md),
1173         is_in: 0,
1174         is_first: true,
1175     };
1176     while let Some(t) = p.next() {
1177         if !t.is_empty() {
1178             s.push_str(&t);
1179         }
1180     }
1181     s
1182 }
1183
1184 pub fn markdown_links(md: &str, render_type: RenderType) -> Vec<String> {
1185     if md.is_empty() {
1186         return vec![];
1187     }
1188
1189     match render_type {
1190         RenderType::Hoedown => {
1191             extern fn hoedown_link(
1192                 _ob: *mut hoedown_buffer,
1193                 _content: *const hoedown_buffer,
1194                 link: *const hoedown_buffer,
1195                 _title: *const hoedown_buffer,
1196                 data: *const hoedown_renderer_data,
1197                 _line: libc::size_t
1198             ) -> libc::c_int {
1199                 if link.is_null() {
1200                     return 0;
1201                 }
1202
1203                 let opaque = unsafe { (*data).opaque as *mut hoedown_html_renderer_state };
1204                 let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
1205
1206                 if let Some(ref mut links) = opaque.links {
1207                     let s = unsafe { (*link).as_bytes() };
1208                     let s = str::from_utf8(&s).unwrap().to_owned();
1209
1210                     debug!("found link: {}", s);
1211
1212                     links.push(s);
1213                 }
1214
1215                 //returning 0 here means "emit the span verbatim", but we're not using the output
1216                 //anyway so we don't really care
1217                 0
1218             }
1219
1220             unsafe {
1221                 let ob = hoedown_buffer_new(DEF_OUNIT);
1222                 let renderer = hoedown_html_renderer_new(0, 0);
1223                 let mut opaque = MyOpaque {
1224                     dfltblk: (*renderer).blockcode.unwrap(),
1225                     toc_builder: None,
1226                     links: Some(vec![]),
1227                 };
1228                 (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
1229                         = &mut opaque as *mut _ as *mut libc::c_void;
1230                 (*renderer).blockcode = Some(hoedown_block);
1231                 (*renderer).header = Some(hoedown_header);
1232                 (*renderer).codespan = Some(hoedown_codespan);
1233                 (*renderer).link = Some(hoedown_link);
1234
1235                 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
1236                 hoedown_document_render(document, ob, md.as_ptr(),
1237                                         md.len() as libc::size_t);
1238                 hoedown_document_free(document);
1239
1240                 hoedown_html_renderer_free(renderer);
1241                 hoedown_buffer_free(ob);
1242
1243                 opaque.links.unwrap()
1244             }
1245         }
1246         RenderType::Pulldown => {
1247             let mut opts = Options::empty();
1248             opts.insert(OPTION_ENABLE_TABLES);
1249             opts.insert(OPTION_ENABLE_FOOTNOTES);
1250
1251             let p = Parser::new_ext(md, opts);
1252
1253             let iter = Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None)));
1254             let mut links = vec![];
1255
1256             for ev in iter {
1257                 if let Event::Start(Tag::Link(dest, _)) = ev {
1258                     debug!("found link: {}", dest);
1259                     links.push(dest.into_owned());
1260                 }
1261             }
1262
1263             links
1264         }
1265     }
1266 }
1267
1268 #[cfg(test)]
1269 mod tests {
1270     use super::{LangString, Markdown, MarkdownHtml};
1271     use super::plain_summary_line;
1272     use super::RenderType;
1273     use html::render::reset_ids;
1274
1275     #[test]
1276     fn test_lang_string_parse() {
1277         fn t(s: &str,
1278             should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
1279             compile_fail: bool, allow_fail: bool, error_codes: Vec<String>) {
1280             assert_eq!(LangString::parse(s), LangString {
1281                 should_panic,
1282                 no_run,
1283                 ignore,
1284                 rust,
1285                 test_harness,
1286                 compile_fail,
1287                 error_codes,
1288                 original: s.to_owned(),
1289                 allow_fail,
1290             })
1291         }
1292
1293         fn v() -> Vec<String> {
1294             Vec::new()
1295         }
1296
1297         // marker                | should_panic| no_run| ignore| rust | test_harness| compile_fail
1298         //                       | allow_fail | error_codes
1299         t("",                      false,        false,  false,  true,  false, false, false, v());
1300         t("rust",                  false,        false,  false,  true,  false, false, false, v());
1301         t("sh",                    false,        false,  false,  false, false, false, false, v());
1302         t("ignore",                false,        false,  true,   true,  false, false, false, v());
1303         t("should_panic",          true,         false,  false,  true,  false, false, false, v());
1304         t("no_run",                false,        true,   false,  true,  false, false, false, v());
1305         t("test_harness",          false,        false,  false,  true,  true,  false, false, v());
1306         t("compile_fail",          false,        true,   false,  true,  false, true,  false, v());
1307         t("allow_fail",            false,        false,  false,  true,  false, false, true,  v());
1308         t("{.no_run .example}",    false,        true,   false,  true,  false, false, false, v());
1309         t("{.sh .should_panic}",   true,         false,  false,  false, false, false, false, v());
1310         t("{.example .rust}",      false,        false,  false,  true,  false, false, false, v());
1311         t("{.test_harness .rust}", false,        false,  false,  true,  true,  false, false, v());
1312         t("text, no_run",          false,        true,   false,  false, false, false, false, v());
1313         t("text,no_run",           false,        true,   false,  false, false, false, false, v());
1314     }
1315
1316     #[test]
1317     fn issue_17736() {
1318         let markdown = "# title";
1319         format!("{}", Markdown(markdown, RenderType::Pulldown));
1320         reset_ids(true);
1321     }
1322
1323     #[test]
1324     fn test_header() {
1325         fn t(input: &str, expect: &str) {
1326             let output = format!("{}", Markdown(input, RenderType::Pulldown));
1327             assert_eq!(output, expect, "original: {}", input);
1328             reset_ids(true);
1329         }
1330
1331         t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
1332           <a href=\"#foo-bar\">Foo bar</a></h1>");
1333         t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
1334           header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
1335         t("### **Foo** *bar* baz!?!& -_qux_-%",
1336           "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
1337           <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
1338           <em>bar</em> baz!?!&amp; -<em>qux</em>-%</a></h3>");
1339         t("#### **Foo?** & \\*bar?!*  _`baz`_ ❤ #qux",
1340           "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
1341           <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> &amp; *bar?!*  \
1342           <em><code>baz</code></em> ❤ #qux</a></h4>");
1343     }
1344
1345     #[test]
1346     fn test_header_ids_multiple_blocks() {
1347         fn t(input: &str, expect: &str) {
1348             let output = format!("{}", Markdown(input, RenderType::Pulldown));
1349             assert_eq!(output, expect, "original: {}", input);
1350         }
1351
1352         let test = || {
1353             t("# Example", "<h1 id=\"example\" class=\"section-header\">\
1354               <a href=\"#example\">Example</a></h1>");
1355             t("# Panics", "<h1 id=\"panics\" class=\"section-header\">\
1356               <a href=\"#panics\">Panics</a></h1>");
1357             t("# Example", "<h1 id=\"example-1\" class=\"section-header\">\
1358               <a href=\"#example-1\">Example</a></h1>");
1359             t("# Main", "<h1 id=\"main-1\" class=\"section-header\">\
1360               <a href=\"#main-1\">Main</a></h1>");
1361             t("# Example", "<h1 id=\"example-2\" class=\"section-header\">\
1362               <a href=\"#example-2\">Example</a></h1>");
1363             t("# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
1364               <a href=\"#panics-1\">Panics</a></h1>");
1365         };
1366         test();
1367         reset_ids(true);
1368         test();
1369     }
1370
1371     #[test]
1372     fn test_plain_summary_line() {
1373         fn t(input: &str, expect: &str) {
1374             let output = plain_summary_line(input);
1375             assert_eq!(output, expect, "original: {}", input);
1376         }
1377
1378         t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
1379         t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
1380         t("code `let x = i32;` ...", "code `let x = i32;` ...");
1381         t("type `Type<'static>` ...", "type `Type<'static>` ...");
1382         t("# top header", "top header");
1383         t("## header", "header");
1384     }
1385
1386     #[test]
1387     fn test_markdown_html_escape() {
1388         fn t(input: &str, expect: &str) {
1389             let output = format!("{}", MarkdownHtml(input, RenderType::Pulldown));
1390             assert_eq!(output, expect, "original: {}", input);
1391         }
1392
1393         t("`Struct<'a, T>`", "<p><code>Struct&lt;'a, T&gt;</code></p>\n");
1394         t("Struct<'a, T>", "<p>Struct&lt;'a, T&gt;</p>\n");
1395         t("Struct<br>", "<p>Struct&lt;br&gt;</p>\n");
1396     }
1397 }