use std::collections::BTreeSet;
use std::fmt;
use std::fs;
use std::io;
#[cfg(unix)]
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
#[cfg(unix)]
use std::fs::OpenOptions;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use pulldown_cmark::Options;
use url::Url;
use crate::highlight;
use crate::page::{source_modified_unix_secs, wrap_html5};
fn dir_to_file_url(dir: &Path) -> Option<String> {
Url::from_directory_path(dir)
.ok()
.map(|url| url.to_string())
}
fn markdown_options() -> Options {
let mut options = Options::empty();
options.insert(Options::ENABLE_STRIKETHROUGH);
options.insert(Options::ENABLE_TABLES);
options.insert(Options::ENABLE_FOOTNOTES);
options.insert(Options::ENABLE_TASKLISTS);
options.insert(Options::ENABLE_GFM);
options
}
fn markdown_to_html(
markdown: &str,
placeholder_discriminator: u64,
plain_fences: &BTreeSet<usize>,
) -> highlight::RenderedMarkdown {
let markdown = yaml_front_matter(markdown)
.map(|(_, body)| body)
.unwrap_or(markdown);
highlight::render(
markdown,
markdown_options(),
placeholder_discriminator,
plain_fences,
)
}
const MAX_PLACEHOLDER_RETRIES: u32 = 16;
fn spliced_markdown_body(
markdown: &str,
mut render: impl FnMut(&str, u64, &BTreeSet<usize>) -> highlight::RenderedMarkdown,
mut process: impl FnMut(&str) -> String,
) -> (String, Option<&'static str>) {
let mut discriminator = 0_u64;
let mut collision_retries = 0_u32;
let mut plain_fences = BTreeSet::new();
loop {
let rendered = render(markdown, discriminator, &plain_fences);
match rendered.finish(rendered.raw_html().to_string()) {
Ok(body) => return (process(&body), rendered.css()),
Err(highlight::SpliceError::Destroyed(fences)) => {
plain_fences.extend(fences);
}
Err(highlight::SpliceError::Collision) => {
collision_retries += 1;
if collision_retries > MAX_PLACEHOLDER_RETRIES {
plain_fences.extend(0..rendered.fence_count());
}
discriminator += 1;
}
}
}
}
fn safe_markdown_body(markdown: &str) -> (String, Option<&'static str>) {
spliced_markdown_body(markdown, markdown_to_html, sanitize_html)
}
fn sanitize_html(html: &str) -> String {
ammonia::Builder::default()
.add_generic_attributes(&["class", "id"])
.add_tags(&["input"])
.add_tag_attributes("input", &["checked", "type"])
.add_tag_attribute_values("input", "checked", &[""])
.add_tag_attribute_values("input", "type", &["checkbox"])
.set_tag_attribute_value("input", "disabled", "")
.clean(html)
.to_string()
}
pub fn render_markdown_document(
markdown: &str,
fallback_title: &str,
source_modified_unix_secs: Option<u64>,
) -> String {
let (body, highlight_css) = safe_markdown_body(markdown);
let title = derive_title(markdown, fallback_title);
wrap_html5(
&body,
&title,
None,
None,
highlight_css,
source_modified_unix_secs,
)
}
fn derive_title(markdown: &str, fallback: &str) -> String {
if let Some(title) = front_matter_title(markdown) {
return title;
}
let markdown = yaml_front_matter(markdown)
.map(|(_, document)| document)
.unwrap_or(markdown);
let without_fences = strip_code_fences(markdown);
for line in without_fences.lines() {
let trimmed = line.trim_start();
if let Some(rest) = trimmed.trim_end().strip_prefix("# ") {
return rest.trim().to_string();
}
}
if let Some(title) = derive_raw_html_h1_title(&without_fences) {
return title;
}
fallback.to_string()
}
fn front_matter_title(markdown: &str) -> Option<String> {
let (metadata, _) = yaml_front_matter(markdown)?;
let mut title = None;
for line in metadata.lines() {
if line.starts_with(char::is_whitespace) {
continue;
}
if let Some((key, value)) = line.split_once(':') {
if key == "title" {
let value = unquote_front_matter_scalar(value.trim());
if !value.is_empty() {
title = Some(value.to_string());
}
}
}
}
title
}
fn yaml_front_matter(markdown: &str) -> Option<(&str, &str)> {
fn delimiter(line: &str) -> Option<&str> {
let line = line.trim_end_matches(['\r', '\n']).trim_end_matches(' ');
(line == "---" || line == "...").then_some(line)
}
let first_line_end = markdown.find('\n').unwrap_or(markdown.len());
if delimiter(&markdown[..first_line_end]) != Some("---") || first_line_end == markdown.len() {
return None;
}
let metadata_start = first_line_end + 1;
let remainder = &markdown[metadata_start..];
let mut consumed = 0;
for segment in remainder.split_inclusive('\n') {
if delimiter(segment).is_some() {
let metadata = &remainder[..consumed];
let first_content_line = metadata.lines().next()?;
if first_content_line.trim().is_empty() {
return None;
}
return Some((metadata, &remainder[consumed + segment.len()..]));
}
consumed += segment.len();
}
None
}
fn unquote_front_matter_scalar(value: &str) -> &str {
if value.len() < 2 {
return value;
}
let bytes = value.as_bytes();
if matches!(
(bytes[0], bytes[value.len() - 1]),
(b'\'', b'\'') | (b'"', b'"')
) {
&value[1..value.len() - 1]
} else {
value
}
}
fn strip_code_fences(markdown: &str) -> String {
let mut out = String::with_capacity(markdown.len());
let mut fence: Option<char> = None;
for line in markdown.lines() {
if let Some(marker) = code_fence_marker(line.trim_start()) {
match fence {
Some(open) if open == marker => fence = None,
Some(_) => {}
None => fence = Some(marker),
}
continue;
}
if fence.is_some() {
continue;
}
out.push_str(line);
out.push('\n');
}
out
}
fn code_fence_marker(trimmed_start: &str) -> Option<char> {
if trimmed_start.starts_with("```") {
Some('`')
} else if trimmed_start.starts_with("~~~") {
Some('~')
} else {
None
}
}
fn derive_raw_html_h1_title(markdown: &str) -> Option<String> {
let lower = markdown.to_ascii_lowercase();
let mut search_start = 0;
while let Some(offset) = lower[search_start..].find("<h1") {
let start = search_start + offset;
let after_tag_name = start + 3;
let next = lower.as_bytes().get(after_tag_name).copied();
if !matches!(
next,
Some(b'>') | Some(b' ') | Some(b'\t') | Some(b'\r') | Some(b'\n')
) {
search_start = after_tag_name;
continue;
}
let content_start = start + markdown[start..].find('>')? + 1;
let content_end = content_start + lower[content_start..].find("</h1>")?;
let title = strip_html_tags(&markdown[content_start..content_end])
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
if !title.is_empty() {
return Some(title);
}
search_start = content_end + 5;
}
None
}
fn strip_html_tags(input: &str) -> String {
let mut output = String::with_capacity(input.len());
let mut in_tag = false;
for ch in input.chars() {
match ch {
'<' => in_tag = true,
'>' if in_tag => in_tag = false,
_ if !in_tag => output.push(ch),
_ => {}
}
}
output
}
#[derive(Debug, Default)]
pub struct StageTimings {
pub read: Duration,
pub markdown: Duration,
pub sanitize: Duration,
pub assemble: Duration,
pub write: Duration,
pub total: Duration,
}
#[derive(Debug)]
pub struct ConvertRequest<'a> {
pub input: &'a Path,
pub output: &'a Path,
pub bare: bool,
pub unsafe_html: bool,
pub private_output: bool,
pub css_override: Option<&'a Path>,
}
#[derive(Debug)]
pub struct ConvertOutcome {
pub output: PathBuf,
pub timings: StageTimings,
}
#[derive(Debug)]
pub enum RenderError {
Read { path: PathBuf, source: io::Error },
ReadCssOverride { path: PathBuf, source: io::Error },
CreateOutputDir { path: PathBuf, source: io::Error },
Write { path: PathBuf, source: io::Error },
}
impl fmt::Display for RenderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (action, path, source) = match self {
RenderError::Read { path, source } => ("failed to read", path, source),
RenderError::ReadCssOverride { path, source } => {
("failed to read CSS override", path, source)
}
RenderError::CreateOutputDir { path, source } => ("failed to create", path, source),
RenderError::Write { path, source } => ("failed to write", path, source),
};
write!(f, "{} {}: {}", action, path.display(), source)
}
}
impl std::error::Error for RenderError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(match self {
RenderError::Read { source, .. }
| RenderError::ReadCssOverride { source, .. }
| RenderError::CreateOutputDir { source, .. }
| RenderError::Write { source, .. } => source,
})
}
}
pub fn convert(request: ConvertRequest) -> Result<ConvertOutcome, RenderError> {
let workflow_start = Instant::now();
let mut timings = StageTimings::default();
let stage_start = Instant::now();
let markdown = fs::read_to_string(request.input).map_err(|source| RenderError::Read {
path: request.input.to_path_buf(),
source,
})?;
timings.read = stage_start.elapsed();
let css_override = if request.bare {
None
} else {
match request.css_override {
Some(path) => {
let stage_start = Instant::now();
let css =
fs::read_to_string(path).map_err(|source| RenderError::ReadCssOverride {
path: path.to_path_buf(),
source,
})?;
timings.read += stage_start.elapsed();
Some(css)
}
None => None,
}
};
let (body, highlight_css) = spliced_markdown_body(
&markdown,
|markdown, discriminator, plain_fences| {
let stage_start = Instant::now();
let rendered = markdown_to_html(markdown, discriminator, plain_fences);
timings.markdown += stage_start.elapsed();
rendered
},
|html| {
if request.unsafe_html {
html.to_string()
} else {
let sanitize_start = Instant::now();
let sanitized = sanitize_html(html);
timings.sanitize += sanitize_start.elapsed();
sanitized
}
},
);
let final_html = if request.bare {
body
} else {
let stage_start = Instant::now();
let fallback = request
.input
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("Document");
let title = derive_title(&markdown, fallback);
let base_href = match (
fs::canonicalize(request.input)
.ok()
.and_then(|p| p.parent().map(Path::to_path_buf)),
request
.output
.parent()
.and_then(|p| fs::canonicalize(p).ok()),
) {
(Some(in_dir), Some(out_dir)) if in_dir != out_dir => dir_to_file_url(&in_dir),
_ => None,
};
let wrapped = wrap_html5(
&body,
&title,
base_href.as_deref(),
css_override.as_deref(),
highlight_css,
source_modified_unix_secs(request.input),
);
timings.assemble = stage_start.elapsed();
wrapped
};
let stage_start = Instant::now();
if let Some(parent) = request.output.parent() {
if !parent.as_os_str().is_empty() {
fs::create_dir_all(parent).map_err(|source| RenderError::CreateOutputDir {
path: parent.to_path_buf(),
source,
})?;
}
}
write_output_file(request.output, &final_html, request.private_output).map_err(|source| {
RenderError::Write {
path: request.output.to_path_buf(),
source,
}
})?;
timings.write = stage_start.elapsed();
timings.total = workflow_start.elapsed();
Ok(ConvertOutcome {
output: request.output.to_path_buf(),
timings,
})
}
#[cfg(unix)]
fn write_output_file(output: &Path, contents: &str, private_output: bool) -> io::Result<()> {
let mut options = OpenOptions::new();
options
.write(true)
.create(true)
.truncate(true)
.custom_flags(libc::O_NOFOLLOW);
if private_output {
options.mode(0o600);
}
let mut file = options.open(output)?;
file.write_all(contents.as_bytes())
}
#[cfg(not(unix))]
fn write_output_file(output: &Path, contents: &str, _private_output: bool) -> io::Result<()> {
fs::write(output, contents)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
fn rendered_markdown_html(markdown: &str) -> String {
let rendered = markdown_to_html(markdown, 0, &BTreeSet::new());
rendered
.finish(rendered.raw_html().to_string())
.expect("unsanitized renderer should preserve its unique placeholders")
}
#[test]
fn in_memory_render_uses_shared_safe_document_pipeline() {
let html = render_markdown_document(
"# Phone note\n\nHello **Android**.\n\n<script>alert('no')</script>",
"fallback.md",
None,
);
assert!(html.contains("<title>Phone note</title>"));
assert!(html.contains("<strong>Android</strong>"));
assert!(html.contains("<meta name=\"generator\" content=\"mdo "));
assert!(!html.contains("<script>alert('no')</script>"));
}
#[test]
fn markdown_extensions_keep_their_existing_html() {
let markdown = "~~gone~~\n\n\
| A | B |\n\
| - | - |\n\
| 1 | 2 |\n\n\
Footnote[^one].\n\n\
[^one]: Detail\n\n\
- [x] done\n\
- [ ] later\n";
let expected = "<p><del>gone</del></p>\n\
<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody>\n\
<tr><td>1</td><td>2</td></tr>\n\
</tbody></table>\n\
<p>Footnote<sup class=\"footnote-reference\"><a href=\"#one\">1</a></sup>.</p>\n\
<div class=\"footnote-definition\" id=\"one\"><sup class=\"footnote-definition-label\">1</sup>\n\
<p>Detail</p>\n\
</div>\n\
<ul>\n\
<li><input disabled=\"\" type=\"checkbox\" checked=\"\"/>\n\
done</li>\n\
<li><input disabled=\"\" type=\"checkbox\"/>\n\
later</li>\n\
</ul>\n";
assert_eq!(rendered_markdown_html(markdown), expected);
}
#[test]
fn gfm_alerts_render_all_supported_classes_and_survive_sanitizing() {
for kind in ["note", "tip", "important", "warning", "caution"] {
let markdown = format!("> [!{}]\n> Alert text\n", kind.to_uppercase());
let raw = rendered_markdown_html(&markdown);
let class = format!("class=\"markdown-alert-{kind}\"");
assert!(raw.contains(&class), "{raw}");
assert!(!raw.contains("[!"), "{raw}");
assert!(sanitize_html(&raw).contains(&class), "{raw}");
}
}
#[test]
fn yaml_front_matter_is_hidden_and_supplies_document_title() {
let markdown =
"---\ntitle: 'Front Matter Title'\nauthor: Example\n...\n\n# Heading Title\n";
let body = rendered_markdown_html(markdown);
assert_eq!(body, "<h1>Heading Title</h1>\n");
assert_eq!(derive_title(markdown, "fallback"), "Front Matter Title");
let document = render_markdown_document(markdown, "fallback", None);
assert!(document.contains("<title>Front Matter Title</title>"));
assert!(!document.contains("author: Example"));
}
#[test]
fn mid_document_metadata_style_blocks_are_rendered_not_swallowed() {
let markdown = "# Top\n\nintro\n\n---\nnot a heading\n---\n\ntail\n";
let html = rendered_markdown_html(markdown);
assert!(html.contains("not a heading"), "{html}");
assert!(html.contains("tail"), "{html}");
assert_eq!(derive_title(markdown, "fallback"), "Top");
}
#[test]
fn blank_first_line_block_is_not_front_matter() {
let markdown = "---\n\ntitle: fake\n---\n\n# Real Heading\n";
let html = rendered_markdown_html(markdown);
assert!(html.contains("title: fake"), "{html}");
assert_eq!(derive_title(markdown, "fallback"), "Real Heading");
assert!(yaml_front_matter("---\n---\n# Heading\n").is_none());
}
#[test]
fn front_matter_title_supports_colons_and_double_quotes() {
let markdown = "---\ntitle: \"Project: Alpha\"\n---\n\n# Heading\n";
assert_eq!(derive_title(markdown, "fallback"), "Project: Alpha");
}
#[test]
fn missing_empty_or_unclosed_front_matter_title_uses_existing_fallbacks() {
assert_eq!(
derive_title("---\nauthor: Example\n---\n\n# Heading\n", "fallback"),
"Heading"
);
assert_eq!(
derive_title("---\ntitle: \n---\n", "Fallback Title"),
"Fallback Title"
);
assert_eq!(
derive_title("---\ntitle: Incomplete\n# Real Heading\n", "fallback"),
"Real Heading"
);
assert_eq!(
derive_title(
"---\ndescription: |\n# Metadata, not a heading\n---\n\n# Real Heading\n",
"fallback"
),
"Real Heading"
);
}
#[test]
fn smart_punctuation_is_not_enabled() {
let html = rendered_markdown_html("-- --- ... \"straight\" 'quotes'\n");
assert_eq!(html, "<p>-- --- ... \"straight\" 'quotes'</p>\n");
assert!(!html.contains(['–', '—', '…', '“', '”', '‘', '’']));
}
#[test]
fn recognized_fences_are_highlighted_with_both_theme_palettes() {
let markdown = "```rust\nfn main() { let html = \"<script>x</script>\"; }\n```\n";
let html = render_markdown_document(markdown, "fallback", None);
assert!(html.contains(
"<pre class=\"mdo-highlight mdo-syntect-code\"><code class=\"language-rust\">"
));
assert!(html.contains("mdo-syntect-keyword"), "{html}");
assert!(html.contains(":root[data-theme=\"light\"] .mdo-syntect-code"));
assert!(html.contains(":root[data-theme=\"dark\"] .mdo-syntect-code"));
assert!(!html.contains("<script>x</script>"));
assert!(html.contains("<script>"));
}
#[test]
fn unknown_fences_remain_plain_and_do_not_add_theme_css() {
let markdown = "```not-a-real-language\n<unsafe> & plain\n```\n";
let html = render_markdown_document(markdown, "fallback", None);
assert!(html.contains(
"<pre><code class=\"language-not-a-real-language\"><unsafe> & plain\n</code></pre>"
));
assert!(!html.contains("mdo-highlight"));
assert!(!html.contains("Syntax highlighting generated by syntect"));
}
#[test]
fn pages_without_code_do_not_add_highlight_css() {
let html = render_markdown_document("# Just prose\n", "fallback", None);
assert!(!html.contains("Syntax highlighting generated by syntect"));
assert!(!html.contains("mdo-syntect-"));
let unlabeled = render_markdown_document("```\nplain code\n```\n", "fallback", None);
assert!(unlabeled.contains("<pre><code>plain code\n</code></pre>"));
assert!(!unlabeled.contains("Syntax highlighting generated by syntect"));
}
#[test]
fn literal_placeholder_spoof_does_not_capture_generated_markup() {
let spoof = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
let markdown = format!("`{spoof}`\n\n```rust\nlet answer = 42;\n```\n");
let html = render_markdown_document(&markdown, "fallback", None);
assert!(html.contains(spoof));
assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
}
#[test]
fn entity_normalized_placeholder_spoof_cannot_capture_generated_markup() {
let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
let encoded = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
let markdown = format!("{encoded}\n\n```rust\nlet answer = 42;\n```\n");
let html = render_markdown_document(&markdown, "fallback", None);
assert!(html.contains(normalized), "{html}");
assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
}
#[test]
fn attribute_normalized_placeholder_cannot_receive_generated_markup() {
let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
let encoded = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
let markdown = format!(
"<span title=\"{encoded}\">probe</span>\n\n```rust\nlet one = 1;\n```\n\n```python\nprint(2)\n```\n"
);
let html = render_markdown_document(&markdown, "fallback", None);
assert!(html.contains(&format!("title=\"{normalized}\"")), "{html}");
assert!(!html.contains("title=\"<pre"), "{html}");
assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 2);
assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_1__"));
}
#[test]
fn normalized_spoof_cannot_mask_a_sanitizer_destroyed_placeholder() {
let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
let encoded = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
let markdown = format!(
"<span title=\"{encoded}\">probe</span>\n\n<style>\n\n```rust\nfn main() {{}}\n```\n"
);
let html = render_markdown_document(&markdown, "fallback", None);
assert!(html.contains(&format!("title=\"{normalized}\"")), "{html}");
assert!(!html.contains("title=\"<pre"), "{html}");
assert!(!html.contains("<pre class=\"mdo-highlight "), "{html}");
assert!(!html.contains("<code class=\"language-rust\""), "{html}");
}
#[test]
fn unclosed_style_before_fence_terminates_without_post_sanitize_splice() {
let markdown = "before <style> after\n\n```rust\nfn main() {}\n```\n";
let html = render_markdown_document(markdown, "fallback", None);
assert!(html.contains("before"));
assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
assert!(!html.contains("mdo-highlight"));
}
#[test]
fn unclosed_script_before_fence_terminates_without_post_sanitize_splice() {
let markdown = "before <script> after\n\n```rust\nfn main() {}\n```\n";
let html = render_markdown_document(markdown, "fallback", None);
assert!(html.contains("before"));
assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
assert!(!html.contains("mdo-highlight"));
}
#[test]
fn sanitizer_drops_only_highlight_markup_after_unclosed_style() {
let markdown =
"```rust\nlet first = 1;\n```\n\ntext <style> text\n\n```rust\nlet second = 2;\n```\n";
let html = render_markdown_document(markdown, "fallback", None);
assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
assert!(html.contains("let"), "{html}");
assert!(html.contains("first"), "{html}");
assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
}
#[test]
fn multiple_highlighted_blocks_splice_once_each() {
let markdown = "```rust\nlet one = 1;\n```\n\n```python\nprint(2)\n```\n";
let html = render_markdown_document(markdown, "fallback", None);
assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 2);
assert!(html.contains("language-rust"));
assert!(html.contains("language-python"));
assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
}
#[test]
fn raw_user_html_still_crosses_the_ammonia_boundary() {
let markdown = "<div onclick=\"alert(1)\"><script>bad()</script><span class=\"mdo-syntect-keyword\">user</span></div>\n\n```rust\nlet safe = \"<b>code</b>\";\n```\n";
let html = render_markdown_document(markdown, "fallback", None);
assert!(!html.contains("onclick=\"alert(1)\""));
assert!(!html.contains("<script>bad()</script>"));
assert!(html.contains(">user</span>"));
assert!(!html.contains("<b>code</b>"));
assert!(html.contains("<b>"));
}
#[test]
fn title_can_come_from_raw_html_h1() {
let title = derive_title(
r#"<section><h1 class="hero-title">Project <span>Home</span></h1></section>"#,
"fallback",
);
assert_eq!(title, "Project Home");
}
#[test]
fn derive_title_ignores_headings_in_code_fences() {
let markdown = "```sh\n# not a title\n```\n\n# Real Title\n";
assert_eq!(derive_title(markdown, "fallback"), "Real Title");
}
#[test]
fn derive_title_falls_back_when_only_heading_is_fenced() {
let markdown = "~~~\n# fenced heading\n~~~\n";
assert_eq!(derive_title(markdown, "Fallback Title"), "Fallback Title");
}
#[test]
fn derive_title_ignores_raw_html_h1_inside_code_fence() {
let markdown = "```html\n<h1>Not the title</h1>\n```\n\n# Real Title\n";
assert_eq!(derive_title(markdown, "fallback"), "Real Title");
}
#[cfg(unix)]
#[test]
fn dir_to_file_url_adds_trailing_slash() {
let url =
dir_to_file_url(Path::new("/home/user/docs")).expect("absolute path should convert");
assert!(url.ends_with('/'));
assert_eq!(url, "file:///home/user/docs/");
}
#[cfg(unix)]
#[test]
fn dir_to_file_url_encodes_spaces() {
let url = dir_to_file_url(Path::new("/home/user/my docs")).expect("should convert");
assert_eq!(url, "file:///home/user/my%20docs/");
}
#[cfg(unix)]
#[test]
fn dir_to_file_url_encodes_hash() {
let url = dir_to_file_url(Path::new("/home/user/docs#1")).expect("should convert");
assert_eq!(url, "file:///home/user/docs%231/");
}
#[cfg(unix)]
#[test]
fn dir_to_file_url_encodes_percent() {
let url = dir_to_file_url(Path::new("/home/user/50%done")).expect("should convert");
assert_eq!(url, "file:///home/user/50%25done/");
}
#[cfg(unix)]
#[test]
fn dir_to_file_url_encodes_question_mark() {
let url = dir_to_file_url(Path::new("/home/user/docs?draft")).expect("should convert");
assert_eq!(url, "file:///home/user/docs%3Fdraft/");
}
#[cfg(unix)]
#[test]
fn dir_to_file_url_encodes_unicode_accented() {
let url = dir_to_file_url(Path::new("/home/user/résumé")).expect("should convert");
assert_eq!(url, "file:///home/user/r%C3%A9sum%C3%A9/");
}
#[cfg(unix)]
#[test]
fn dir_to_file_url_encodes_unicode_cjk() {
let url = dir_to_file_url(Path::new("/home/user/日本語")).expect("should convert");
assert_eq!(url, "file:///home/user/%E6%97%A5%E6%9C%AC%E8%AA%9E/");
}
#[test]
fn dir_to_file_url_returns_none_for_relative_path() {
assert_eq!(dir_to_file_url(Path::new("relative/dir")), None);
}
#[cfg(windows)]
#[test]
fn dir_to_file_url_windows_drive_letter() {
let url = dir_to_file_url(Path::new(r"C:\foo\bar")).expect("should convert");
assert_eq!(url, "file:///C:/foo/bar/");
}
#[cfg(windows)]
#[test]
fn dir_to_file_url_windows_drive_letter_with_space() {
let url = dir_to_file_url(Path::new(r"C:\Program Files\mdo")).expect("should convert");
assert_eq!(url, "file:///C:/Program%20Files/mdo/");
}
#[cfg(windows)]
#[test]
fn dir_to_file_url_windows_extended_length_prefix() {
let url = dir_to_file_url(Path::new(r"\\?\C:\foo\bar")).expect("should convert");
assert_eq!(url, "file:///C:/foo/bar/");
}
#[cfg(windows)]
#[test]
fn dir_to_file_url_windows_unc_path() {
let url = dir_to_file_url(Path::new(r"\\server\share\dir")).expect("should convert");
assert_eq!(url, "file://server/share/dir/");
}
}