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