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.
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.
11 //! Markdown formatting for rustdoc
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:
19 //! use rustdoc::html::markdown::Markdown;
21 //! let s = "My *markdown* _text_";
22 //! let html = format!("{}", Markdown(s));
23 //! // ... something using html
26 #![allow(non_camel_case_types)]
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};
37 use syntax::feature_gate::UnstableFeatures;
38 use syntax::codemap::Span;
40 use html::render::derive_id;
41 use html::toc::TocBuilder;
43 use html::escape::Escape;
46 use pulldown_cmark::{html, Event, Tag, Parser};
47 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
49 #[derive(PartialEq, Debug, Clone, Copy)]
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);
68 /// Controls whether a line will be hidden or shown in HTML output.
70 /// All lines are used in documentation tests.
77 fn for_html(self) -> Option<&'a str> {
79 Line::Shown(l) => Some(l),
80 Line::Hidden(_) => None,
84 fn for_code(self) -> &'a str {
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("# ") {
103 Line::Hidden(&trimmed[2..])
104 } else if trimmed == "#" {
105 // We cannot handle '#text' because it could be #[attr].
112 /// Returns a new string with all consecutive whitespace collapsed into
115 /// Any leading or trailing whitespace will be trimmed.
116 fn collapse_whitespace(s: &str) -> String {
117 s.split_whitespace().collect::<Vec<_>>().join(" ")
120 /// Convert chars from a title for an id.
122 /// "Hello, world!" -> "hello-world"
123 fn slugify(c: char) -> Option<char> {
124 if c.is_alphanumeric() || c == '-' || c == '_' {
126 Some(c.to_ascii_lowercase())
130 } else if c.is_whitespace() && c.is_ascii() {
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)>> = {
143 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
144 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
148 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
149 fn new(iter: I) -> Self {
156 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
157 type Item = Event<'a>;
159 fn next(&mut self) -> Option<Self::Item> {
160 let event = self.inner.next();
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)));
168 compile_fail = parse_result.compile_fail;
169 ignore = parse_result.ignore;
174 let mut origtext = String::new();
175 for event in &mut self.inner {
177 Event::End(Tag::CodeBlock(..)) => break,
178 Event::Text(ref s) => {
179 origtext.push_str(s);
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)| {
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 "&version=nightly"
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'*'
215 let mut test_escaped = String::new();
216 for b in test.bytes() {
218 test_escaped.push(char::from(b));
220 write!(test_escaped, "%{:02X}", b).unwrap();
224 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
225 url, test_escaped, channel
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"))
235 s.push_str(&highlight::render_with_highlighting(
237 Some(&format!("rust-example-rendered{}",
238 if ignore { " ignore" }
239 else if compile_fail { " compile_fail" }
242 playground_button.as_ref().map(String::as_str),
244 Some(Event::Html(s.into()))
249 /// Make headings links with anchor ids and build up TOC.
250 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
252 toc: Option<&'b mut TocBuilder>,
253 buf: VecDeque<Event<'a>>,
256 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
257 fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
261 buf: VecDeque::new(),
266 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
267 type Item = Event<'a>;
269 fn next(&mut self) -> Option<Self::Item> {
270 if let Some(e) = self.buf.pop_front() {
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 {
279 Event::End(Tag::Header(..)) => break,
280 Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
283 self.buf.push_back(event);
285 let id = derive_id(id);
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()));
294 self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
296 let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
300 return Some(Event::InlineHtml(start_tags.into()));
306 /// Extracts just the first paragraph.
307 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
313 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
314 fn new(iter: I) -> Self {
323 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
324 type Item = Event<'a>;
326 fn next(&mut self) -> Option<Self::Item> {
327 if self.started && self.depth == 0 {
333 let event = self.inner.next();
335 Some(Event::Start(..)) => self.depth += 1,
336 Some(Event::End(..)) => self.depth -= 1,
343 /// Moves all footnote definitions to the end and add back links to the
345 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
347 footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
350 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
351 fn new(iter: I) -> Self {
354 footnotes: HashMap::new(),
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))
364 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
365 type Item = Event<'a>;
367 fn next(&mut self) -> Option<Self::Item> {
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}\
375 return Some(Event::Html(reference.into()));
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 {
385 let entry = self.get_entry(&def);
386 (*entry).0 = content;
388 Some(e) => return Some(e),
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() {
401 html::push_html(&mut ret, content.into_iter());
403 " <a href=\"#supref{}\" rev=\"footnote\">↩</a>",
406 ret.push_str("</p>");
408 ret.push_str("</li>");
410 ret.push_str("</ol></div>");
411 return Some(Event::Html(ret.into()));
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;
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;
437 enum hoedown_document {}
439 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
440 *const hoedown_buffer, *const hoedown_renderer_data,
443 type blockquotefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
444 *const hoedown_renderer_data, libc::size_t);
446 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
447 libc::c_int, *const hoedown_renderer_data,
450 type blockhtmlfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
451 *const hoedown_renderer_data, libc::size_t);
453 type codespanfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
454 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
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;
460 type entityfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
461 *const hoedown_renderer_data, libc::size_t);
463 type normaltextfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
464 *const hoedown_renderer_data, libc::size_t);
467 struct hoedown_renderer_data {
468 opaque: *mut libc::c_void,
472 struct hoedown_renderer {
473 opaque: *mut libc::c_void,
475 blockcode: Option<blockcodefn>,
476 blockquote: Option<blockquotefn>,
477 header: Option<headerfn>,
479 other_block_level_callbacks: [libc::size_t; 11],
481 blockhtml: Option<blockhtmlfn>,
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],
490 /* low level callbacks - NULL copies input directly into the output */
491 entity: Option<entityfn>,
492 normal_text: Option<normaltextfn>,
494 /* header and footer */
495 other_callbacks: [libc::size_t; 2],
499 struct hoedown_html_renderer_state {
500 opaque: *mut libc::c_void,
501 toc_data: html_toc_data,
503 link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
504 *const hoedown_buffer,
505 *const hoedown_renderer_data)>,
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,
517 struct hoedown_buffer {
525 dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
526 *const hoedown_buffer, *const hoedown_renderer_data,
528 toc_builder: Option<TocBuilder>,
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);
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,
543 doc_size: libc::size_t);
544 fn hoedown_document_free(md: *mut hoedown_document);
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);
551 impl hoedown_buffer {
552 fn as_bytes(&self) -> &[u8] {
553 unsafe { slice::from_raw_parts(self.data, self.size as usize) }
557 pub fn render(w: &mut fmt::Formatter,
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) {
565 if orig_text.is_null() { return }
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;
576 let rendered = if lang.is_null() || origtext.is_empty() {
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,
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)| {
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 "&version=nightly"
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'*'
626 let mut test_escaped = String::new();
627 for b in test.bytes() {
629 test_escaped.push(char::from(b));
631 write!(test_escaped, "%{:02X}", b).unwrap();
635 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
636 url, test_escaped, channel
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"))
646 s.push_str(&highlight::render_with_highlighting(
648 Some(&format!("rust-example-rendered{}",
649 if ignore { " ignore" }
650 else if compile_fail { " compile_fail" }
653 playground_button.as_ref().map(String::as_str),
655 hoedown_buffer_put(ob, s.as_ptr(), s.len());
660 extern fn header(ob: *mut hoedown_buffer, text: *const hoedown_buffer,
661 level: libc::c_int, data: *const hoedown_renderer_data,
663 // hoedown does this, we may as well too
664 unsafe { hoedown_buffer_put(ob, "\n".as_ptr(), 1); }
666 // Extract the text provided
667 let s = if text.is_null() {
670 let s = unsafe { (*text).as_bytes() };
671 str::from_utf8(&s).unwrap().to_owned()
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 '_'.
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 "<", ">", "&", "'", """];
684 for sub in repl_sub {
685 id = id.replace(sub, "");
687 let id = id.chars().filter_map(|c| {
688 if c.is_alphanumeric() || c == '-' || c == '_' {
690 Some(c.to_ascii_lowercase())
694 } else if c.is_whitespace() && c.is_ascii() {
699 }).collect::<String>();
701 let opaque = unsafe { (*data).opaque as *mut hoedown_html_renderer_state };
702 let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
704 let id = derive_id(id);
706 let sec = opaque.toc_builder.as_mut().map_or("".to_owned(), |builder| {
707 format!("{} ", builder.push(level as u32, s.clone(), id.clone()))
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);
715 unsafe { hoedown_buffer_put(ob, text.as_ptr(), text.len()); }
719 ob: *mut hoedown_buffer,
720 text: *const hoedown_buffer,
721 _: *const hoedown_renderer_data,
724 let content = if text.is_null() {
727 let bytes = unsafe { (*text).as_bytes() };
728 let s = str::from_utf8(bytes).unwrap();
729 collapse_whitespace(s)
732 let content = format!("<code>{}</code>", Escape(&content));
734 hoedown_buffer_put(ob, content.as_ptr(), content.len());
736 // Return anything except 0, which would mean "also print the code span verbatim".
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}
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);
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);
758 hoedown_html_renderer_free(renderer);
760 let mut ret = opaque.toc_builder.map_or(Ok(()), |builder| {
761 write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
765 let buf = (*ob).as_bytes();
766 ret = w.write_str(str::from_utf8(buf).unwrap());
768 hoedown_buffer_free(ob);
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) {
780 if text.is_null() { return }
781 let block_info = if lang.is_null() {
782 LangString::all_false()
784 let lang = (*lang).as_bytes();
785 let s = str::from_utf8(lang).unwrap();
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();
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);
805 tests.add_old_test(text, filename);
810 extern fn header(_ob: *mut hoedown_buffer,
811 text: *const hoedown_buffer,
812 level: libc::c_int, data: *const hoedown_renderer_data,
815 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
816 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
818 tests.register_header("", level as u32);
820 let text = (*text).as_bytes();
821 let text = str::from_utf8(text).unwrap();
822 tests.register_header(text, level as u32);
827 tests.set_position(position);
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;
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);
841 hoedown_html_renderer_free(renderer);
842 hoedown_buffer_free(ob);
846 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
847 tests.set_position(position);
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() {
855 Event::Start(Tag::CodeBlock(s)) => {
856 let block_info = if s.is_empty() {
857 LangString::all_false()
859 LangString::parse(&*s)
861 if !block_info.rust {
864 let mut test_s = String::new();
865 let mut offset = None;
867 let event = parser.next();
868 if let Some(event) = event {
870 Event::End(Tag::CodeBlock(_)) => break,
871 Event::Text(ref s) => {
873 if offset.is_none() {
874 offset = Some(parser.get_offset());
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;
896 Event::Start(Tag::Header(level)) => {
897 register_header = Some(level as u32);
899 Event::Text(ref s) if register_header.is_some() => {
900 let level = register_header.unwrap();
902 tests.register_header("", level);
904 tests.register_header(s, level);
906 register_header = None;
913 #[derive(Eq, PartialEq, Clone, Debug)]
922 error_codes: Vec<String>,
927 fn all_false() -> LangString {
929 original: String::new(),
933 rust: true, // NB This used to be `notrust = false`
936 error_codes: Vec::new(),
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;
952 data.original = string.to_owned();
953 let tokens = string.split(|c: char|
954 !(c == '_' || c == '-' || c.is_alphanumeric())
957 for token in tokens {
961 data.should_panic = true;
962 seen_rust_tags = seen_other_tags == false;
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; }
969 data.test_harness = true;
970 seen_rust_tags = !seen_other_tags || seen_rust_tags;
972 "compile_fail" if allow_compile_fail => {
973 data.compile_fail = true;
974 seen_rust_tags = !seen_other_tags || seen_rust_tags;
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;
982 seen_other_tags = true;
985 _ => { seen_other_tags = true }
989 data.rust &= !seen_other_tags || seen_rust_tags;
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;
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)
1004 let mut opts = Options::empty();
1005 opts.insert(OPTION_ENABLE_TABLES);
1006 opts.insert(OPTION_ENABLE_FOOTNOTES);
1008 let p = Parser::new_ext(md, opts);
1010 let mut s = String::with_capacity(md.len() * 3 / 2);
1012 html::push_html(&mut s,
1013 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
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;
1024 if render_type == RenderType::Hoedown {
1025 render(fmt, md, true, 0)
1027 let mut opts = Options::empty();
1028 opts.insert(OPTION_ENABLE_TABLES);
1029 opts.insert(OPTION_ENABLE_FOOTNOTES);
1031 let p = Parser::new_ext(md, opts);
1033 let mut s = String::with_capacity(md.len() * 3 / 2);
1035 let mut toc = TocBuilder::new();
1037 html::push_html(&mut s,
1038 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, Some(&mut toc)))));
1040 write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
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;
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)
1056 let mut opts = Options::empty();
1057 opts.insert(OPTION_ENABLE_TABLES);
1058 opts.insert(OPTION_ENABLE_FOOTNOTES);
1060 let p = Parser::new_ext(md, opts);
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),
1068 let mut s = String::with_capacity(md.len() * 3 / 2);
1070 html::push_html(&mut s,
1071 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
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(()) }
1084 let p = Parser::new(md);
1086 let mut s = String::new();
1088 html::push_html(&mut s, SummaryLine::new(p));
1094 pub fn plain_summary_line(md: &str) -> String {
1095 struct ParserWrapper<'a> {
1101 impl<'a> Iterator for ParserWrapper<'a> {
1104 fn next(&mut self) -> Option<String> {
1105 let next_event = self.inner.next();
1106 if next_event.is_none() {
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),
1119 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
1120 self.is_in += is_in;
1123 self.is_first = false;
1130 let mut s = String::with_capacity(md.len() * 3 / 2);
1131 let mut p = ParserWrapper {
1132 inner: Parser::new(md),
1136 while let Some(t) = p.next() {
1146 use super::{LangString, Markdown, MarkdownHtml};
1147 use super::plain_summary_line;
1148 use super::RenderType;
1149 use html::render::reset_ids;
1152 fn test_lang_string_parse() {
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 {
1164 original: s.to_owned(),
1169 fn v() -> Vec<String> {
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());
1194 let markdown = "# title";
1195 format!("{}", Markdown(markdown, RenderType::Pulldown));
1201 fn t(input: &str, expect: &str) {
1202 let output = format!("{}", Markdown(input, RenderType::Pulldown));
1203 assert_eq!(output, expect, "original: {}", input);
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!?!& -<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> & *bar?!* \
1218 <em><code>baz</code></em> ❤ #qux</a></h4>");
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);
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>");
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);
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");
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);
1269 t("`Struct<'a, T>`", "<p><code>Struct<'a, T></code></p>\n");
1270 t("Struct<'a, T>", "<p>Struct<'a, T></p>\n");
1271 t("Struct<br>", "<p>Struct<br></p>\n");