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