fix: strip windows verbatim prefix and build valid file base url

This commit is contained in:
2026-10-21 16:13:28 +08:00
parent f63aff47a8
commit 0ca339dcf7
2 changed files with 62 additions and 33 deletions

View File

@@ -776,8 +776,11 @@ fn load_recent_files() -> Vec<PathBuf> {
};
let mut files = Vec::new();
for line in txt.lines() {
let path = PathBuf::from(line);
if line.is_empty() || !path.exists() || files.iter().any(|p| p == &path) {
if line.is_empty() {
continue;
}
let path = session::strip_verbatim(PathBuf::from(line));
if !path.exists() || files.iter().any(|p| p == &path) {
continue;
}
files.push(path);
@@ -819,33 +822,11 @@ fn forget_recent_file(files: &Arc<Mutex<Vec<PathBuf>>>, path: &Path) -> bool {
true
}
fn percent_encode_file_path(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for &b in s.as_bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b':' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
fn base_href_for_file(path: &Path) -> Option<String> {
let dir = path.parent()?;
Some(file_url_for_path_dir(dir))
}
fn file_url_for_path_dir(dir: &Path) -> String {
let mut path = dir.to_string_lossy().replace('\\', "/");
if cfg!(windows) && !path.starts_with('/') {
path.insert(0, '/');
}
if !path.ends_with('/') {
path.push('/');
}
format!("file://{}", percent_encode_file_path(&path))
url::Url::from_directory_path(dir)
.ok()
.map(|url| url.to_string())
}
fn starts_mermaid_fence(line: &str) -> bool {
@@ -2114,6 +2095,20 @@ mod tests {
assert!(!html.contains("mdp-mark"), "code blocks must not get highlight markup");
}
#[test]
fn base_href_is_a_directory_file_url() {
let dir = temp_test_dir("base-href");
let file = dir.join("note.md");
fs::write(&file, "# x").unwrap();
let href = base_href_for_file(&file).unwrap();
assert!(href.starts_with("file:///"), "{href}");
assert!(href.ends_with('/'), "{href}");
assert!(!href.contains("%3F"), "{href}");
let _ = fs::remove_dir_all(dir);
}
#[test]
fn local_relative_images_are_embedded_from_markdown_directory() {
let dir = temp_test_dir("local-image");