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 title = if ignore {
229 let mut tmp = HashMap::new();
230 tmp.insert("title".to_owned(),
231 "Be careful when using this code, it's not being tested!".to_owned());
233 } else if compile_fail {
234 let mut tmp = HashMap::new();
235 tmp.insert("title".to_owned(),
236 "This code doesn't compile so be extra careful!".to_owned());
241 s.push_str(&highlight::render_with_highlighting(
243 Some(&format!("rust-example-rendered{}",
244 if ignore { " ignore" }
245 else if compile_fail { " compile_fail" }
248 playground_button.as_ref().map(String::as_str),
250 Some(Event::Html(s.into()))
255 /// Make headings links with anchor ids and build up TOC.
256 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
258 toc: Option<&'b mut TocBuilder>,
259 buf: VecDeque<Event<'a>>,
262 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
263 fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
267 buf: VecDeque::new(),
272 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
273 type Item = Event<'a>;
275 fn next(&mut self) -> Option<Self::Item> {
276 if let Some(e) = self.buf.pop_front() {
280 let event = self.inner.next();
281 if let Some(Event::Start(Tag::Header(level))) = event {
282 let mut id = String::new();
283 for event in &mut self.inner {
285 Event::End(Tag::Header(..)) => break,
286 Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
289 self.buf.push_back(event);
291 let id = derive_id(id);
293 if let Some(ref mut builder) = self.toc {
294 let mut html_header = String::new();
295 html::push_html(&mut html_header, self.buf.iter().cloned());
296 let sec = builder.push(level as u32, html_header, id.clone());
297 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
300 self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
302 let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
306 return Some(Event::InlineHtml(start_tags.into()));
312 /// Extracts just the first paragraph.
313 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
319 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
320 fn new(iter: I) -> Self {
329 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
330 type Item = Event<'a>;
332 fn next(&mut self) -> Option<Self::Item> {
333 if self.started && self.depth == 0 {
339 let event = self.inner.next();
341 Some(Event::Start(..)) => self.depth += 1,
342 Some(Event::End(..)) => self.depth -= 1,
349 /// Moves all footnote definitions to the end and add back links to the
351 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
353 footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
356 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
357 fn new(iter: I) -> Self {
360 footnotes: HashMap::new(),
363 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
364 let new_id = self.footnotes.keys().count() + 1;
365 let key = key.to_owned();
366 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
370 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
371 type Item = Event<'a>;
373 fn next(&mut self) -> Option<Self::Item> {
375 match self.inner.next() {
376 Some(Event::FootnoteReference(ref reference)) => {
377 let entry = self.get_entry(&reference);
378 let reference = format!("<sup id=\"supref{0}\"><a href=\"#ref{0}\">{0}\
381 return Some(Event::Html(reference.into()));
383 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
384 let mut content = Vec::new();
385 for event in &mut self.inner {
386 if let Event::End(Tag::FootnoteDefinition(..)) = event {
391 let entry = self.get_entry(&def);
392 (*entry).0 = content;
394 Some(e) => return Some(e),
396 if !self.footnotes.is_empty() {
397 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
398 v.sort_by(|a, b| a.1.cmp(&b.1));
399 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
400 for (mut content, id) in v {
401 write!(ret, "<li id=\"ref{}\">", id).unwrap();
402 let mut is_paragraph = false;
403 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
407 html::push_html(&mut ret, content.into_iter());
409 " <a href=\"#supref{}\" rev=\"footnote\">↩</a>",
412 ret.push_str("</p>");
414 ret.push_str("</li>");
416 ret.push_str("</ol></div>");
417 return Some(Event::Html(ret.into()));
427 const DEF_OUNIT: libc::size_t = 64;
428 const HOEDOWN_EXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 11;
429 const HOEDOWN_EXT_TABLES: libc::c_uint = 1 << 0;
430 const HOEDOWN_EXT_FENCED_CODE: libc::c_uint = 1 << 1;
431 const HOEDOWN_EXT_AUTOLINK: libc::c_uint = 1 << 3;
432 const HOEDOWN_EXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
433 const HOEDOWN_EXT_SUPERSCRIPT: libc::c_uint = 1 << 8;
434 const HOEDOWN_EXT_FOOTNOTES: libc::c_uint = 1 << 2;
435 const HOEDOWN_HTML_ESCAPE: libc::c_uint = 1 << 1;
437 const HOEDOWN_EXTENSIONS: libc::c_uint =
438 HOEDOWN_EXT_NO_INTRA_EMPHASIS | HOEDOWN_EXT_TABLES |
439 HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_AUTOLINK |
440 HOEDOWN_EXT_STRIKETHROUGH | HOEDOWN_EXT_SUPERSCRIPT |
441 HOEDOWN_EXT_FOOTNOTES;
443 enum hoedown_document {}
445 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
446 *const hoedown_buffer, *const hoedown_renderer_data,
449 type blockquotefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
450 *const hoedown_renderer_data, libc::size_t);
452 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
453 libc::c_int, *const hoedown_renderer_data,
456 type blockhtmlfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
457 *const hoedown_renderer_data, libc::size_t);
459 type codespanfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
460 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
462 type linkfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
463 *const hoedown_buffer, *const hoedown_buffer,
464 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
466 type entityfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
467 *const hoedown_renderer_data, libc::size_t);
469 type normaltextfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
470 *const hoedown_renderer_data, libc::size_t);
473 struct hoedown_renderer_data {
474 opaque: *mut libc::c_void,
478 struct hoedown_renderer {
479 opaque: *mut libc::c_void,
481 blockcode: Option<blockcodefn>,
482 blockquote: Option<blockquotefn>,
483 header: Option<headerfn>,
485 other_block_level_callbacks: [libc::size_t; 11],
487 blockhtml: Option<blockhtmlfn>,
489 /* span level callbacks - NULL or return 0 prints the span verbatim */
490 autolink: libc::size_t, // unused
491 codespan: Option<codespanfn>,
492 other_span_level_callbacks_1: [libc::size_t; 7],
493 link: Option<linkfn>,
494 other_span_level_callbacks_2: [libc::size_t; 6],
496 /* low level callbacks - NULL copies input directly into the output */
497 entity: Option<entityfn>,
498 normal_text: Option<normaltextfn>,
500 /* header and footer */
501 other_callbacks: [libc::size_t; 2],
505 struct hoedown_html_renderer_state {
506 opaque: *mut libc::c_void,
507 toc_data: html_toc_data,
509 link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
510 *const hoedown_buffer,
511 *const hoedown_renderer_data)>,
515 struct html_toc_data {
516 header_count: libc::c_int,
517 current_level: libc::c_int,
518 level_offset: libc::c_int,
519 nesting_level: libc::c_int,
523 struct hoedown_buffer {
531 dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
532 *const hoedown_buffer, *const hoedown_renderer_data,
534 toc_builder: Option<TocBuilder>,
538 fn hoedown_html_renderer_new(render_flags: libc::c_uint,
539 nesting_level: libc::c_int)
540 -> *mut hoedown_renderer;
541 fn hoedown_html_renderer_free(renderer: *mut hoedown_renderer);
543 fn hoedown_document_new(rndr: *const hoedown_renderer,
544 extensions: libc::c_uint,
545 max_nesting: libc::size_t) -> *mut hoedown_document;
546 fn hoedown_document_render(doc: *mut hoedown_document,
547 ob: *mut hoedown_buffer,
549 doc_size: libc::size_t);
550 fn hoedown_document_free(md: *mut hoedown_document);
552 fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer;
553 fn hoedown_buffer_free(b: *mut hoedown_buffer);
554 fn hoedown_buffer_put(b: *mut hoedown_buffer, c: *const u8, len: libc::size_t);
557 impl hoedown_buffer {
558 fn as_bytes(&self) -> &[u8] {
559 unsafe { slice::from_raw_parts(self.data, self.size as usize) }
563 pub fn render(w: &mut fmt::Formatter,
566 html_flags: libc::c_uint) -> fmt::Result {
567 extern fn block(ob: *mut hoedown_buffer, orig_text: *const hoedown_buffer,
568 lang: *const hoedown_buffer, data: *const hoedown_renderer_data,
569 line: libc::size_t) {
571 if orig_text.is_null() { return }
573 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
574 let my_opaque: &MyOpaque = &*((*opaque).opaque as *const MyOpaque);
575 let text = (*orig_text).as_bytes();
576 let origtext = str::from_utf8(text).unwrap();
577 let origtext = origtext.trim_left();
578 debug!("docblock: ==============\n{:?}\n=======", text);
579 let mut compile_fail = false;
580 let mut ignore = false;
582 let rendered = if lang.is_null() || origtext.is_empty() {
585 let rlang = (*lang).as_bytes();
586 let rlang = str::from_utf8(rlang).unwrap();
587 let parse_result = LangString::parse(rlang);
588 compile_fail = parse_result.compile_fail;
589 ignore = parse_result.ignore;
590 if !parse_result.rust {
591 (my_opaque.dfltblk)(ob, orig_text, lang,
592 opaque as *const hoedown_renderer_data,
600 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
601 let text = lines.collect::<Vec<&str>>().join("\n");
602 if rendered { return }
603 PLAYGROUND.with(|play| {
604 // insert newline to clearly separate it from the
605 // previous block so we can shorten the html output
606 let mut s = String::from("\n");
607 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
611 let test = origtext.lines()
612 .map(|l| map_line(l).for_code())
613 .collect::<Vec<&str>>().join("\n");
614 let krate = krate.as_ref().map(|s| &**s);
615 let test = test::make_test(&test, krate, false,
616 &Default::default());
617 let channel = if test.contains("#![feature(") {
618 "&version=nightly"
622 // These characters don't need to be escaped in a URI.
623 // FIXME: use a library function for percent encoding.
624 fn dont_escape(c: u8) -> bool {
625 (b'a' <= c && c <= b'z') ||
626 (b'A' <= c && c <= b'Z') ||
627 (b'0' <= c && c <= b'9') ||
628 c == b'-' || c == b'_' || c == b'.' ||
629 c == b'~' || c == b'!' || c == b'\'' ||
630 c == b'(' || c == b')' || c == b'*'
632 let mut test_escaped = String::new();
633 for b in test.bytes() {
635 test_escaped.push(char::from(b));
637 write!(test_escaped, "%{:02X}", b).unwrap();
641 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
642 url, test_escaped, channel
645 let title = if ignore {
646 let mut tmp = HashMap::new();
647 tmp.insert("title".to_owned(),
648 "Be careful when using this code, it's not being \
649 tested!".to_owned());
651 } else if compile_fail {
652 let mut tmp = HashMap::new();
653 tmp.insert("title".to_owned(),
654 "This code doesn't compile so be extra \
655 careful!".to_owned());
660 s.push_str(&highlight::render_with_highlighting(
662 Some(&format!("rust-example-rendered{}",
663 if ignore { " ignore" }
664 else if compile_fail { " compile_fail" }
667 playground_button.as_ref().map(String::as_str),
669 hoedown_buffer_put(ob, s.as_ptr(), s.len());
674 extern fn header(ob: *mut hoedown_buffer, text: *const hoedown_buffer,
675 level: libc::c_int, data: *const hoedown_renderer_data,
677 // hoedown does this, we may as well too
678 unsafe { hoedown_buffer_put(ob, "\n".as_ptr(), 1); }
680 // Extract the text provided
681 let s = if text.is_null() {
684 let s = unsafe { (*text).as_bytes() };
685 str::from_utf8(&s).unwrap().to_owned()
688 // Discard '<em>', '<code>' tags and some escaped characters,
689 // transform the contents of the header into a hyphenated string
690 // without non-alphanumeric characters other than '-' and '_'.
692 // This is a terrible hack working around how hoedown gives us rendered
693 // html for text rather than the raw text.
694 let mut id = s.clone();
695 let repl_sub = vec!["<em>", "</em>", "<code>", "</code>",
696 "<strong>", "</strong>",
697 "<", ">", "&", "'", """];
698 for sub in repl_sub {
699 id = id.replace(sub, "");
701 let id = id.chars().filter_map(|c| {
702 if c.is_alphanumeric() || c == '-' || c == '_' {
704 Some(c.to_ascii_lowercase())
708 } else if c.is_whitespace() && c.is_ascii() {
713 }).collect::<String>();
715 let opaque = unsafe { (*data).opaque as *mut hoedown_html_renderer_state };
716 let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
718 let id = derive_id(id);
720 let sec = opaque.toc_builder.as_mut().map_or("".to_owned(), |builder| {
721 format!("{} ", builder.push(level as u32, s.clone(), id.clone()))
725 let text = format!("<h{lvl} id='{id}' class='section-header'>\
726 <a href='#{id}'>{sec}{}</a></h{lvl}>",
727 s, lvl = level, id = id, sec = sec);
729 unsafe { hoedown_buffer_put(ob, text.as_ptr(), text.len()); }
733 ob: *mut hoedown_buffer,
734 text: *const hoedown_buffer,
735 _: *const hoedown_renderer_data,
738 let content = if text.is_null() {
741 let bytes = unsafe { (*text).as_bytes() };
742 let s = str::from_utf8(bytes).unwrap();
743 collapse_whitespace(s)
746 let content = format!("<code>{}</code>", Escape(&content));
748 hoedown_buffer_put(ob, content.as_ptr(), content.len());
750 // Return anything except 0, which would mean "also print the code span verbatim".
755 let ob = hoedown_buffer_new(DEF_OUNIT);
756 let renderer = hoedown_html_renderer_new(html_flags, 0);
757 let mut opaque = MyOpaque {
758 dfltblk: (*renderer).blockcode.unwrap(),
759 toc_builder: if print_toc {Some(TocBuilder::new())} else {None}
761 (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
762 = &mut opaque as *mut _ as *mut libc::c_void;
763 (*renderer).blockcode = Some(block);
764 (*renderer).header = Some(header);
765 (*renderer).codespan = Some(codespan);
767 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
768 hoedown_document_render(document, ob, s.as_ptr(),
769 s.len() as libc::size_t);
770 hoedown_document_free(document);
772 hoedown_html_renderer_free(renderer);
774 let mut ret = opaque.toc_builder.map_or(Ok(()), |builder| {
775 write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
779 let buf = (*ob).as_bytes();
780 ret = w.write_str(str::from_utf8(buf).unwrap());
782 hoedown_buffer_free(ob);
787 pub fn old_find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
788 extern fn block(_ob: *mut hoedown_buffer,
789 text: *const hoedown_buffer,
790 lang: *const hoedown_buffer,
791 data: *const hoedown_renderer_data,
792 line: libc::size_t) {
794 if text.is_null() { return }
795 let block_info = if lang.is_null() {
796 LangString::all_false()
798 let lang = (*lang).as_bytes();
799 let s = str::from_utf8(lang).unwrap();
802 if !block_info.rust { return }
803 let text = (*text).as_bytes();
804 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
805 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
806 let text = str::from_utf8(text).unwrap();
807 let lines = text.lines().map(|l| map_line(l).for_code());
808 let text = lines.collect::<Vec<&str>>().join("\n");
809 let filename = tests.get_filename();
811 if tests.render_type == RenderType::Hoedown {
812 let line = tests.get_line() + line;
813 tests.add_test(text.to_owned(),
814 block_info.should_panic, block_info.no_run,
815 block_info.ignore, block_info.test_harness,
816 block_info.compile_fail, block_info.error_codes,
817 line, filename, block_info.allow_fail);
819 tests.add_old_test(text, filename);
824 extern fn header(_ob: *mut hoedown_buffer,
825 text: *const hoedown_buffer,
826 level: libc::c_int, data: *const hoedown_renderer_data,
829 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
830 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
832 tests.register_header("", level as u32);
834 let text = (*text).as_bytes();
835 let text = str::from_utf8(text).unwrap();
836 tests.register_header(text, level as u32);
841 tests.set_position(position);
843 let ob = hoedown_buffer_new(DEF_OUNIT);
844 let renderer = hoedown_html_renderer_new(0, 0);
845 (*renderer).blockcode = Some(block);
846 (*renderer).header = Some(header);
847 (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
848 = tests as *mut _ as *mut libc::c_void;
850 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
851 hoedown_document_render(document, ob, doc.as_ptr(),
852 doc.len() as libc::size_t);
853 hoedown_document_free(document);
855 hoedown_html_renderer_free(renderer);
856 hoedown_buffer_free(ob);
860 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
861 tests.set_position(position);
863 let mut parser = Parser::new(doc);
864 let mut prev_offset = 0;
865 let mut nb_lines = 0;
866 let mut register_header = None;
867 'main: while let Some(event) = parser.next() {
869 Event::Start(Tag::CodeBlock(s)) => {
870 let block_info = if s.is_empty() {
871 LangString::all_false()
873 LangString::parse(&*s)
875 if !block_info.rust {
878 let mut test_s = String::new();
879 let mut offset = None;
881 let event = parser.next();
882 if let Some(event) = event {
884 Event::End(Tag::CodeBlock(_)) => break,
885 Event::Text(ref s) => {
887 if offset.is_none() {
888 offset = Some(parser.get_offset());
897 let offset = offset.unwrap_or(0);
898 let lines = test_s.lines().map(|l| map_line(l).for_code());
899 let text = lines.collect::<Vec<&str>>().join("\n");
900 nb_lines += doc[prev_offset..offset].lines().count();
901 let line = tests.get_line() + (nb_lines - 1);
902 let filename = tests.get_filename();
903 tests.add_test(text.to_owned(),
904 block_info.should_panic, block_info.no_run,
905 block_info.ignore, block_info.test_harness,
906 block_info.compile_fail, block_info.error_codes,
907 line, filename, block_info.allow_fail);
908 prev_offset = offset;
910 Event::Start(Tag::Header(level)) => {
911 register_header = Some(level as u32);
913 Event::Text(ref s) if register_header.is_some() => {
914 let level = register_header.unwrap();
916 tests.register_header("", level);
918 tests.register_header(s, level);
920 register_header = None;
927 #[derive(Eq, PartialEq, Clone, Debug)]
936 error_codes: Vec<String>,
941 fn all_false() -> LangString {
943 original: String::new(),
947 rust: true, // NB This used to be `notrust = false`
950 error_codes: Vec::new(),
955 fn parse(string: &str) -> LangString {
956 let mut seen_rust_tags = false;
957 let mut seen_other_tags = false;
958 let mut data = LangString::all_false();
959 let mut allow_compile_fail = false;
960 let mut allow_error_code_check = false;
961 if UnstableFeatures::from_environment().is_nightly_build() {
962 allow_compile_fail = true;
963 allow_error_code_check = true;
966 data.original = string.to_owned();
967 let tokens = string.split(|c: char|
968 !(c == '_' || c == '-' || c.is_alphanumeric())
971 for token in tokens {
975 data.should_panic = true;
976 seen_rust_tags = seen_other_tags == false;
978 "no_run" => { data.no_run = true; seen_rust_tags = !seen_other_tags; }
979 "ignore" => { data.ignore = true; seen_rust_tags = !seen_other_tags; }
980 "allow_fail" => { data.allow_fail = true; seen_rust_tags = !seen_other_tags; }
981 "rust" => { data.rust = true; seen_rust_tags = true; }
983 data.test_harness = true;
984 seen_rust_tags = !seen_other_tags || seen_rust_tags;
986 "compile_fail" if allow_compile_fail => {
987 data.compile_fail = true;
988 seen_rust_tags = !seen_other_tags || seen_rust_tags;
991 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
992 if let Ok(_) = x[1..].parse::<u32>() {
993 data.error_codes.push(x.to_owned());
994 seen_rust_tags = !seen_other_tags || seen_rust_tags;
996 seen_other_tags = true;
999 _ => { seen_other_tags = true }
1003 data.rust &= !seen_other_tags || seen_rust_tags;
1009 impl<'a> fmt::Display for Markdown<'a> {
1010 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1011 let Markdown(md, render_type) = *self;
1013 // This is actually common enough to special-case
1014 if md.is_empty() { return Ok(()) }
1015 if render_type == RenderType::Hoedown {
1016 render(fmt, md, false, 0)
1018 let mut opts = Options::empty();
1019 opts.insert(OPTION_ENABLE_TABLES);
1020 opts.insert(OPTION_ENABLE_FOOTNOTES);
1022 let p = Parser::new_ext(md, opts);
1024 let mut s = String::with_capacity(md.len() * 3 / 2);
1026 html::push_html(&mut s,
1027 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
1034 impl<'a> fmt::Display for MarkdownWithToc<'a> {
1035 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1036 let MarkdownWithToc(md, render_type) = *self;
1038 if render_type == RenderType::Hoedown {
1039 render(fmt, md, true, 0)
1041 let mut opts = Options::empty();
1042 opts.insert(OPTION_ENABLE_TABLES);
1043 opts.insert(OPTION_ENABLE_FOOTNOTES);
1045 let p = Parser::new_ext(md, opts);
1047 let mut s = String::with_capacity(md.len() * 3 / 2);
1049 let mut toc = TocBuilder::new();
1051 html::push_html(&mut s,
1052 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, Some(&mut toc)))));
1054 write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
1061 impl<'a> fmt::Display for MarkdownHtml<'a> {
1062 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1063 let MarkdownHtml(md, render_type) = *self;
1065 // This is actually common enough to special-case
1066 if md.is_empty() { return Ok(()) }
1067 if render_type == RenderType::Hoedown {
1068 render(fmt, md, false, HOEDOWN_HTML_ESCAPE)
1070 let mut opts = Options::empty();
1071 opts.insert(OPTION_ENABLE_TABLES);
1072 opts.insert(OPTION_ENABLE_FOOTNOTES);
1074 let p = Parser::new_ext(md, opts);
1076 // Treat inline HTML as plain text.
1077 let p = p.map(|event| match event {
1078 Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
1082 let mut s = String::with_capacity(md.len() * 3 / 2);
1084 html::push_html(&mut s,
1085 Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
1092 impl<'a> fmt::Display for MarkdownSummaryLine<'a> {
1093 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1094 let MarkdownSummaryLine(md) = *self;
1095 // This is actually common enough to special-case
1096 if md.is_empty() { return Ok(()) }
1098 let p = Parser::new(md);
1100 let mut s = String::new();
1102 html::push_html(&mut s, SummaryLine::new(p));
1108 pub fn plain_summary_line(md: &str) -> String {
1109 struct ParserWrapper<'a> {
1115 impl<'a> Iterator for ParserWrapper<'a> {
1118 fn next(&mut self) -> Option<String> {
1119 let next_event = self.inner.next();
1120 if next_event.is_none() {
1123 let next_event = next_event.unwrap();
1124 let (ret, is_in) = match next_event {
1125 Event::Start(Tag::Paragraph) => (None, 1),
1126 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
1127 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
1128 Event::Start(Tag::Header(_)) => (None, 1),
1129 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
1130 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
1133 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
1134 self.is_in += is_in;
1137 self.is_first = false;
1144 let mut s = String::with_capacity(md.len() * 3 / 2);
1145 let mut p = ParserWrapper {
1146 inner: Parser::new(md),
1150 while let Some(t) = p.next() {
1160 use super::{LangString, Markdown, MarkdownHtml};
1161 use super::plain_summary_line;
1162 use super::RenderType;
1163 use html::render::reset_ids;
1166 fn test_lang_string_parse() {
1168 should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
1169 compile_fail: bool, allow_fail: bool, error_codes: Vec<String>) {
1170 assert_eq!(LangString::parse(s), LangString {
1178 original: s.to_owned(),
1183 fn v() -> Vec<String> {
1187 // marker | should_panic| no_run| ignore| rust | test_harness| compile_fail
1188 // | allow_fail | error_codes
1189 t("", false, false, false, true, false, false, false, v());
1190 t("rust", false, false, false, true, false, false, false, v());
1191 t("sh", false, false, false, false, false, false, false, v());
1192 t("ignore", false, false, true, true, false, false, false, v());
1193 t("should_panic", true, false, false, true, false, false, false, v());
1194 t("no_run", false, true, false, true, false, false, false, v());
1195 t("test_harness", false, false, false, true, true, false, false, v());
1196 t("compile_fail", false, true, false, true, false, true, false, v());
1197 t("allow_fail", false, false, false, true, false, false, true, v());
1198 t("{.no_run .example}", false, true, false, true, false, false, false, v());
1199 t("{.sh .should_panic}", true, false, false, false, false, false, false, v());
1200 t("{.example .rust}", false, false, false, true, false, false, false, v());
1201 t("{.test_harness .rust}", false, false, false, true, true, false, false, v());
1202 t("text, no_run", false, true, false, false, false, false, false, v());
1203 t("text,no_run", false, true, false, false, false, false, false, v());
1208 let markdown = "# title";
1209 format!("{}", Markdown(markdown, RenderType::Pulldown));
1215 fn t(input: &str, expect: &str) {
1216 let output = format!("{}", Markdown(input, RenderType::Pulldown));
1217 assert_eq!(output, expect, "original: {}", input);
1221 t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
1222 <a href=\"#foo-bar\">Foo bar</a></h1>");
1223 t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
1224 header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
1225 t("### **Foo** *bar* baz!?!& -_qux_-%",
1226 "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
1227 <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
1228 <em>bar</em> baz!?!& -<em>qux</em>-%</a></h3>");
1229 t("#### **Foo?** & \\*bar?!* _`baz`_ ❤ #qux",
1230 "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
1231 <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> & *bar?!* \
1232 <em><code>baz</code></em> ❤ #qux</a></h4>");
1236 fn test_header_ids_multiple_blocks() {
1237 fn t(input: &str, expect: &str) {
1238 let output = format!("{}", Markdown(input, RenderType::Pulldown));
1239 assert_eq!(output, expect, "original: {}", input);
1243 t("# Example", "<h1 id=\"example\" class=\"section-header\">\
1244 <a href=\"#example\">Example</a></h1>");
1245 t("# Panics", "<h1 id=\"panics\" class=\"section-header\">\
1246 <a href=\"#panics\">Panics</a></h1>");
1247 t("# Example", "<h1 id=\"example-1\" class=\"section-header\">\
1248 <a href=\"#example-1\">Example</a></h1>");
1249 t("# Main", "<h1 id=\"main-1\" class=\"section-header\">\
1250 <a href=\"#main-1\">Main</a></h1>");
1251 t("# Example", "<h1 id=\"example-2\" class=\"section-header\">\
1252 <a href=\"#example-2\">Example</a></h1>");
1253 t("# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
1254 <a href=\"#panics-1\">Panics</a></h1>");
1262 fn test_plain_summary_line() {
1263 fn t(input: &str, expect: &str) {
1264 let output = plain_summary_line(input);
1265 assert_eq!(output, expect, "original: {}", input);
1268 t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
1269 t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
1270 t("code `let x = i32;` ...", "code `let x = i32;` ...");
1271 t("type `Type<'static>` ...", "type `Type<'static>` ...");
1272 t("# top header", "top header");
1273 t("## header", "header");
1277 fn test_markdown_html_escape() {
1278 fn t(input: &str, expect: &str) {
1279 let output = format!("{}", MarkdownHtml(input, RenderType::Pulldown));
1280 assert_eq!(output, expect, "original: {}", input);
1283 t("`Struct<'a, T>`", "<p><code>Struct<'a, T></code></p>\n");
1284 t("Struct<'a, T>", "<p>Struct<'a, T></p>\n");
1285 t("Struct<br>", "<p>Struct<br></p>\n");