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::Show`. 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::cell::{RefCell, Cell};
36 use std::collections::HashMap;
38 use html::toc::TocBuilder;
40 use html::escape::Escape;
43 /// A unit struct which has the `fmt::Show` trait implemented. When
44 /// formatted, this struct will emit the HTML corresponding to the rendered
45 /// version of the contained markdown string.
46 pub struct Markdown<'a>(pub &'a str);
47 /// A unit struct like `Markdown`, that renders the markdown with a
48 /// table of contents.
49 pub struct MarkdownWithToc<'a>(pub &'a str);
51 static DEF_OUNIT: libc::size_t = 64;
52 static HOEDOWN_EXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 10;
53 static HOEDOWN_EXT_TABLES: libc::c_uint = 1 << 0;
54 static HOEDOWN_EXT_FENCED_CODE: libc::c_uint = 1 << 1;
55 static HOEDOWN_EXT_AUTOLINK: libc::c_uint = 1 << 3;
56 static HOEDOWN_EXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
57 static HOEDOWN_EXT_SUPERSCRIPT: libc::c_uint = 1 << 8;
58 static HOEDOWN_EXT_FOOTNOTES: libc::c_uint = 1 << 2;
60 static HOEDOWN_EXTENSIONS: libc::c_uint =
61 HOEDOWN_EXT_NO_INTRA_EMPHASIS | HOEDOWN_EXT_TABLES |
62 HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_AUTOLINK |
63 HOEDOWN_EXT_STRIKETHROUGH | HOEDOWN_EXT_SUPERSCRIPT |
64 HOEDOWN_EXT_FOOTNOTES;
66 type hoedown_document = libc::c_void; // this is opaque to us
68 struct hoedown_renderer {
69 opaque: *mut hoedown_html_renderer_state,
70 blockcode: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
71 *const hoedown_buffer, *mut libc::c_void)>,
72 blockquote: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
74 blockhtml: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
76 header: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
77 libc::c_int, *mut libc::c_void)>,
78 other: [libc::size_t, ..28],
81 struct hoedown_html_renderer_state {
82 opaque: *mut libc::c_void,
83 toc_data: html_toc_data,
85 link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
86 *const hoedown_buffer,
90 struct html_toc_data {
91 header_count: libc::c_int,
92 current_level: libc::c_int,
93 level_offset: libc::c_int,
94 nesting_level: libc::c_int,
98 dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
99 *const hoedown_buffer, *mut libc::c_void),
100 toc_builder: Option<TocBuilder>,
103 struct hoedown_buffer {
111 #[link(name = "hoedown", kind = "static")]
113 fn hoedown_html_renderer_new(render_flags: libc::c_uint,
114 nesting_level: libc::c_int)
115 -> *mut hoedown_renderer;
116 fn hoedown_html_renderer_free(renderer: *mut hoedown_renderer);
118 fn hoedown_document_new(rndr: *mut hoedown_renderer,
119 extensions: libc::c_uint,
120 max_nesting: libc::size_t) -> *mut hoedown_document;
121 fn hoedown_document_render(doc: *mut hoedown_document,
122 ob: *mut hoedown_buffer,
124 doc_size: libc::size_t);
125 fn hoedown_document_free(md: *mut hoedown_document);
127 fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer;
128 fn hoedown_buffer_puts(b: *mut hoedown_buffer, c: *const libc::c_char);
129 fn hoedown_buffer_free(b: *mut hoedown_buffer);
133 /// Returns Some(code) if `s` is a line that should be stripped from
134 /// documentation but used in example code. `code` is the portion of
135 /// `s` that should be used in tests. (None for lines that should be
137 fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
138 let trimmed = s.trim();
139 if trimmed.starts_with("# ") {
140 Some(trimmed.slice_from(2))
146 local_data_key!(used_header_map: RefCell<HashMap<String, uint>>)
147 local_data_key!(test_idx: Cell<uint>)
148 // None == render an example, but there's no crate name
149 local_data_key!(pub playground_krate: Option<String>)
151 pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
152 extern fn block(ob: *mut hoedown_buffer, text: *const hoedown_buffer,
153 lang: *const hoedown_buffer, opaque: *mut libc::c_void) {
155 if text.is_null() { return }
157 let opaque = opaque as *mut hoedown_html_renderer_state;
158 let my_opaque: &MyOpaque = &*((*opaque).opaque as *const MyOpaque);
159 slice::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
160 let origtext = str::from_utf8(text).unwrap();
161 debug!("docblock: ==============\n{}\n=======", text);
162 let mut lines = origtext.lines().filter(|l| {
163 stripped_filtered_line(*l).is_none()
165 let text = lines.collect::<Vec<&str>>().connect("\n");
167 let buf = hoedown_buffer {
168 data: text.as_bytes().as_ptr(),
169 size: text.len() as libc::size_t,
170 asize: text.len() as libc::size_t,
173 let rendered = if lang.is_null() {
176 slice::raw::buf_as_slice((*lang).data,
177 (*lang).size as uint, |rlang| {
178 let rlang = str::from_utf8(rlang).unwrap();
179 if LangString::parse(rlang).notrust {
180 (my_opaque.dfltblk)(ob, &buf, lang,
181 opaque as *mut libc::c_void);
190 let mut s = String::new();
191 let id = playground_krate.get().map(|krate| {
192 let idx = test_idx.get().unwrap();
196 let test = origtext.lines().map(|l| {
197 stripped_filtered_line(l).unwrap_or(l)
198 }).collect::<Vec<&str>>().connect("\n");
199 let krate = krate.as_ref().map(|s| s.as_slice());
200 let test = test::maketest(test.as_slice(), krate, false, false);
201 s.push_str(format!("<span id='rust-example-raw-{}' \
202 class='rusttest'>{}</span>",
203 i, Escape(test.as_slice())).as_slice());
204 format!("rust-example-rendered-{}", i)
206 let id = id.as_ref().map(|a| a.as_slice());
207 s.push_str(highlight::highlight(text.as_slice(), None, id)
209 let output = s.to_c_str();
210 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 "\n".with_c_str(|p| unsafe { hoedown_buffer_puts(ob, p) });
221 // Extract the text provided
222 let s = if text.is_null() {
226 string::raw::from_buf_len((*text).data, (*text).size as uint)
230 // Transform the contents of the header into a hyphenated string
231 let id = s.as_slice().words().map(|s| {
232 match s.to_ascii_opt() {
233 Some(s) => s.to_lower().into_string(),
234 None => s.to_string()
236 }).collect::<Vec<String>>().connect("-");
238 // This is a terrible hack working around how hoedown gives us rendered
239 // html for text rather than the raw text.
240 let id = id.replace("<code>", "").replace("</code>", "").to_string();
242 let opaque = opaque as *mut hoedown_html_renderer_state;
243 let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
245 // Make sure our hyphenated ID is unique for this page
246 let map = used_header_map.get().unwrap();
247 let id = match map.borrow_mut().find_mut(&id) {
249 Some(a) => { *a += 1; format!("{}-{}", id, *a - 1) }
251 map.borrow_mut().insert(id.clone(), 1);
253 let sec = match opaque.toc_builder {
254 Some(ref mut builder) => {
255 builder.push(level as u32, s.clone(), id.clone())
261 let text = format!(r##"<h{lvl} id="{id}" class='section-header'><a
262 href="#{id}">{sec}{}</a></h{lvl}>"##,
263 s, lvl = level, id = id,
264 sec = if sec.len() == 0 {
270 text.with_c_str(|p| unsafe { hoedown_buffer_puts(ob, p) });
274 let ob = hoedown_buffer_new(DEF_OUNIT);
275 let renderer = hoedown_html_renderer_new(0, 0);
276 let mut opaque = MyOpaque {
277 dfltblk: (*renderer).blockcode.unwrap(),
278 toc_builder: if print_toc {Some(TocBuilder::new())} else {None}
280 (*(*renderer).opaque).opaque = &mut opaque as *mut _ as *mut libc::c_void;
281 (*renderer).blockcode = Some(block);
282 (*renderer).header = Some(header);
284 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
285 hoedown_document_render(document, ob, s.as_ptr(),
286 s.len() as libc::size_t);
287 hoedown_document_free(document);
289 hoedown_html_renderer_free(renderer);
291 let mut ret = match opaque.toc_builder {
292 Some(b) => write!(w, "<nav id=\"TOC\">{}</nav>", b.into_toc()),
297 ret = slice::raw::buf_as_slice((*ob).data, (*ob).size as uint, |buf| {
301 hoedown_buffer_free(ob);
306 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
307 extern fn block(_ob: *mut hoedown_buffer,
308 text: *const hoedown_buffer,
309 lang: *const hoedown_buffer,
310 opaque: *mut libc::c_void) {
312 if text.is_null() { return }
313 let block_info = if lang.is_null() {
314 LangString::all_false()
316 slice::raw::buf_as_slice((*lang).data,
317 (*lang).size as uint, |lang| {
318 let s = str::from_utf8(lang).unwrap();
322 if block_info.notrust { return }
323 slice::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
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 mut 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);
338 extern fn header(_ob: *mut hoedown_buffer,
339 text: *const hoedown_buffer,
340 level: libc::c_int, opaque: *mut libc::c_void) {
342 let opaque = opaque as *mut hoedown_html_renderer_state;
343 let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
345 tests.register_header("", level as u32);
347 slice::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
348 let text = str::from_utf8(text).unwrap();
349 tests.register_header(text, level as u32);
356 let ob = hoedown_buffer_new(DEF_OUNIT);
357 let renderer = hoedown_html_renderer_new(0, 0);
358 (*renderer).blockcode = Some(block);
359 (*renderer).header = Some(header);
360 (*(*renderer).opaque).opaque = tests as *mut _ as *mut libc::c_void;
362 let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
363 hoedown_document_render(document, ob, doc.as_ptr(),
364 doc.len() as libc::size_t);
365 hoedown_document_free(document);
367 hoedown_html_renderer_free(renderer);
368 hoedown_buffer_free(ob);
372 #[deriving(Eq, PartialEq, Clone, Show)]
382 fn all_false() -> LangString {
392 fn parse(string: &str) -> LangString {
393 let mut seen_rust_tags = false;
394 let mut seen_other_tags = false;
395 let mut data = LangString::all_false();
397 let mut tokens = string.as_slice().split(|c: char|
398 !(c == '_' || c == '-' || c.is_alphanumeric())
401 for token in tokens {
404 "should_fail" => { data.should_fail = true; seen_rust_tags = true; },
405 "no_run" => { data.no_run = true; seen_rust_tags = true; },
406 "ignore" => { data.ignore = true; seen_rust_tags = true; },
407 "notrust" => { data.notrust = true; seen_rust_tags = true; },
408 "rust" => { data.notrust = false; seen_rust_tags = true; },
409 "test_harness" => { data.test_harness = true; seen_rust_tags = true; }
410 _ => { seen_other_tags = true }
414 data.notrust |= seen_other_tags && !seen_rust_tags;
420 /// By default this markdown renderer generates anchors for each header in the
421 /// rendered document. The anchor name is the contents of the header separated
422 /// by hyphens, and a task-local map is used to disambiguate among duplicate
423 /// headers (numbers are appended).
425 /// This method will reset the local table for these headers. This is typically
426 /// used at the beginning of rendering an entire HTML page to reset from the
427 /// previous state (if any).
428 pub fn reset_headers() {
429 used_header_map.replace(Some(RefCell::new(HashMap::new())));
430 test_idx.replace(Some(Cell::new(0)));
433 impl<'a> fmt::Show for Markdown<'a> {
434 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
435 let Markdown(md) = *self;
436 // This is actually common enough to special-case
437 if md.len() == 0 { return Ok(()) }
438 render(fmt, md.as_slice(), false)
442 impl<'a> fmt::Show for MarkdownWithToc<'a> {
443 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
444 let MarkdownWithToc(md) = *self;
445 render(fmt, md.as_slice(), true)
451 use super::LangString;
454 fn test_lang_string_parse() {
456 should_fail: bool, no_run: bool, ignore: bool, notrust: bool, test_harness: bool) {
457 assert_eq!(LangString::parse(s), LangString {
458 should_fail: should_fail,
462 test_harness: test_harness,
466 t("", false,false,false,false,false);
467 t("rust", false,false,false,false,false);
468 t("sh", false,false,false,true,false);
469 t("notrust", false,false,false,true,false);
470 t("ignore", false,false,true,false,false);
471 t("should_fail", true,false,false,false,false);
472 t("no_run", false,true,false,false,false);
473 t("test_harness", false,false,false,false,true);
474 t("{.no_run .example}", false,true,false,false,false);
475 t("{.sh .should_fail}", true,false,false,false,false);
476 t("{.example .rust}", false,false,false,false,false);
477 t("{.test_harness .rust}", false,false,false,false,true);