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 //! #![feature(rustc_private)]
21 //! use rustdoc::html::markdown::{RenderType, Markdown};
23 //! let s = "My *markdown* _text_";
24 //! let html = format!("{}", Markdown(s, RenderType::Pulldown));
25 //! // ... something using html
28 #![allow(non_camel_case_types)]
33 use std::ascii::AsciiExt;
34 use std::cell::RefCell;
35 use std::collections::{HashMap, VecDeque};
36 use std::default::Default;
37 use std::fmt::{self, Write};
39 use syntax::feature_gate::UnstableFeatures;
40 use syntax::codemap::Span;
42 use html::render::derive_id;
43 use html::toc::TocBuilder;
45 use html::escape::Escape;
48 use pulldown_cmark::{html, Event, Tag, Parser};
49 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
51 #[derive(PartialEq, Debug, Clone, Copy)]
57 /// A unit struct which has the `fmt::Display` trait implemented. When
58 /// formatted, this struct will emit the HTML corresponding to the rendered
59 /// version of the contained markdown string.
60 // The second parameter is whether we need a shorter version or not.
61 pub struct Markdown<'a>(pub &'a str, pub RenderType);
62 /// A unit struct like `Markdown`, that renders the markdown with a
63 /// table of contents.
64 pub struct MarkdownWithToc<'a>(pub &'a str, pub RenderType);
65 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
66 pub struct MarkdownHtml<'a>(pub &'a str, pub RenderType);
67 /// A unit struct like `Markdown`, that renders only the first paragraph.
68 pub struct MarkdownSummaryLine<'a>(pub &'a str);
70 /// Controls whether a line will be hidden or shown in HTML output.
72 /// All lines are used in documentation tests.
79 fn for_html(self) -> Option<&'a str> {
81 Line::Shown(l) => Some(l),
82 Line::Hidden(_) => None,
86 fn for_code(self) -> &'a str {
94 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
95 // have no easy way of removing a potential single space after the hashes, which
96 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
97 // order to fix it we'd have to iterate to find the first non-# character, and
98 // then reallocate to remove it; which would make us return a String.
99 fn map_line(s: &str) -> Line {
100 let trimmed = s.trim();
101 if trimmed.starts_with("##") {
102 Line::Shown(&trimmed[1..])
103 } else if trimmed.starts_with("# ") {
105 Line::Hidden(&trimmed[2..])
106 } else if trimmed == "#" {
107 // We cannot handle '#text' because it could be #[attr].
114 /// Returns a new string with all consecutive whitespace collapsed into
117 /// Any leading or trailing whitespace will be trimmed.
118 fn collapse_whitespace(s: &str) -> String {
119 s.split_whitespace().collect::<Vec<_>>().join(" ")
122 /// Convert chars from a title for an id.
124 /// "Hello, world!" -> "hello-world"
125 fn slugify(c: char) -> Option<char> {
126 if c.is_alphanumeric() || c == '-' || c == '_' {
128 Some(c.to_ascii_lowercase())
132 } else if c.is_whitespace() && c.is_ascii() {
139 // Information about the playground if a URL has been specified, containing an
140 // optional crate name and the URL.
141 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
145 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
146 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
150 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
151 fn new(iter: I) -> Self {
158 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
159 type Item = Event<'a>;
161 fn next(&mut self) -> Option<Self::Item> {
162 let event = self.inner.next();
165 if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
166 let parse_result = LangString::parse(&lang);
167 if !parse_result.rust {
168 return Some(Event::Start(Tag::CodeBlock(lang)));
170 compile_fail = parse_result.compile_fail;
171 ignore = parse_result.ignore;
176 let mut origtext = String::new();
177 for event in &mut self.inner {
179 Event::End(Tag::CodeBlock(..)) => break,
180 Event::Text(ref s) => {
181 origtext.push_str(s);
186 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
187 let text = lines.collect::<Vec<&str>>().join("\n");
188 PLAYGROUND.with(|play| {
189 // insert newline to clearly separate it from the
190 // previous block so we can shorten the html output
191 let mut s = String::from("\n");
192 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
196 let test = origtext.lines()
197 .map(|l| map_line(l).for_code())
198 .collect::<Vec<&str>>().join("\n");
199 let krate = krate.as_ref().map(|s| &**s);
200 let test = test::make_test(&test, krate, false,
201 &Default::default());
202 let channel = if test.contains("#![feature(") {
203 "&version=nightly"
207 // These characters don't need to be escaped in a URI.
208 // FIXME: use a library function for percent encoding.
209 fn dont_escape(c: u8) -> bool {
210 (b'a' <= c && c <= b'z') ||
211 (b'A' <= c && c <= b'Z') ||
212 (b'0' <= c && c <= b'9') ||
213 c == b'-' || c == b'_' || c == b'.' ||
214 c == b'~' || c == b'!' || c == b'\'' ||
215 c == b'(' || c == b')' || c == b'*'
217 let mut test_escaped = String::new();
218 for b in test.bytes() {
220 test_escaped.push(char::from(b));
222 write!(test_escaped, "%{:02X}", b).unwrap();
226 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
227 url, test_escaped, channel
230 let tooltip = if ignore {
231 Some(("Be careful when using this code, it's not being tested!", "ignore"))
232 } else if compile_fail {
233 Some(("This code doesn't compile so be extra careful!", "compile_fail"))
237 s.push_str(&highlight::render_with_highlighting(
239 Some(&format!("rust-example-rendered{}",
240 if ignore { " ignore" }
241 else if compile_fail { " compile_fail" }
244 playground_button.as_ref().map(String::as_str),
246 Some(Event::Html(s.into()))
251 /// Make headings links with anchor ids and build up TOC.
252 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
254 toc: Option<&'b mut TocBuilder>,
255 buf: VecDeque<Event<'a>>,
258 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
259 fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
263 buf: VecDeque::new(),
268 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
269 type Item = Event<'a>;
271 fn next(&mut self) -> Option<Self::Item> {
272 if let Some(e) = self.buf.pop_front() {
276 let event = self.inner.next();
277 if let Some(Event::Start(Tag::Header(level))) = event {
278 let mut id = String::new();
279 for event in &mut self.inner {
281 Event::End(Tag::Header(..)) => break,
282 Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
285 self.buf.push_back(event);
287 let id = derive_id(id);
289 if let Some(ref mut builder) = self.toc {
290 let mut html_header = String::new();
291 html::push_html(&mut html_header, self.buf.iter().cloned());
292 let sec = builder.push(level as u32, html_header, id.clone());
293 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
296 self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
298 let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
302 return Some(Event::InlineHtml(start_tags.into()));
308 /// Extracts just the first paragraph.
309 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
315 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
316 fn new(iter: I) -> Self {
325 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
326 type Item = Event<'a>;
328 fn next(&mut self) -> Option<Self::Item> {
329 if self.started && self.depth == 0 {
335 let event = self.inner.next();
337 Some(Event::Start(..)) => self.depth += 1,
338 Some(Event::End(..)) => self.depth -= 1,
345 /// Moves all footnote definitions to the end and add back links to the
347 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
349 footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
352 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
353 fn new(iter: I) -> Self {
356 footnotes: HashMap::new(),
359 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
360 let new_id = self.footnotes.keys().count() + 1;
361 let key = key.to_owned();
362 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
366 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
367 type Item = Event<'a>;
369 fn next(&mut self) -> Option<Self::Item> {
371 match self.inner.next() {
372 Some(Event::FootnoteReference(ref reference)) => {
373 let entry = self.get_entry(&reference);
374 let reference = format!("<sup id=\"supref{0}\"><a href=\"#ref{0}\">{0}\
377 return Some(Event::Html(reference.into()));
379 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
380 let mut content = Vec::new();
381 for event in &mut self.inner {
382 if let Event::End(Tag::FootnoteDefinition(..)) = event {
387 let entry = self.get_entry(&def);
388 (*entry).0 = content;
390 Some(e) => return Some(e),
392 if !self.footnotes.is_empty() {
393 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
394 v.sort_by(|a, b| a.1.cmp(&b.1));
395 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
396 for (mut content, id) in v {
397 write!(ret, "<li id=\"ref{}\">", id).unwrap();
398 let mut is_paragraph = false;
399 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
403 html::push_html(&mut ret, content.into_iter());
405 " <a href=\"#supref{}\" rev=\"footnote\">↩</a>",
408 ret.push_str("</p>");
410 ret.push_str("</li>");
412 ret.push_str("</ol></div>");
413 return Some(Event::Html(ret.into()));
423 const DEF_OUNIT: libc::size_t = 64;
424 const HOEDOWN_EXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 11;
425 const HOEDOWN_EXT_TABLES: libc::c_uint = 1 << 0;
426 const HOEDOWN_EXT_FENCED_CODE: libc::c_uint = 1 << 1;
427 const HOEDOWN_EXT_AUTOLINK: libc::c_uint = 1 << 3;
428 const HOEDOWN_EXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
429 const HOEDOWN_EXT_SUPERSCRIPT: libc::c_uint = 1 << 8;
430 const HOEDOWN_EXT_FOOTNOTES: libc::c_uint = 1 << 2;
431 const HOEDOWN_HTML_ESCAPE: libc::c_uint = 1 << 1;
433 const HOEDOWN_EXTENSIONS: libc::c_uint =
434 HOEDOWN_EXT_NO_INTRA_EMPHASIS | HOEDOWN_EXT_TABLES |
435 HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_AUTOLINK |
436 HOEDOWN_EXT_STRIKETHROUGH | HOEDOWN_EXT_SUPERSCRIPT |
437 HOEDOWN_EXT_FOOTNOTES;
439 enum hoedown_document {}
441 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
442 *const hoedown_buffer, *const hoedown_renderer_data,
445 type blockquotefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
446 *const hoedown_renderer_data, libc::size_t);
448 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
449 libc::c_int, *const hoedown_renderer_data,
452 type blockhtmlfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
453 *const hoedown_renderer_data, libc::size_t);
455 type codespanfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
456 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
458 type linkfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
459 *const hoedown_buffer, *const hoedown_buffer,
460 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
462 type entityfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
463 *const hoedown_renderer_data, libc::size_t);
465 type normaltextfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
466 *const hoedown_renderer_data, libc::size_t);
469 struct hoedown_renderer_data {
470 opaque: *mut libc::c_void,
474 struct hoedown_renderer {
475 opaque: *mut libc::c_void,
477 blockcode: Option<blockcodefn>,
478 blockquote: Option<blockquotefn>,
479 header: Option<headerfn>,
481 other_block_level_callbacks: [libc::size_t; 11],
483 blockhtml: Option<blockhtmlfn>,
485 /* span level callbacks - NULL or return 0 prints the span verbatim */
486 autolink: libc::size_t, // unused
487 codespan: Option<codespanfn>,
488 other_span_level_callbacks_1: [libc::size_t; 7],
489 link: Option<linkfn>,
490 other_span_level_callbacks_2: [libc::size_t; 6],
492 /* low level callbacks - NULL copies input directly into the output */
493 entity: Option<entityfn>,
494 normal_text: Option<normaltextfn>,
496 /* header and footer */
497 other_callbacks: [libc::size_t; 2],
501 struct hoedown_html_renderer_state {
502 opaque: *mut libc::c_void,
503 toc_data: html_toc_data,
505 link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
506 *const hoedown_buffer,
507 *const hoedown_renderer_data)>,
511 struct html_toc_data {
512 header_count: libc::c_int,
513 current_level: libc::c_int,
514 level_offset: libc::c_int,
515 nesting_level: libc::c_int,
519 struct hoedown_buffer {
527 dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
528 *const hoedown_buffer, *const hoedown_renderer_data,
530 toc_builder: Option<TocBuilder>,
534 fn hoedown_html_renderer_new(render_flags: libc::c_uint,
535 nesting_level: libc::c_int)
536 -> *mut hoedown_renderer;
537 fn hoedown_html_renderer_free(renderer: *mut hoedown_renderer);
539 fn hoedown_document_new(rndr: *const hoedown_renderer,
540 extensions: libc::c_uint,
541 max_nesting: libc::size_t) -> *mut hoedown_document;
542 fn hoedown_document_render(doc: *mut hoedown_document,
543 ob: *mut hoedown_buffer,
545 doc_size: libc::size_t);
546 fn hoedown_document_free(md: *mut hoedown_document);
548 fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer;
549 fn hoedown_buffer_free(b: *mut hoedown_buffer);
550 fn hoedown_buffer_put(b: *mut hoedown_buffer, c: *const u8, len: libc::size_t);
553 impl hoedown_buffer {
554 fn as_bytes(&self) -> &[u8] {
555 unsafe { slice::from_raw_parts(self.data, self.size as usize) }
559 pub fn render(w: &mut fmt::Formatter,
562 html_flags: libc::c_uint) -> fmt::Result {
563 extern fn block(ob: *mut hoedown_buffer, orig_text: *const hoedown_buffer,
564 lang: *const hoedown_buffer, data: *const hoedown_renderer_data,
565 line: libc::size_t) {
567 if orig_text.is_null() { return }
569 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
570 let my_opaque: &MyOpaque = &*((*opaque).opaque as *const MyOpaque);
571 let text = (*orig_text).as_bytes();
572 let origtext = str::from_utf8(text).unwrap();
573 let origtext = origtext.trim_left();
574 debug!("docblock: ==============\n{:?}\n=======", text);
575 let mut compile_fail = false;
576 let mut ignore = false;
578 let rendered = if lang.is_null() || origtext.is_empty() {
581 let rlang = (*lang).as_bytes();
582 let rlang = str::from_utf8(rlang).unwrap();
583 let parse_result = LangString::parse(rlang);
584 compile_fail = parse_result.compile_fail;
585 ignore = parse_result.ignore;
586 if !parse_result.rust {
587 (my_opaque.dfltblk)(ob, orig_text, lang,
588 opaque as *const hoedown_renderer_data,
596 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
597 let text = lines.collect::<Vec<&str>>().join("\n");
598 if rendered { return }
599 PLAYGROUND.with(|play| {
600 // insert newline to clearly separate it from the
601 // previous block so we can shorten the html output
602 let mut s = String::from("\n");
603 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
607 let test = origtext.lines()
608 .map(|l| map_line(l).for_code())
609 .collect::<Vec<&str>>().join("\n");
610 let krate = krate.as_ref().map(|s| &**s);
611 let test = test::make_test(&test, krate, false,
612 &Default::default());
613 let channel = if test.contains("#![feature(") {
614 "&version=nightly"
618 // These characters don't need to be escaped in a URI.
619 // FIXME: use a library function for percent encoding.
620 fn dont_escape(c: u8) -> bool {
621 (b'a' <= c && c <= b'z') ||
622 (b'A' <= c && c <= b'Z') ||
623 (b'0' <= c && c <= b'9') ||
624 c == b'-' || c == b'_' || c == b'.' ||
625 c == b'~' || c == b'!' || c == b'\'' ||
626 c == b'(' || c == b')' || c == b'*'
628 let mut test_escaped = String::new();
629 for b in test.bytes() {
631 test_escaped.push(char::from(b));
633 write!(test_escaped, "%{:02X}", b).unwrap();
637 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
638 url, test_escaped, channel
641 let tooltip = if ignore {
642 Some(("Be careful when using this code, it's not being tested!", "ignore"))
643 } else if compile_fail {
644 Some(("This code doesn't compile so be extra careful!", "compile_fail"))
648 s.push_str(&highlight::render_with_highlighting(
650 Some(&format!("rust-example-rendered{}",
651 if ignore { " ignore" }
652 else if compile_fail { " compile_fail" }
655 playground_button.as_ref().map(String::as_str),
657 hoedown_buffer_put(ob, s.as_ptr(), s.len());
662 extern fn header(ob: *mut hoedown_buffer, text: *const hoedown_buffer,
663 level: libc::c_int, data: *const hoedown_renderer_data,
665 // hoedown does this, we may as well too
666 unsafe { hoedown_buffer_put(ob, "\n".as_ptr(), 1); }
668 // Extract the text provided
669 let s = if text.is_null() {
672 let s = unsafe { (*text).as_bytes() };
673 str::from_utf8(&s).unwrap().to_owned()
676 // Discard '<em>', '<code>' tags and some escaped characters,
677 // transform the contents of the header into a hyphenated string
678 // without non-alphanumeric characters other than '-' and '_'.
680 // This is a terrible hack working around how hoedown gives us rendered
681 // html for text rather than the raw text.
682 let mut id = s.clone();
683 let repl_sub = vec!["<em>", "</em>", "<code>", "</code>",
684 "<strong>", "</strong>",
685 "<", ">", "&", "'", """];
686 for sub in repl_sub {
687 id = id.replace(sub, "");
689 let id = id.chars().filter_map(|c| {
690 if c.is_alphanumeric() || c == '-' || c == '_' {
692 Some(c.to_ascii_lowercase())
696 } else if c.is_whitespace() && c.is_ascii() {
701 }).collect::<String>();
703 let opaque = unsafe { (*data).opaque as *mut hoedown_html_renderer_state };
704 let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
706 let id = derive_id(id);
708 let sec = opaque.toc_builder.as_mut().map_or("".to_owned(), |builder| {
709 format!("{} ", builder.push(level as u32, s.clone(), id.clone()))
713 let text = format!("<h{lvl} id='{id}' class='section-header'>\
714 <a href='#{id}'>{sec}{}</a></h{lvl}>",
715 s, lvl = level, id = id, sec = sec);
717 unsafe { hoedown_buffer_put(ob, text.as_ptr(), text.len()); }
721 ob: *mut hoedown_buffer,
722 text: *const hoedown_buffer,
723 _: *const hoedown_renderer_data,
726 let content = if text.is_null() {
729 let bytes = unsafe { (*text).as_bytes() };
730 let s = str::from_utf8(bytes).unwrap();
731 collapse_whitespace(s)
734 let content = format!("<code>{}</code>", Escape(&content));
736 hoedown_buffer_put(ob, content.as_ptr(), content.len());
738 // Return anything except 0, which would mean "also print the code span verbatim".
743 let ob = hoedown_buffer_new(DEF_OUNIT);
744 let renderer = hoedown_html_renderer_new(html_flags, 0);
745 let mut opaque = MyOpaque {
746 dfltblk: (*renderer).blockcode.unwrap(),
747 toc_builder: if print_toc {Some(TocBuilder::new())} else {None}
749 (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
750 = &mut opaque as *mut _ as *mut libc::c_void;
751 (*renderer).blockcode = Some(block);
752 (*renderer).header = Some(header);
753 (*renderer).codespan = Some(codespan);
755 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
756 hoedown_document_render(document, ob, s.as_ptr(),
757 s.len() as libc::size_t);
758 hoedown_document_free(document);
760 hoedown_html_renderer_free(renderer);
762 let mut ret = opaque.toc_builder.map_or(Ok(()), |builder| {
763 write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
767 let buf = (*ob).as_bytes();
768 ret = w.write_str(str::from_utf8(buf).unwrap());
770 hoedown_buffer_free(ob);
775 pub fn old_find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
776 extern fn block(_ob: *mut hoedown_buffer,
777 text: *const hoedown_buffer,
778 lang: *const hoedown_buffer,
779 data: *const hoedown_renderer_data,
780 line: libc::size_t) {
782 if text.is_null() { return }
783 let block_info = if lang.is_null() {
784 LangString::all_false()
786 let lang = (*lang).as_bytes();
787 let s = str::from_utf8(lang).unwrap();
790 if !block_info.rust { return }
791 let text = (*text).as_bytes();
792 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
793 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
794 let text = str::from_utf8(text).unwrap();
795 let lines = text.lines().map(|l| map_line(l).for_code());
796 let text = lines.collect::<Vec<&str>>().join("\n");
797 let filename = tests.get_filename();
799 if tests.render_type == RenderType::Hoedown {
800 let line = tests.get_line() + line;
801 tests.add_test(text.to_owned(),
802 block_info.should_panic, block_info.no_run,
803 block_info.ignore, block_info.test_harness,
804 block_info.compile_fail, block_info.error_codes,
805 line, filename, block_info.allow_fail);
807 tests.add_old_test(text, filename);
812 extern fn header(_ob: *mut hoedown_buffer,
813 text: *const hoedown_buffer,
814 level: libc::c_int, data: *const hoedown_renderer_data,
817 let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
818 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
820 tests.register_header("", level as u32);
822 let text = (*text).as_bytes();
823 let text = str::from_utf8(text).unwrap();
824 tests.register_header(text, level as u32);
829 tests.set_position(position);
831 let ob = hoedown_buffer_new(DEF_OUNIT);
832 let renderer = hoedown_html_renderer_new(0, 0);
833 (*renderer).blockcode = Some(block);
834 (*renderer).header = Some(header);
835 (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
836 = tests as *mut _ as *mut libc::c_void;
838 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
839 hoedown_document_render(document, ob, doc.as_ptr(),
840 doc.len() as libc::size_t);
841 hoedown_document_free(document);
843 hoedown_html_renderer_free(renderer);
844 hoedown_buffer_free(ob);
848 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
849 tests.set_position(position);
851 let mut parser = Parser::new(doc);
852 let mut prev_offset = 0;
853 let mut nb_lines = 0;
854 let mut register_header = None;
855 'main: while let Some(event) = parser.next() {
857 Event::Start(Tag::CodeBlock(s)) => {
858 let block_info = if s.is_empty() {
859 LangString::all_false()
861 LangString::parse(&*s)
863 if !block_info.rust {
866 let mut test_s = String::new();
867 let mut offset = None;
869 let event = parser.next();
870 if let Some(event) = event {
872 Event::End(Tag::CodeBlock(_)) => break,
873 Event::Text(ref s) => {
875 if offset.is_none() {
876 offset = Some(parser.get_offset());
885 let offset = offset.unwrap_or(0);
886 let lines = test_s.lines().map(|l| map_line(l).for_code());
887 let text = lines.collect::<Vec<&str>>().join("\n");
888 nb_lines += doc[prev_offset..offset].lines().count();
889 let line = tests.get_line() + (nb_lines - 1);
890 let filename = tests.get_filename();
891 tests.add_test(text.to_owned(),
892 block_info.should_panic, block_info.no_run,
893 block_info.ignore, block_info.test_harness,
894 block_info.compile_fail, block_info.error_codes,
895 line, filename, block_info.allow_fail);
896 prev_offset = offset;
898 Event::Start(Tag::Header(level)) => {
899 register_header = Some(level as u32);
901 Event::Text(ref s) if register_header.is_some() => {
902 let level = register_header.unwrap();
904 tests.register_header("", level);
906 tests.register_header(s, level);
908 register_header = None;
915 #[derive(Eq, PartialEq, Clone, Debug)]
924 error_codes: Vec<String>,
929 fn all_false() -> LangString {
931 original: String::new(),
935 rust: true, // NB This used to be `notrust = false`
938 error_codes: Vec::new(),
943 fn parse(string: &str) -> LangString {
944 let mut seen_rust_tags = false;
945 let mut seen_other_tags = false;
946 let mut data = LangString::all_false();
947 let mut allow_error_code_check = false;
948 if UnstableFeatures::from_environment().is_nightly_build() {
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;
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");