]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
Various minor/cosmetic improvements to code
[rust.git] / src / librustdoc / markdown.rs
1 // Copyright 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.
4 //
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.
10
11 use std::default::Default;
12 use std::fs::File;
13 use std::io::prelude::*;
14 use std::path::PathBuf;
15 use std::cell::RefCell;
16
17 use errors;
18 use testing;
19 use syntax::source_map::DUMMY_SP;
20 use syntax::feature_gate::UnstableFeatures;
21
22 use externalfiles::{LoadStringError, load_string};
23
24 use config::{Options, RenderOptions};
25 use html::escape::Escape;
26 use html::markdown;
27 use html::markdown::{ErrorCodes, IdMap, Markdown, MarkdownWithToc, find_testable_code};
28 use test::{TestOptions, Collector};
29
30 /// Separate any lines at the start of the file that begin with `# ` or `%`.
31 fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) {
32     let mut metadata = Vec::new();
33     let mut count = 0;
34
35     for line in s.lines() {
36         if line.starts_with("# ") || line.starts_with("%") {
37             // trim the whitespace after the symbol
38             metadata.push(line[1..].trim_left());
39             count += line.len() + 1;
40         } else {
41             return (metadata, &s[count..]);
42         }
43     }
44
45     // if we're here, then all lines were metadata `# ` or `%` lines.
46     (metadata, "")
47 }
48
49 /// Render `input` (e.g., "foo.md") into an HTML file in `output`
50 /// (e.g., output = "bar" => "bar/foo.html").
51 pub fn render(input: PathBuf, options: RenderOptions, diag: &errors::Handler) -> isize {
52     let mut output = options.output;
53     output.push(input.file_stem().unwrap());
54     output.set_extension("html");
55
56     let mut css = String::new();
57     for name in &options.markdown_css {
58         let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
59         css.push_str(&s)
60     }
61
62     let input_str = match load_string(&input, diag) {
63         Ok(s) => s,
64         Err(LoadStringError::ReadFail) => return 1,
65         Err(LoadStringError::BadUtf8) => return 2,
66     };
67     let playground_url = options.markdown_playground_url
68                             .or(options.playground_url);
69     if let Some(playground) = playground_url {
70         markdown::PLAYGROUND.with(|s| { *s.borrow_mut() = Some((None, playground)); });
71     }
72
73     let mut out = match File::create(&output) {
74         Err(e) => {
75             diag.struct_err(&format!("{}: {}", output.display(), e)).emit();
76             return 4;
77         }
78         Ok(f) => f,
79     };
80
81     let (metadata, text) = extract_leading_metadata(&input_str);
82     if metadata.is_empty() {
83         diag.struct_err("invalid markdown file: no initial lines starting with `# ` or `%`").emit();
84         return 5;
85     }
86     let title = metadata[0];
87
88     let mut ids = IdMap::new();
89     let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
90     let text = if !options.markdown_no_toc {
91         MarkdownWithToc(text, RefCell::new(&mut ids), error_codes).to_string()
92     } else {
93         Markdown(text, &[], RefCell::new(&mut ids), error_codes).to_string()
94     };
95
96     let err = write!(
97         &mut out,
98         r#"<!DOCTYPE html>
99 <html lang="en">
100 <head>
101     <meta charset="utf-8">
102     <meta name="viewport" content="width=device-width, initial-scale=1.0">
103     <meta name="generator" content="rustdoc">
104     <title>{title}</title>
105
106     {css}
107     {in_header}
108 </head>
109 <body class="rustdoc">
110     <!--[if lte IE 8]>
111     <div class="warning">
112         This old browser is unsupported and will most likely display funky
113         things.
114     </div>
115     <![endif]-->
116
117     {before_content}
118     <h1 class="title">{title}</h1>
119     {text}
120     {after_content}
121 </body>
122 </html>"#,
123         title = Escape(title),
124         css = css,
125         in_header = options.external_html.in_header,
126         before_content = options.external_html.before_content,
127         text = text,
128         after_content = options.external_html.after_content,
129     );
130
131     match err {
132         Err(e) => {
133             diag.struct_err(&format!("cannot write to `{}`: {}", output.display(), e)).emit();
134             6
135         }
136         Ok(_) => 0,
137     }
138 }
139
140 /// Run any tests/code examples in the markdown file `input`.
141 pub fn test(mut options: Options, diag: &errors::Handler) -> isize {
142     let input_str = match load_string(&options.input, diag) {
143         Ok(s) => s,
144         Err(LoadStringError::ReadFail) => return 1,
145         Err(LoadStringError::BadUtf8) => return 2,
146     };
147
148     let mut opts = TestOptions::default();
149     opts.no_crate_inject = true;
150     opts.display_warnings = options.display_warnings;
151     let mut collector = Collector::new(options.input.display().to_string(), options.cfgs,
152                                        options.libs, options.codegen_options, options.externs,
153                                        true, opts, options.maybe_sysroot, None,
154                                        Some(options.input),
155                                        options.linker, options.edition);
156     collector.set_position(DUMMY_SP);
157     let codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
158     let res = find_testable_code(&input_str, &mut collector, codes);
159     if let Err(err) = res {
160         diag.span_warn(DUMMY_SP, &err.to_string());
161     }
162     options.test_args.insert(0, "rustdoctest".to_string());
163     testing::test_main(&options.test_args, collector.tests,
164                        testing::Options::new().display_output(options.display_warnings));
165     0
166 }