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 hoedown C-library
14 //! (bundled into the rust runtime). This module self-contains the C bindings
15 //! and necessary legwork to render markdown, and exposes all of the
16 //! functionality through a unit-struct, `Markdown`, which has an implementation
17 //! of `fmt::String`. Example usage:
20 //! use rustdoc::html::markdown::Markdown;
22 //! let s = "My *markdown* _text_";
23 //! let html = format!("{}", Markdown(s));
24 //! // ... something using html
28 #![allow(non_camel_case_types)]
31 use std::ascii::AsciiExt;
32 use std::ffi::CString;
33 use std::cell::RefCell;
34 use std::collections::HashMap;
39 use html::toc::TocBuilder;
41 use html::escape::Escape;
44 /// A unit struct which has the `fmt::String` trait implemented. When
45 /// formatted, this struct will emit the HTML corresponding to the rendered
46 /// version of the contained markdown string.
47 pub struct Markdown<'a>(pub &'a str);
48 /// A unit struct like `Markdown`, that renders the markdown with a
49 /// table of contents.
50 pub struct MarkdownWithToc<'a>(pub &'a str);
52 const DEF_OUNIT: libc::size_t = 64;
53 const HOEDOWN_EXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 10;
54 const HOEDOWN_EXT_TABLES: libc::c_uint = 1 << 0;
55 const HOEDOWN_EXT_FENCED_CODE: libc::c_uint = 1 << 1;
56 const HOEDOWN_EXT_AUTOLINK: libc::c_uint = 1 << 3;
57 const HOEDOWN_EXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
58 const HOEDOWN_EXT_SUPERSCRIPT: libc::c_uint = 1 << 8;
59 const HOEDOWN_EXT_FOOTNOTES: libc::c_uint = 1 << 2;
61 const HOEDOWN_EXTENSIONS: libc::c_uint =
62 HOEDOWN_EXT_NO_INTRA_EMPHASIS | HOEDOWN_EXT_TABLES |
63 HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_AUTOLINK |
64 HOEDOWN_EXT_STRIKETHROUGH | HOEDOWN_EXT_SUPERSCRIPT |
65 HOEDOWN_EXT_FOOTNOTES;
67 type hoedown_document = libc::c_void; // this is opaque to us
69 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
70 *const hoedown_buffer, *mut libc::c_void);
72 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
73 libc::c_int, *mut libc::c_void);
76 struct hoedown_renderer {
77 opaque: *mut hoedown_html_renderer_state,
78 blockcode: Option<blockcodefn>,
79 blockquote: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
81 blockhtml: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
83 header: Option<headerfn>,
84 other: [libc::size_t; 28],
88 struct hoedown_html_renderer_state {
89 opaque: *mut libc::c_void,
90 toc_data: html_toc_data,
92 link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
93 *const hoedown_buffer,
98 struct html_toc_data {
99 header_count: libc::c_int,
100 current_level: libc::c_int,
101 level_offset: libc::c_int,
102 nesting_level: libc::c_int,
106 dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
107 *const hoedown_buffer, *mut libc::c_void),
108 toc_builder: Option<TocBuilder>,
112 struct hoedown_buffer {
120 #[link(name = "hoedown", kind = "static")]
122 fn hoedown_html_renderer_new(render_flags: libc::c_uint,
123 nesting_level: libc::c_int)
124 -> *mut hoedown_renderer;
125 fn hoedown_html_renderer_free(renderer: *mut hoedown_renderer);
127 fn hoedown_document_new(rndr: *mut hoedown_renderer,
128 extensions: libc::c_uint,
129 max_nesting: libc::size_t) -> *mut hoedown_document;
130 fn hoedown_document_render(doc: *mut hoedown_document,
131 ob: *mut hoedown_buffer,
133 doc_size: libc::size_t);
134 fn hoedown_document_free(md: *mut hoedown_document);
136 fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer;
137 fn hoedown_buffer_puts(b: *mut hoedown_buffer, c: *const libc::c_char);
138 fn hoedown_buffer_free(b: *mut hoedown_buffer);
142 /// Returns Some(code) if `s` is a line that should be stripped from
143 /// documentation but used in example code. `code` is the portion of
144 /// `s` that should be used in tests. (None for lines that should be
146 fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
147 let trimmed = s.trim();
148 if trimmed.starts_with("# ") {
149 Some(trimmed.slice_from(2))
155 thread_local!(static USED_HEADER_MAP: RefCell<HashMap<String, uint>> = {
156 RefCell::new(HashMap::new())
159 thread_local!(pub static PLAYGROUND_KRATE: RefCell<Option<Option<String>>> = {
163 pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
164 extern fn block(ob: *mut hoedown_buffer, orig_text: *const hoedown_buffer,
165 lang: *const hoedown_buffer, opaque: *mut libc::c_void) {
167 if orig_text.is_null() { return }
169 let opaque = opaque as *mut hoedown_html_renderer_state;
170 let my_opaque: &MyOpaque = &*((*opaque).opaque as *const MyOpaque);
171 let text = slice::from_raw_buf(&(*orig_text).data,
172 (*orig_text).size as uint);
173 let origtext = str::from_utf8(text).unwrap();
174 debug!("docblock: ==============\n{:?}\n=======", text);
175 let rendered = if lang.is_null() {
178 let rlang = slice::from_raw_buf(&(*lang).data,
179 (*lang).size as uint);
180 let rlang = str::from_utf8(rlang).unwrap();
181 if !LangString::parse(rlang).rust {
182 (my_opaque.dfltblk)(ob, orig_text, lang,
183 opaque as *mut libc::c_void);
190 let lines = origtext.lines().filter(|l| {
191 stripped_filtered_line(*l).is_none()
193 let text = lines.collect::<Vec<&str>>().connect("\n");
194 if rendered { return }
195 PLAYGROUND_KRATE.with(|krate| {
196 let mut s = String::new();
197 krate.borrow().as_ref().map(|krate| {
198 let test = origtext.lines().map(|l| {
199 stripped_filtered_line(l).unwrap_or(l)
200 }).collect::<Vec<&str>>().connect("\n");
201 let krate = krate.as_ref().map(|s| s.as_slice());
202 let test = test::maketest(test.as_slice(), krate, false, false);
203 s.push_str(format!("<span class='rusttest'>{}</span>",
204 Escape(test.as_slice())).as_slice());
206 s.push_str(highlight::highlight(text.as_slice(),
208 Some("rust-example-rendered"))
210 let output = CString::from_vec(s.into_bytes());
211 hoedown_buffer_puts(ob, output.as_ptr());
216 extern fn header(ob: *mut hoedown_buffer, text: *const hoedown_buffer,
217 level: libc::c_int, opaque: *mut libc::c_void) {
218 // hoedown does this, we may as well too
219 unsafe { hoedown_buffer_puts(ob, "\n\0".as_ptr() as *const _); }
221 // Extract the text provided
222 let s = if text.is_null() {
226 slice::from_raw_buf(&(*text).data, (*text).size as uint)
228 str::from_utf8(s).unwrap().to_string()
231 // Transform the contents of the header into a hyphenated string
232 let id = s.words().map(|s| s.to_ascii_lowercase())
233 .collect::<Vec<String>>().connect("-");
235 // This is a terrible hack working around how hoedown gives us rendered
236 // html for text rather than the raw text.
238 let opaque = opaque as *mut hoedown_html_renderer_state;
239 let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
241 // Make sure our hyphenated ID is unique for this page
242 let id = USED_HEADER_MAP.with(|map| {
243 let id = id.replace("<code>", "").replace("</code>", "").to_string();
244 let id = match map.borrow_mut().get_mut(&id) {
246 Some(a) => { *a += 1; format!("{}-{}", id, *a - 1) }
248 map.borrow_mut().insert(id.clone(), 1);
252 let sec = match opaque.toc_builder {
253 Some(ref mut builder) => {
254 builder.push(level as u32, s.clone(), id.clone())
260 let text = format!(r##"<h{lvl} id="{id}" class='section-header'><a
261 href="#{id}">{sec}{}</a></h{lvl}>"##,
262 s, lvl = level, id = id,
263 sec = if sec.len() == 0 {
269 let text = CString::from_vec(text.into_bytes());
270 unsafe { hoedown_buffer_puts(ob, text.as_ptr()) }
276 let ob = hoedown_buffer_new(DEF_OUNIT);
277 let renderer = hoedown_html_renderer_new(0, 0);
278 let mut opaque = MyOpaque {
279 dfltblk: (*renderer).blockcode.unwrap(),
280 toc_builder: if print_toc {Some(TocBuilder::new())} else {None}
282 (*(*renderer).opaque).opaque = &mut opaque as *mut _ as *mut libc::c_void;
283 (*renderer).blockcode = Some(block as blockcodefn);
284 (*renderer).header = Some(header as headerfn);
286 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
287 hoedown_document_render(document, ob, s.as_ptr(),
288 s.len() as libc::size_t);
289 hoedown_document_free(document);
291 hoedown_html_renderer_free(renderer);
293 let mut ret = match opaque.toc_builder {
294 Some(b) => write!(w, "<nav id=\"TOC\">{}</nav>", b.into_toc()),
299 let buf = slice::from_raw_buf(&(*ob).data, (*ob).size as uint);
300 ret = w.write_str(str::from_utf8(buf).unwrap());
302 hoedown_buffer_free(ob);
307 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
308 extern fn block(_ob: *mut hoedown_buffer,
309 text: *const hoedown_buffer,
310 lang: *const hoedown_buffer,
311 opaque: *mut libc::c_void) {
313 if text.is_null() { return }
314 let block_info = if lang.is_null() {
315 LangString::all_false()
317 let lang = slice::from_raw_buf(&(*lang).data,
318 (*lang).size as uint);
319 let s = str::from_utf8(lang).unwrap();
322 if !block_info.rust { return }
323 let text = slice::from_raw_buf(&(*text).data, (*text).size as uint);
324 let opaque = opaque as *mut hoedown_html_renderer_state;
325 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
326 let text = str::from_utf8(text).unwrap();
327 let lines = text.lines().map(|l| {
328 stripped_filtered_line(l).unwrap_or(l)
330 let text = lines.collect::<Vec<&str>>().connect("\n");
331 tests.add_test(text.to_string(),
332 block_info.should_fail, block_info.no_run,
333 block_info.ignore, block_info.test_harness);
337 extern fn header(_ob: *mut hoedown_buffer,
338 text: *const hoedown_buffer,
339 level: libc::c_int, opaque: *mut libc::c_void) {
341 let opaque = opaque as *mut hoedown_html_renderer_state;
342 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
344 tests.register_header("", level as u32);
346 let text = slice::from_raw_buf(&(*text).data, (*text).size as uint);
347 let text = str::from_utf8(text).unwrap();
348 tests.register_header(text, level as u32);
354 let ob = hoedown_buffer_new(DEF_OUNIT);
355 let renderer = hoedown_html_renderer_new(0, 0);
356 (*renderer).blockcode = Some(block as blockcodefn);
357 (*renderer).header = Some(header as headerfn);
358 (*(*renderer).opaque).opaque = tests as *mut _ as *mut libc::c_void;
360 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
361 hoedown_document_render(document, ob, doc.as_ptr(),
362 doc.len() as libc::size_t);
363 hoedown_document_free(document);
365 hoedown_html_renderer_free(renderer);
366 hoedown_buffer_free(ob);
370 #[derive(Eq, PartialEq, Clone, Show)]
380 fn all_false() -> LangString {
385 rust: true, // NB This used to be `notrust = false`
390 fn parse(string: &str) -> LangString {
391 let mut seen_rust_tags = false;
392 let mut seen_other_tags = false;
393 let mut data = LangString::all_false();
395 let mut tokens = string.split(|&: c: char|
396 !(c == '_' || c == '-' || c.is_alphanumeric())
399 for token in tokens {
402 "should_fail" => { data.should_fail = true; seen_rust_tags = true; },
403 "no_run" => { data.no_run = true; seen_rust_tags = true; },
404 "ignore" => { data.ignore = true; seen_rust_tags = true; },
405 "rust" => { data.rust = true; seen_rust_tags = true; },
406 "test_harness" => { data.test_harness = true; seen_rust_tags = true; }
407 _ => { seen_other_tags = true }
411 data.rust &= !seen_other_tags || seen_rust_tags;
417 /// By default this markdown renderer generates anchors for each header in the
418 /// rendered document. The anchor name is the contents of the header separated
419 /// by hyphens, and a task-local map is used to disambiguate among duplicate
420 /// headers (numbers are appended).
422 /// This method will reset the local table for these headers. This is typically
423 /// used at the beginning of rendering an entire HTML page to reset from the
424 /// previous state (if any).
425 pub fn reset_headers() {
426 USED_HEADER_MAP.with(|s| s.borrow_mut().clear());
429 impl<'a> fmt::Display for Markdown<'a> {
430 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
431 let Markdown(md) = *self;
432 // This is actually common enough to special-case
433 if md.len() == 0 { return Ok(()) }
434 render(fmt, md.as_slice(), false)
438 impl<'a> fmt::Display for MarkdownWithToc<'a> {
439 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
440 let MarkdownWithToc(md) = *self;
441 render(fmt, md.as_slice(), true)
447 use super::{LangString, Markdown};
450 fn test_lang_string_parse() {
452 should_fail: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool) {
453 assert_eq!(LangString::parse(s), LangString {
454 should_fail: should_fail,
458 test_harness: test_harness,
462 // marker | should_fail | no_run | ignore | rust | test_harness
463 t("", false, false, false, true, false);
464 t("rust", false, false, false, true, false);
465 t("sh", false, false, false, false, false);
466 t("ignore", false, false, true, true, false);
467 t("should_fail", true, false, false, true, false);
468 t("no_run", false, true, false, true, false);
469 t("test_harness", false, false, false, true, true);
470 t("{.no_run .example}", false, true, false, true, false);
471 t("{.sh .should_fail}", true, false, false, true, false);
472 t("{.example .rust}", false, false, false, true, false);
473 t("{.test_harness .rust}", false, false, false, true, true);
478 let markdown = "# title";
479 format!("{}", Markdown(markdown.as_slice()));