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::ffi::CString;
36 use std::fmt::{self, Write};
38 use syntax::feature_gate::UnstableFeatures;
39 use syntax::codemap::Span;
41 use html::render::derive_id;
42 use html::toc::TocBuilder;
44 use html::escape::Escape;
47 use pulldown_cmark::{html, Event, Tag, Parser};
48 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
50 #[derive(PartialEq, Debug, Clone, Copy)]
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);
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
73 fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
74 let trimmed = s.trim();
77 } else if trimmed.starts_with("# ") {
84 /// Returns a new string with all consecutive whitespace collapsed into
87 /// Any leading or trailing whitespace will be trimmed.
88 fn collapse_whitespace(s: &str) -> String {
89 s.split_whitespace().collect::<Vec<_>>().join(" ")
92 /// Convert chars from a title for an id.
94 /// "Hello, world!" -> "hello-world"
95 fn slugify(c: char) -> Option<char> {
96 if c.is_alphanumeric() || c == '-' || c == '_' {
98 Some(c.to_ascii_lowercase())
102 } else if c.is_whitespace() && c.is_ascii() {
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)>> = {
115 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
116 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
120 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
121 fn new(iter: I) -> Self {
128 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
129 type Item = Event<'a>;
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)));
141 let mut origtext = String::new();
142 for event in &mut self.inner {
144 Event::End(Tag::CodeBlock(..)) => break,
145 Event::Text(ref s) => {
146 origtext.push_str(s);
151 let lines = origtext.lines().filter(|l| {
152 stripped_filtered_line(*l).is_none()
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)| {
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 "&version=nightly"
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'*'
184 let mut test_escaped = String::new();
185 for b in test.bytes() {
187 test_escaped.push(char::from(b));
189 write!(test_escaped, "%{:02X}", b).unwrap();
193 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
194 url, test_escaped, channel
197 s.push_str(&highlight::render_with_highlighting(
199 Some("rust-example-rendered"),
201 playground_button.as_ref().map(String::as_str)));
202 Some(Event::Html(s.into()))
207 /// Make headings links with anchor ids and build up TOC.
208 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
210 toc: Option<&'b mut TocBuilder>,
211 buf: VecDeque<Event<'a>>,
214 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
215 fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
219 buf: VecDeque::new(),
224 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
225 type Item = Event<'a>;
227 fn next(&mut self) -> Option<Self::Item> {
228 if let Some(e) = self.buf.pop_front() {
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 {
237 Event::End(Tag::Header(..)) => break,
238 Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
241 self.buf.push_back(event);
243 let id = derive_id(id);
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()));
252 self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
254 let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
258 return Some(Event::InlineHtml(start_tags.into()));
264 /// Extracts just the first paragraph.
265 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
271 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
272 fn new(iter: I) -> Self {
281 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
282 type Item = Event<'a>;
284 fn next(&mut self) -> Option<Self::Item> {
285 if self.started && self.depth == 0 {
291 let event = self.inner.next();
293 Some(Event::Start(..)) => self.depth += 1,
294 Some(Event::End(..)) => self.depth -= 1,
301 /// Moves all footnote definitions to the end and add back links to the
303 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
305 footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
308 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
309 fn new(iter: I) -> Self {
312 footnotes: HashMap::new(),
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))
322 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
323 type Item = Event<'a>;
325 fn next(&mut self) -> Option<Self::Item> {
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}\
333 return Some(Event::Html(reference.into()));
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 {
343 let entry = self.get_entry(&def);
344 (*entry).0 = content;
346 Some(e) => return Some(e),
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() {
359 html::push_html(&mut ret, content.into_iter());
361 " <a href=\"#supref{}\" rev=\"footnote\">↩</a>",
364 ret.push_str("</p>");
366 ret.push_str("</li>");
368 ret.push_str("</ol></div>");
369 return Some(Event::Html(ret.into()));
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;
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;
395 enum hoedown_document {}
397 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
398 *const hoedown_buffer, *const hoedown_renderer_data,
401 type blockquotefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
402 *const hoedown_renderer_data, libc::size_t);
404 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
405 libc::c_int, *const hoedown_renderer_data,
408 type blockhtmlfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
409 *const hoedown_renderer_data, libc::size_t);
411 type codespanfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
412 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
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;
418 type entityfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
419 *const hoedown_renderer_data, libc::size_t);
421 type normaltextfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
422 *const hoedown_renderer_data, libc::size_t);
425 struct hoedown_renderer_data {
426 opaque: *mut libc::c_void,
430 struct hoedown_renderer {
431 opaque: *mut libc::c_void,
433 blockcode: Option<blockcodefn>,
434 blockquote: Option<blockquotefn>,
435 header: Option<headerfn>,
437 other_block_level_callbacks: [libc::size_t; 11],
439 blockhtml: Option<blockhtmlfn>,
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],
448 /* low level callbacks - NULL copies input directly into the output */
449 entity: Option<entityfn>,
450 normal_text: Option<normaltextfn>,
452 /* header and footer */
453 other_callbacks: [libc::size_t; 2],
457 struct hoedown_html_renderer_state {
458 opaque: *mut libc::c_void,
459 toc_data: html_toc_data,
461 link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
462 *const hoedown_buffer,
463 *const hoedown_renderer_data)>,
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,
475 struct hoedown_buffer {
483 dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
484 *const hoedown_buffer, *const hoedown_renderer_data,
486 toc_builder: Option<TocBuilder>,
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);
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,
501 doc_size: libc::size_t);
502 fn hoedown_document_free(md: *mut hoedown_document);
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);
509 impl hoedown_buffer {
510 fn as_bytes(&self) -> &[u8] {
511 unsafe { slice::from_raw_parts(self.data, self.size as usize) }
515 pub fn render(w: &mut fmt::Formatter,
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) {
523 if orig_text.is_null() { return }
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() {
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,
546 let lines = origtext.lines().filter(|l| {
547 stripped_filtered_line(*l).is_none()
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)| {
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 "&version=nightly"
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'*'
580 let mut test_escaped = String::new();
581 for b in test.bytes() {
583 test_escaped.push(char::from(b));
585 write!(test_escaped, "%{:02X}", b).unwrap();
589 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
590 url, test_escaped, channel
593 s.push_str(&highlight::render_with_highlighting(
595 Some("rust-example-rendered"),
597 playground_button.as_ref().map(String::as_str)));
598 let output = CString::new(s).unwrap();
599 hoedown_buffer_puts(ob, output.as_ptr());
604 extern fn header(ob: *mut hoedown_buffer, text: *const hoedown_buffer,
605 level: libc::c_int, data: *const hoedown_renderer_data,
607 // hoedown does this, we may as well too
608 unsafe { hoedown_buffer_puts(ob, "\n\0".as_ptr() as *const _); }
610 // Extract the text provided
611 let s = if text.is_null() {
614 let s = unsafe { (*text).as_bytes() };
615 str::from_utf8(&s).unwrap().to_owned()
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 '_'.
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 "<", ">", "&", "'", """];
628 for sub in repl_sub {
629 id = id.replace(sub, "");
631 let id = id.chars().filter_map(|c| {
632 if c.is_alphanumeric() || c == '-' || c == '_' {
634 Some(c.to_ascii_lowercase())
638 } else if c.is_whitespace() && c.is_ascii() {
643 }).collect::<String>();
645 let opaque = unsafe { (*data).opaque as *mut hoedown_html_renderer_state };
646 let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
648 let id = derive_id(id);
650 let sec = opaque.toc_builder.as_mut().map_or("".to_owned(), |builder| {
651 format!("{} ", builder.push(level as u32, s.clone(), id.clone()))
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);
659 let text = CString::new(text).unwrap();
660 unsafe { hoedown_buffer_puts(ob, text.as_ptr()) }
664 ob: *mut hoedown_buffer,
665 text: *const hoedown_buffer,
666 _: *const hoedown_renderer_data,
669 let content = if text.is_null() {
672 let bytes = unsafe { (*text).as_bytes() };
673 let s = str::from_utf8(bytes).unwrap();
674 collapse_whitespace(s)
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".
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}
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);
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);
702 hoedown_html_renderer_free(renderer);
704 let mut ret = opaque.toc_builder.map_or(Ok(()), |builder| {
705 write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
709 let buf = (*ob).as_bytes();
710 ret = w.write_str(str::from_utf8(buf).unwrap());
712 hoedown_buffer_free(ob);
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) {
724 if text.is_null() { return }
725 let block_info = if lang.is_null() {
726 LangString::all_false()
728 let lang = (*lang).as_bytes();
729 let s = str::from_utf8(lang).unwrap();
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)
740 let text = lines.collect::<Vec<&str>>().join("\n");
741 let filename = tests.get_filename();
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,
751 tests.add_old_test(text, filename);
756 extern fn header(_ob: *mut hoedown_buffer,
757 text: *const hoedown_buffer,
758 level: libc::c_int, data: *const hoedown_renderer_data,
761 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
762 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
764 tests.register_header("", level as u32);
766 let text = (*text).as_bytes();
767 let text = str::from_utf8(text).unwrap();
768 tests.register_header(text, level as u32);
773 tests.set_position(position);
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;
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);
787 hoedown_html_renderer_free(renderer);
788 hoedown_buffer_free(ob);
792 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
793 tests.set_position(position);
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() {
801 Event::Start(Tag::CodeBlock(s)) => {
802 let block_info = if s.is_empty() {
803 LangString::all_false()
805 LangString::parse(&*s)
807 if !block_info.rust {
810 let mut test_s = String::new();
811 let mut offset = None;
813 let event = parser.next();
814 if let Some(event) = event {
816 Event::End(Tag::CodeBlock(_)) => break,
817 Event::Text(ref s) => {
819 if offset.is_none() {
820 offset = Some(parser.get_offset());
829 let offset = offset.unwrap_or(0);
830 let lines = test_s.lines().map(|l| {
831 stripped_filtered_line(l).unwrap_or(l)
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,
842 prev_offset = offset;
844 Event::Start(Tag::Header(level)) => {
845 register_header = Some(level as u32);
847 Event::Text(ref s) if register_header.is_some() => {
848 let level = register_header.unwrap();
850 tests.register_header("", level);
852 tests.register_header(s, level);
854 register_header = None;
861 #[derive(Eq, PartialEq, Clone, Debug)]
870 error_codes: Vec<String>,
874 fn all_false() -> LangString {
876 original: String::new(),
880 rust: true, // NB This used to be `notrust = false`
883 error_codes: Vec::new(),
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;
898 data.original = string.to_owned();
899 let tokens = string.split(|c: char|
900 !(c == '_' || c == '-' || c.is_alphanumeric())
903 for token in tokens {
907 data.should_panic = true;
908 seen_rust_tags = seen_other_tags == false;
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; }
914 data.test_harness = true;
915 seen_rust_tags = !seen_other_tags || seen_rust_tags;
917 "compile_fail" if allow_compile_fail => {
918 data.compile_fail = true;
919 seen_rust_tags = !seen_other_tags || seen_rust_tags;
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;
927 seen_other_tags = true;
930 _ => { seen_other_tags = true }
934 data.rust &= !seen_other_tags || seen_rust_tags;
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;
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)
949 let mut opts = Options::empty();
950 opts.insert(OPTION_ENABLE_TABLES);
951 opts.insert(OPTION_ENABLE_FOOTNOTES);
953 let p = Parser::new_ext(md, opts);
955 let mut s = String::with_capacity(md.len() * 3 / 2);
957 html::push_html(&mut s,
958 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
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;
969 if render_type == RenderType::Hoedown {
970 render(fmt, md, true, 0)
972 let mut opts = Options::empty();
973 opts.insert(OPTION_ENABLE_TABLES);
974 opts.insert(OPTION_ENABLE_FOOTNOTES);
976 let p = Parser::new_ext(md, opts);
978 let mut s = String::with_capacity(md.len() * 3 / 2);
980 let mut toc = TocBuilder::new();
982 html::push_html(&mut s,
983 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, Some(&mut toc)))));
985 write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
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;
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)
1001 let mut opts = Options::empty();
1002 opts.insert(OPTION_ENABLE_TABLES);
1003 opts.insert(OPTION_ENABLE_FOOTNOTES);
1005 let p = Parser::new_ext(md, opts);
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),
1013 let mut s = String::with_capacity(md.len() * 3 / 2);
1015 html::push_html(&mut s,
1016 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
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(()) }
1029 let p = Parser::new(md);
1031 let mut s = String::new();
1033 html::push_html(&mut s, SummaryLine::new(p));
1039 pub fn plain_summary_line(md: &str) -> String {
1040 struct ParserWrapper<'a> {
1046 impl<'a> Iterator for ParserWrapper<'a> {
1049 fn next(&mut self) -> Option<String> {
1050 let next_event = self.inner.next();
1051 if next_event.is_none() {
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),
1064 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
1065 self.is_in += is_in;
1068 self.is_first = false;
1075 let mut s = String::with_capacity(md.len() * 3 / 2);
1076 let mut p = ParserWrapper {
1077 inner: Parser::new(md),
1081 while let Some(t) = p.next() {
1091 use super::{LangString, Markdown, MarkdownHtml};
1092 use super::plain_summary_line;
1093 use super::RenderType;
1094 use html::render::reset_ids;
1097 fn test_lang_string_parse() {
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,
1106 test_harness: test_harness,
1107 compile_fail: compile_fail,
1108 error_codes: error_codes,
1109 original: s.to_owned(),
1113 // marker | should_panic| no_run| ignore| rust | test_harness| compile_fail
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());
1133 let markdown = "# title";
1134 format!("{}", Markdown(markdown, RenderType::Pulldown));
1140 fn t(input: &str, expect: &str) {
1141 let output = format!("{}", Markdown(input, RenderType::Pulldown));
1142 assert_eq!(output, expect, "original: {}", input);
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!?!& -<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> & *bar?!* \
1157 <em><code>baz</code></em> ❤ #qux</a></h4>");
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);
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>");
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);
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");
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);
1208 t("`Struct<'a, T>`", "<p><code>Struct<'a, T></code></p>\n");
1209 t("Struct<'a, T>", "<p>Struct<'a, T></p>\n");
1210 t("Struct<br>", "<p>Struct<br></p>\n");