Skip to main content

rustdoc/
markdown.rs

1//! Standalone markdown rendering.
2//!
3//! For the (much more common) case of rendering markdown in doc-comments, see
4//! [crate::html::markdown].
5//!
6//! This is used when [rendering a markdown file to an html file][docs], without processing
7//! rust source code.
8//!
9//! [docs]: https://doc.rust-lang.org/stable/rustdoc/#using-standalone-markdown-files
10
11use std::fmt::{self, Write as _};
12use std::fs::{File, create_dir_all};
13use std::io::prelude::*;
14use std::path::PathBuf;
15use std::sync::Arc;
16
17use rustc_span::SourceFile;
18use rustc_span::edition::Edition;
19
20use crate::config::RenderOptions;
21use crate::html::escape::Escape;
22use crate::html::markdown;
23use crate::html::markdown::{ErrorCodes, HeadingOffset, IdMap, Markdown, MarkdownWithToc};
24
25/// Separate any lines at the start of the file that begin with `# ` or `%`.
26fn extract_leading_metadata(s: &str) -> (Vec<&str>, &str) {
27    let mut metadata = Vec::new();
28    let mut count = 0;
29
30    for line in s.lines() {
31        if line.starts_with("# ") || line.starts_with('%') {
32            // trim the whitespace after the symbol
33            metadata.push(line[1..].trim_start());
34            count += line.len() + 1;
35        } else {
36            return (metadata, &s[count..]);
37        }
38    }
39
40    // if we're here, then all lines were metadata `# ` or `%` lines.
41    (metadata, "")
42}
43
44/// Render `input` (e.g., "foo.md") into an HTML file in `output`
45/// (e.g., output = "bar" => "bar/foo.html").
46///
47/// Requires session globals to be available, for symbol interning.
48pub(crate) fn render_and_write(
49    input: Arc<SourceFile>,
50    options: RenderOptions,
51    edition: Edition,
52) -> Result<(), String> {
53    if let Err(e) = create_dir_all(&options.output) {
54        return Err(format!("{output}: {e}", output = options.output.display()));
55    }
56
57    let input_path = input.name.clone().into_local_path().unwrap_or(PathBuf::new());
58    let mut output = options.output;
59    output.push(input_path.file_name().unwrap());
60    output.set_extension("html");
61
62    let mut css = String::new();
63    for name in &options.markdown_css {
64        write!(css, r#"<link rel="stylesheet" href="{name}">"#)
65            .expect("Writing to a String can't fail");
66    }
67
68    let input_str = input.src.as_ref().map(|src| &src[..]).unwrap_or("");
69    let playground_url = options.markdown_playground_url.or(options.playground_url);
70    let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url });
71
72    let (metadata, text) = extract_leading_metadata(&input_str);
73    if metadata.is_empty() {
74        return Err("invalid markdown file: no initial lines starting with `# ` or `%`".to_owned());
75    }
76
77    let mut out =
78        File::create(&output).map_err(|e| format!("{output}: {e}", output = output.display()))?;
79
80    let title = metadata[0];
81
82    let error_codes = ErrorCodes::from(options.unstable_features.is_nightly_build());
83    let text = fmt::from_fn(|f| {
84        if !options.markdown_no_toc {
85            MarkdownWithToc {
86                content: text,
87                links: &[],
88                ids: &mut IdMap::new(),
89                error_codes,
90                edition,
91                playground: &playground,
92            }
93            .write_into(f)
94        } else {
95            Markdown {
96                content: text,
97                links: &[],
98                ids: &mut IdMap::new(),
99                error_codes,
100                edition,
101                playground: &playground,
102                heading_offset: HeadingOffset::H1,
103            }
104            .write_into(f)
105        }
106    });
107
108    let res = write!(
109        &mut out,
110        r#"<!DOCTYPE html>
111<html lang="en">
112<head>
113    <meta charset="utf-8">
114    <meta name="viewport" content="width=device-width, initial-scale=1.0">
115    <meta name="generator" content="rustdoc">
116    <title>{title}</title>
117
118    {css}
119    {in_header}
120</head>
121<body class="rustdoc">
122    <!--[if lte IE 8]>
123    <div class="warning">
124        This old browser is unsupported and will most likely display funky
125        things.
126    </div>
127    <![endif]-->
128
129    {before_content}
130    <h1 class="title">{title}</h1>
131    {text}
132    {after_content}
133</body>
134</html>"#,
135        title = Escape(title),
136        in_header = options.external_html.in_header,
137        before_content = options.external_html.before_content,
138        after_content = options.external_html.after_content,
139    );
140
141    res.map_err(|e| format!("cannot write to `{output}`: {e}", output = output.display()))
142}