#![cfg_attr( all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows" )] mod instance; mod session; use notify::{Event, RecursiveMode, Watcher}; use pulldown_cmark::{html, CowStr, Event as MdEvent, Options, Parser, Tag, TagEnd}; use session::DocumentSession; use std::collections::HashMap; use std::fs; use std::path::Component; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Instant; use tao::dpi::{LogicalPosition, LogicalSize}; use tao::event::{Event as TaoEvent, WindowEvent}; use tao::event_loop::{ControlFlow, EventLoop, EventLoopBuilder, EventLoopProxy}; use tao::window::{Theme, Window, WindowBuilder}; use wry::{WebView, WebViewBuilder}; const ICON_BYTES: &[u8] = include_bytes!("../assets/icon.ico"); const DEFAULT_W: f64 = 900.0; const DEFAULT_H: f64 = 700.0; static APP_DIRTY: AtomicBool = AtomicBool::new(false); #[derive(Debug)] struct SelfWriteRecord { path: PathBuf, content: String, } #[derive(Debug)] enum UserEvent { NewFile, OpenFile, OpenPaths(Vec, bool), ActivateTab(u64), CloseTab(u64), CloseActiveTab, LocateTab(u64), FileChanged(PathBuf), // external change: refresh preview AND textarea ExternalChangeResolved(bool), FileSaved(PathBuf), // our own save: refresh preview only, leave textarea cursor alone SaveFailed(PathBuf, String), DirtyChanged(bool), ToggleEdit, ShowFind, Print, // route print through wry's native API (WKWebView ignores window.print()) SetTheme(ThemeChoice), Quit, RecentChanged, Ready, // first paint landed: inject hljs now; if bench mode, also exit } #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] enum ThemeChoice { #[default] System, Light, Dark, } impl ThemeChoice { fn as_str(self) -> &'static str { match self { ThemeChoice::System => "system", ThemeChoice::Light => "light", ThemeChoice::Dark => "dark", } } fn from_str(value: &str) -> Self { match value.trim().to_ascii_lowercase().as_str() { "light" => ThemeChoice::Light, "dark" => ThemeChoice::Dark, _ => ThemeChoice::System, } } fn tao_theme(self) -> Option { match self { ThemeChoice::System => None, ThemeChoice::Light => Some(Theme::Light), ThemeChoice::Dark => Some(Theme::Dark), } } } #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] struct EnhanceFlags { math: bool, mermaid: bool, } impl EnhanceFlags { fn any(self) -> bool { self.math || self.mermaid } } fn is_help_arg(arg: &str) -> bool { arg == "-h" || arg == "--help" } fn print_help() { println!( "MD Preview {}\n\nUsage:\n md-preview [file.md]\n\nOptions:\n -h, --help Show this help message", env!("CARGO_PKG_VERSION") ); } #[derive(Copy, Clone)] enum Lang { Zh, En, } fn detect_lang() -> Lang { sys_locale::get_locale() .map(|l| { if l.to_lowercase().starts_with("zh") { Lang::Zh } else { Lang::En } }) .unwrap_or(Lang::En) } struct Strings { drop_hint: &'static str, cannot_read: &'static str, open_file: &'static str, recent_title: &'static str, missing_title: &'static str, missing_body: &'static str, locate_file: &'static str, close_tab: &'static str, cannot_save: &'static str, btn_edit: &'static str, btn_preview: &'static str, btn_new: &'static str, new_filename: &'static str, fold_toggle: &'static str, btn_zoom: &'static str, btn_zoom_out: &'static str, btn_zoom_reset: &'static str, btn_zoom_in: &'static str, search_placeholder: &'static str, stat_words: &'static str, stat_chars: &'static str, } impl Strings { fn for_lang(lang: Lang) -> Self { match lang { Lang::Zh => Strings { drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open", cannot_read: "无法读取文件", open_file: "Open File", recent_title: "Recent", missing_title: "文件已移动或删除", missing_body: "这个标签会继续保留。你可以重新定位文件,或关闭标签。", locate_file: "重新定位", close_tab: "关闭标签", cannot_save: "修改无法保存(文件可能只读或被占用)。继续将丢弃这些修改,是否继续?", btn_edit: "编辑 (Cmd/Ctrl+E)", btn_preview: "预览 (Cmd/Ctrl+E)", btn_new: "新建 Markdown (Cmd/Ctrl+N)", new_filename: "新建.md", fold_toggle: "折叠/展开", btn_zoom: "正文缩放", btn_zoom_out: "缩小正文 (Cmd/Ctrl+-)", btn_zoom_reset: "重置正文缩放 (Cmd/Ctrl+0)", btn_zoom_in: "放大正文 (Cmd/Ctrl++)", search_placeholder: "搜索", stat_words: "字", stat_chars: "字符", }, Lang::En => Strings { drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open", cannot_read: "Cannot read file", open_file: "Open File", recent_title: "Recent", missing_title: "File Moved or Deleted", missing_body: "This tab is kept. Locate the file again or close the tab.", locate_file: "Locate File", close_tab: "Close Tab", cannot_save: "This file could not be saved (read-only or locked). Continue and discard the unsaved changes?", btn_edit: "Edit (Cmd/Ctrl+E)", btn_preview: "Preview (Cmd/Ctrl+E)", btn_new: "New Markdown (Cmd/Ctrl+N)", new_filename: "Untitled.md", fold_toggle: "Collapse / Expand", btn_zoom: "Content zoom", btn_zoom_out: "Zoom out (Cmd/Ctrl+-)", btn_zoom_reset: "Reset zoom (Cmd/Ctrl+0)", btn_zoom_in: "Zoom in (Cmd/Ctrl++)", search_placeholder: "Find", stat_words: "non-space", stat_chars: "chars", }, } } } fn config_dir() -> PathBuf { if let Some(path) = std::env::var_os("MD_PREVIEW_CONFIG_DIR") { return PathBuf::from(path); } #[cfg(target_os = "windows")] { std::env::var_os("LOCALAPPDATA") .or_else(|| std::env::var_os("APPDATA")) .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(".")) .join("md-preview") } #[cfg(not(target_os = "windows"))] { std::env::var_os("HOME") .map(PathBuf::from) .unwrap_or_default() .join(".config/md-preview") } } #[derive(Copy, Clone)] struct WindowGeom { x: f64, y: f64, w: f64, h: f64, } fn geom_path() -> PathBuf { config_dir().join("window.geom") } fn theme_path() -> PathBuf { config_dir().join("theme.txt") } fn load_theme_choice() -> ThemeChoice { fs::read_to_string(theme_path()) .map(|raw| ThemeChoice::from_str(&raw)) .unwrap_or_default() } fn save_theme_choice(choice: ThemeChoice) { let dir = config_dir(); let _ = fs::create_dir_all(&dir); let _ = fs::write(dir.join("theme.txt"), choice.as_str()); } const ZOOM_MIN: u32 = 50; const ZOOM_MAX: u32 = 300; fn zoom_path() -> PathBuf { config_dir().join("zoom.txt") } fn clamp_zoom(percent: u32) -> u32 { percent.clamp(ZOOM_MIN, ZOOM_MAX) } fn load_zoom() -> u32 { fs::read_to_string(zoom_path()) .ok() .and_then(|raw| raw.trim().parse::().ok()) .map(clamp_zoom) .unwrap_or(100) } fn save_zoom(percent: u32) { let dir = config_dir(); let _ = fs::create_dir_all(&dir); let _ = fs::write(zoom_path(), clamp_zoom(percent).to_string()); } fn show_warning_dialog(title: &str, description: &str) { let _ = rfd::MessageDialog::new() .set_level(rfd::MessageLevel::Warning) .set_title(title) .set_description(description) .show(); } fn confirm_discard_unsaved(error: &str) -> bool { matches!( rfd::MessageDialog::new() .set_level(rfd::MessageLevel::Warning) .set_title("Could Not Save") .set_description(&format!( "{error}\n\nThe file may be read-only or locked by another program. Close the window and discard the unsaved changes?" )) .set_buttons(rfd::MessageButtons::OkCancel) .show(), rfd::MessageDialogResult::Ok ) } fn load_window_geom() -> Option { let txt = fs::read_to_string(geom_path()).ok()?; let parts: Vec<&str> = txt.trim().split(',').collect(); if parts.len() != 4 { return None; } Some(WindowGeom { x: parts[0].parse().ok()?, y: parts[1].parse().ok()?, w: parts[2].parse().ok()?, h: parts[3].parse().ok()?, }) } fn save_window_geom(window: &Window) { let Ok(pos) = window.outer_position() else { return; }; let scale = window.scale_factor(); let size = window.inner_size(); let geom = WindowGeom { x: pos.x as f64 / scale, y: pos.y as f64 / scale, w: size.width as f64 / scale, h: size.height as f64 / scale, }; if geom.w < 200.0 || geom.h < 150.0 { return; } let dir = config_dir(); let _ = fs::create_dir_all(&dir); let _ = fs::write( dir.join("window.geom"), format!("{},{},{},{}", geom.x, geom.y, geom.w, geom.h), ); } /// Return the saved geometry only when its center still falls inside /// some connected monitor — prevents the window from landing off-screen /// after a display swap. fn geom_visible(geom: &WindowGeom, event_loop: &EventLoop) -> bool { let cx = geom.x + geom.w / 2.0; let cy = geom.y + geom.h / 2.0; event_loop.available_monitors().any(|mon| { let scale = mon.scale_factor(); let mp = mon.position(); let ms = mon.size(); let mx = mp.x as f64 / scale; let my = mp.y as f64 / scale; let mw = ms.width as f64 / scale; let mh = ms.height as f64 / scale; cx >= mx && cx <= mx + mw && cy >= my && cy <= my + mh }) } fn centered_geom(event_loop: &EventLoop) -> WindowGeom { if let Some(mon) = event_loop.primary_monitor() { let scale = mon.scale_factor(); let mp = mon.position(); let ms = mon.size(); let mx = mp.x as f64 / scale; let my = mp.y as f64 / scale; let mw = ms.width as f64 / scale; let mh = ms.height as f64 / scale; WindowGeom { x: mx + (mw - DEFAULT_W) / 2.0, y: my + (mh - DEFAULT_H) / 2.0, w: DEFAULT_W, h: DEFAULT_H, } } else { WindowGeom { x: 100.0, y: 100.0, w: DEFAULT_W, h: DEFAULT_H, } } } #[cfg(test)] fn md_to_html(md: &str) -> String { md_to_html_with_base(md, None) } fn md_to_html_with_base(md: &str, base_dir: Option<&Path>) -> String { // A UTF-8 BOM is legal in files but not part of Markdown syntax. Strip it // before front-matter detection so both `---` metadata and a leading // heading still parse. let md = md.strip_prefix('\u{feff}').unwrap_or(md); let (front_matter, markdown) = split_yaml_front_matter(md) .map(|(metadata, body)| (Some(metadata), body)) .unwrap_or((None, md)); let opts = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_HEADING_ATTRIBUTES | Options::ENABLE_MATH | Options::ENABLE_GFM | Options::ENABLE_FOOTNOTES | Options::ENABLE_DEFINITION_LIST; let parser = Parser::new_ext(markdown, opts); let events = render_softbreaks_as_hard(embed_local_images( add_mark_highlights(add_heading_ids(parser.collect())), base_dir, )); let mut html_out = String::new(); if let Some(metadata) = front_matter { html_out.push_str(r#"\n"); } html::push_html(&mut html_out, events.into_iter()); html_out } /// AI-generated Markdown often uses a single newline as a visual line break. /// Treat those soft breaks as hard breaks in normal prose, but keep headings /// untouched: a multi-line setext heading should stay one visual line. fn render_softbreaks_as_hard<'a>(events: Vec>) -> Vec> { let mut heading_depth = 0usize; let mut out = Vec::with_capacity(events.len()); for event in events { match &event { MdEvent::Start(Tag::Heading { .. }) => heading_depth += 1, MdEvent::End(TagEnd::Heading(_)) => { heading_depth = heading_depth.saturating_sub(1); } MdEvent::SoftBreak if heading_depth == 0 => { out.push(MdEvent::HardBreak); continue; } _ => {} } out.push(event); } out } fn split_yaml_front_matter(md: &str) -> Option<(&str, &str)> { let mut lines = md.split_inclusive('\n'); let first = lines.next()?; if first.trim_end_matches(['\r', '\n']) != "---" { return None; } let metadata_start = first.len(); let mut offset = metadata_start; for line in lines { let value = line.trim_end_matches(['\r', '\n']); if value == "---" || value == "..." { let metadata = &md[metadata_start..offset]; let body = &md[offset + line.len()..]; return Some((metadata, body)); } offset += line.len(); } None } fn embed_local_images<'a>(events: Vec>, base_dir: Option<&Path>) -> Vec> { let Some(base_dir) = base_dir else { return events; }; events .into_iter() .map(|event| match event { MdEvent::Start(Tag::Image { link_type, dest_url, title, id, }) => { let embedded = local_image_data_url(base_dir, dest_url.as_ref()); MdEvent::Start(Tag::Image { link_type, dest_url: embedded.map(CowStr::from).unwrap_or(dest_url), title, id, }) } _ => event, }) .collect() } fn local_image_data_url(base_dir: &Path, url: &str) -> Option { let image_path = resolve_local_relative_image_path(base_dir, url)?; let mime = image_mime_type(&image_path)?; let bytes = fs::read(image_path).ok()?; Some(format!("data:{mime};base64,{}", base64_encode(&bytes))) } fn resolve_local_relative_image_path(base_dir: &Path, url: &str) -> Option { let path_part = url.split(['#', '?']).next()?.trim(); if !is_local_relative_url(path_part) { return None; } let mut candidate = base_dir.to_path_buf(); for segment in path_part.split('/') { if segment.is_empty() || segment == "." { continue; } let decoded = percent_decode_path_segment(segment)?; let segment_path = Path::new(&decoded); if segment_path .components() .any(|component| !matches!(component, Component::Normal(_))) { return None; } candidate.push(segment_path); } if candidate == base_dir { return None; } Some(candidate) } fn is_local_relative_url(url: &str) -> bool { !url.is_empty() && !url.starts_with('#') && !url.starts_with('/') && !url.starts_with('\\') && !url.starts_with("//") && !url.contains(':') } fn percent_decode_path_segment(segment: &str) -> Option { let bytes = segment.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; while i < bytes.len() { if bytes[i] == b'%' { let hi = bytes.get(i + 1).and_then(|b| hex_value(*b))?; let lo = bytes.get(i + 2).and_then(|b| hex_value(*b))?; out.push((hi << 4) | lo); i += 3; } else { out.push(bytes[i]); i += 1; } } String::from_utf8(out).ok() } fn hex_value(byte: u8) -> Option { match byte { b'0'..=b'9' => Some(byte - b'0'), b'a'..=b'f' => Some(byte - b'a' + 10), b'A'..=b'F' => Some(byte - b'A' + 10), _ => None, } } fn image_mime_type(path: &Path) -> Option<&'static str> { match path .extension()? .to_string_lossy() .to_ascii_lowercase() .as_str() { "png" => Some("image/png"), "jpg" | "jpeg" => Some("image/jpeg"), "gif" => Some("image/gif"), "webp" => Some("image/webp"), "svg" => Some("image/svg+xml"), "bmp" => Some("image/bmp"), "ico" => Some("image/x-icon"), "avif" => Some("image/avif"), _ => None, } } fn base64_encode(bytes: &[u8]) -> String { const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; let mut out = String::with_capacity(((bytes.len() + 2) / 3) * 4); let mut chunks = bytes.chunks_exact(3); for chunk in &mut chunks { let n = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32; out.push(TABLE[((n >> 18) & 0x3f) as usize] as char); out.push(TABLE[((n >> 12) & 0x3f) as usize] as char); out.push(TABLE[((n >> 6) & 0x3f) as usize] as char); out.push(TABLE[(n & 0x3f) as usize] as char); } match chunks.remainder() { [a] => { let n = (*a as u32) << 16; out.push(TABLE[((n >> 18) & 0x3f) as usize] as char); out.push(TABLE[((n >> 12) & 0x3f) as usize] as char); out.push('='); out.push('='); } [a, b] => { let n = ((*a as u32) << 16) | ((*b as u32) << 8); out.push(TABLE[((n >> 18) & 0x3f) as usize] as char); out.push(TABLE[((n >> 12) & 0x3f) as usize] as char); out.push(TABLE[((n >> 6) & 0x3f) as usize] as char); out.push('='); } _ => {} } out } fn add_mark_highlights<'a>(events: Vec>) -> Vec> { let mut out = Vec::with_capacity(events.len()); let mut code_block_depth = 0usize; for event in events { match &event { MdEvent::Start(Tag::CodeBlock(_)) => code_block_depth += 1, MdEvent::End(TagEnd::CodeBlock) => { code_block_depth = code_block_depth.saturating_sub(1); } MdEvent::Text(text) if code_block_depth == 0 && text.contains("==") => { push_mark_highlight_events(text.as_ref(), &mut out); continue; } _ => {} } out.push(event); } out } fn push_mark_highlight_events<'a>(text: &str, out: &mut Vec>) { let mut rest = text; while let Some(open) = rest.find("==") { let after_open = open + 2; let Some(close_rel) = rest[after_open..].find("==") else { break; }; let close = after_open + close_rel; let body = &rest[after_open..close]; if body.trim().is_empty() { break; } if open > 0 { out.push(MdEvent::Text(CowStr::Boxed( rest[..open].to_string().into_boxed_str(), ))); } out.push(MdEvent::Html(CowStr::Borrowed( r#""#, ))); out.push(MdEvent::Text(CowStr::Boxed( body.to_string().into_boxed_str(), ))); out.push(MdEvent::Html(CowStr::Borrowed(""))); rest = &rest[close + 2..]; } if !rest.is_empty() { out.push(MdEvent::Text(CowStr::Boxed( rest.to_string().into_boxed_str(), ))); } } fn add_heading_ids<'a>(mut events: Vec>) -> Vec> { let mut seen: HashMap = HashMap::new(); for i in 0..events.len() { let generate_id = match &events[i] { MdEvent::Start(Tag::Heading { id: Some(id), .. }) => { register_heading_id(id.as_ref(), &mut seen); false } MdEvent::Start(Tag::Heading { id: None, .. }) => true, _ => false, }; if !generate_id { continue; } let text = collect_heading_text(&events, i); let base = heading_slug(&text); let id_value = unique_heading_id(base, &mut seen); if let MdEvent::Start(Tag::Heading { id, .. }) = &mut events[i] { *id = Some(CowStr::Boxed(id_value.into_boxed_str())); } } events } fn collect_heading_text(events: &[MdEvent<'_>], start: usize) -> String { let mut text = String::new(); for event in events.iter().skip(start + 1) { match event { MdEvent::End(TagEnd::Heading(_)) => break, MdEvent::Text(value) | MdEvent::Code(value) | MdEvent::InlineMath(value) | MdEvent::DisplayMath(value) => text.push_str(value.as_ref()), MdEvent::SoftBreak | MdEvent::HardBreak => text.push(' '), _ => {} } } text } fn heading_slug(text: &str) -> String { let mut slug = String::new(); let mut last_dash = false; for c in text.trim().chars().flat_map(char::to_lowercase) { if c.is_alphanumeric() || c == '_' || c == '-' { slug.push(c); last_dash = false; } else if c.is_whitespace() && !slug.is_empty() && !last_dash { slug.push('-'); last_dash = true; } } while slug.ends_with('-') { slug.pop(); } if slug.is_empty() { "section".to_string() } else { slug } } fn register_heading_id(id: &str, seen: &mut HashMap) { if !id.is_empty() { *seen.entry(id.to_string()).or_insert(0) += 1; } } fn unique_heading_id(base: String, seen: &mut HashMap) -> String { let count = seen.entry(base.clone()).or_insert(0); let id = if *count == 0 { base } else { format!("{base}-{count}") }; *count += 1; id } // Embedded highlight.js + themes (offline) const HLJS_JS: &str = include_str!("../assets/hljs/highlight.min.js"); // Always-dark code blocks; app chrome still follows the system theme. const HLJS_CODE: &str = include_str!("../assets/hljs/vs-dark.css"); // Extra language pack(s) not in the `common` bundle. Each file // ends with `hljs.registerLanguage(...)` and only works if evaluated // in the same scope as the main bundle — we concat them into hljs-src. const HLJS_EXTRA_LANGS: &str = concat!( // Delphi / Pascal (aliases: dpr, dfm, pas, pascal) — user requested include_str!("../assets/hljs/delphi.min.js"), ); const PREVIEW_ENHANCE_JS: &str = include_str!("../assets/enhance/preview-enhance.js"); const KATEX_JS: &str = include_str!("../assets/katex/katex.min.js"); const KATEX_CSS: &str = include_str!("../assets/katex/katex.inline.css"); const MERMAID_JS: &str = include_str!("../assets/mermaid/mermaid.min.js"); const MAX_RECENT_FILES: usize = 8; fn html_escape_ta(s: &str) -> String { s.replace('&', "&").replace('<', "<") } fn html_escape_attr(s: &str) -> String { s.replace('&', "&") .replace('"', """) .replace('<', "<") } fn html_escape_text(s: &str) -> String { s.replace('&', "&") .replace('<', "<") .replace('>', ">") } fn recent_files_path() -> PathBuf { config_dir().join("recent-files.txt") } fn session_path() -> PathBuf { config_dir().join("session.json") } fn tabs_json(session: &DocumentSession) -> String { let tabs = session .tabs .iter() .map(|tab| { let name = tab .path .file_name() .map(|name| name.to_string_lossy().to_string()) .unwrap_or_else(|| tab.path.to_string_lossy().to_string()); serde_json::json!({ "id": tab.id, "name": name, "path": tab.path.to_string_lossy(), "active": session.active_id == Some(tab.id), "missing": tab.missing, "dirty": tab.dirty, }) }) .collect::>(); serde_json::to_string(&tabs).expect("tab state is serializable") } fn missing_preview_html(tab_id: u64, path: &Path, s: &Strings) -> String { format!( r#"
!

{}

{}

{}
"#, html_escape_text(s.missing_title), html_escape_text(s.missing_body), html_escape_text(&path.to_string_lossy()), html_escape_text(s.locate_file), html_escape_text(s.close_tab), ) } fn load_recent_files() -> Vec { let Ok(txt) = fs::read_to_string(recent_files_path()) else { return Vec::new(); }; let mut files = Vec::new(); for line in txt.lines() { 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); if files.len() == MAX_RECENT_FILES { break; } } files } fn save_recent_files(files: &[PathBuf]) { let dir = config_dir(); let _ = fs::create_dir_all(&dir); let body = files .iter() .take(MAX_RECENT_FILES) .map(|p| p.to_string_lossy()) .collect::>() .join("\n"); let _ = fs::write(dir.join("recent-files.txt"), body); } fn remember_recent_file(files: &Arc>>, path: &Path) { let mut recent = files.lock().unwrap(); recent.retain(|p| p != path); recent.insert(0, path.to_path_buf()); recent.truncate(MAX_RECENT_FILES); save_recent_files(&recent); } fn forget_recent_file(files: &Arc>>, path: &Path) -> bool { let mut recent = files.lock().unwrap(); let original_len = recent.len(); recent.retain(|p| p != path); if recent.len() == original_len { return false; } save_recent_files(&recent); true } fn base_href_for_file(path: &Path) -> Option { let dir = path.parent()?; url::Url::from_directory_path(dir) .ok() .map(|url| url.to_string()) } fn starts_mermaid_fence(line: &str) -> bool { let trimmed = line.trim_start(); let rest = trimmed .strip_prefix("```") .or_else(|| trimmed.strip_prefix("~~~")); let Some(info) = rest else { return false; }; let info = info.trim_start(); info == "mermaid" || info .strip_prefix("mermaid") .and_then(|s| s.chars().next()) .map(|c| c.is_whitespace() || c == '{') .unwrap_or(false) } fn has_unescaped_at(s: &str, index: usize, needle: &str) -> bool { if !s[index..].starts_with(needle) { return false; } let mut backslashes = 0; for b in s[..index].bytes().rev() { if b == b'\\' { backslashes += 1; } else { break; } } backslashes % 2 == 0 } fn has_unescaped_pair(s: &str, open: &str, close: &str) -> bool { let mut pos = 0; while let Some(rel) = s[pos..].find(open) { let start = pos + rel; if !has_unescaped_at(s, start, open) { pos = start + open.len(); continue; } let body_start = start + open.len(); let mut search = body_start; while let Some(close_rel) = s[search..].find(close) { let close_at = search + close_rel; if has_unescaped_at(s, close_at, close) { return true; } search = close_at + close.len(); } pos = body_start; } false } fn has_inline_dollar_math(s: &str) -> bool { let bytes = s.as_bytes(); let mut i = 0; while i < bytes.len() { if bytes[i] != b'$' || !has_unescaped_at(s, i, "$") { i += 1; continue; } if bytes.get(i + 1).copied() == Some(b'$') || bytes .get(i + 1) .map(|b| b.is_ascii_whitespace()) .unwrap_or(true) { i += 1; continue; } let mut j = i + 1; while j < bytes.len() { if bytes[j] == b'$' && has_unescaped_at(s, j, "$") && bytes .get(j.wrapping_sub(1)) .map(|b| !b.is_ascii_whitespace()) .unwrap_or(false) { return true; } j += 1; } i += 1; } false } fn enhance_flags_for(md: &str) -> EnhanceFlags { EnhanceFlags { math: has_unescaped_pair(md, "$$", "$$") || has_unescaped_pair(md, "\\[", "\\]") || has_unescaped_pair(md, "\\(", "\\)") || has_inline_dollar_math(md), mermaid: md.lines().any(starts_mermaid_fence), } } fn build_enhancer_bootstrap(flags: EnhanceFlags, loaded: EnhanceFlags) -> Vec { if !flags.any() { return Vec::new(); } let mut scripts = Vec::new(); if flags.math && !loaded.math { let mut js = String::from("(function(){\nif(!window.katex){\n"); js.push_str(KATEX_JS); js.push_str("\n;try{window.katex=katex;}catch(e){}\n}\n"); js.push_str("if(window.__setKatexCss)window.__setKatexCss('"); js.push_str(&escape_js(KATEX_CSS)); js.push_str("');\n})();"); scripts.push(js); } if flags.mermaid && !loaded.mermaid { // Mermaid's standalone bundle expects global script scope. Keep it // out of the function wrapper that is safe for KaTeX/highlight.js. let mut js = String::with_capacity(MERMAID_JS.len() + 80); js.push_str(MERMAID_JS); js.push_str("\n;try{window.mermaid=mermaid;}catch(e){}\n"); scripts.push(js); } scripts.push("if(window.__enhancePreview)window.__enhancePreview();".to_string()); scripts } fn empty_preview_html(s: &Strings, recent_files: &[PathBuf]) -> String { let empty_class = if recent_files.is_empty() { "empty" } else { "empty has-recent" }; let mut html = format!( r#"
#
{}
"#, html_escape_text(s.drop_hint), html_escape_text(s.open_file) ); if !recent_files.is_empty() { html.push_str(&format!( r#"
{}
"#, html_escape_text(s.recent_title) )); for (index, path) in recent_files.iter().take(MAX_RECENT_FILES).enumerate() { let name = path .file_name() .map(|n| n.to_string_lossy()) .unwrap_or_else(|| path.to_string_lossy()); let parent = path .parent() .map(|p| p.to_string_lossy()) .unwrap_or_default(); html.push_str(&format!( r#""#, html_escape_text(&name), html_escape_text(&parent) )); } html.push_str("
"); } html.push_str("
"); html } fn build_page( preview_html: &str, raw_md: &str, base_href: Option<&str>, flags: EnhanceFlags, s: &Strings, empty: bool, ) -> String { let body_class = if empty { "empty" } else { "" }; let base_tag = base_href .map(|href| format!(r#""#, html_escape_attr(href))) .unwrap_or_else(|| r#""#.to_string()); format!( r#" {base_tag}
{preview_html}
"#, css_code = HLJS_CODE, base_tag = base_tag, preview_html = preview_html, raw_md_escaped = html_escape_ta(raw_md), btn_new = s.btn_new, btn_edit = s.btn_edit, btn_preview = s.btn_preview, fold_toggle = s.fold_toggle, cannot_save_js = escape_js(s.cannot_save), btn_zoom = s.btn_zoom, btn_zoom_out = s.btn_zoom_out, btn_zoom_reset = s.btn_zoom_reset, btn_zoom_in = s.btn_zoom_in, search_placeholder = s.search_placeholder, stat_words_js = escape_js(s.stat_words), stat_chars_js = escape_js(s.stat_chars), body_class = body_class, needs_math = flags.math, needs_mermaid = flags.mermaid, preview_enhance_js = PREVIEW_ENHANCE_JS, ) } fn escape_js(s: &str) -> String { s.replace('\\', "\\\\") .replace('\'', "\\'") .replace('\n', "\\n") .replace('\r', "\\r") } fn watch_scope_for_file(path: &Path) -> &Path { path.parent() .filter(|parent| !parent.as_os_str().is_empty()) .unwrap_or(path) } fn event_path_matches_file(event_path: &Path, target: &Path) -> bool { event_path == target || (target.file_name().is_some() && event_path.file_name() == target.file_name() && event_path.parent() == target.parent()) } fn event_should_reload_file(ev: &Event, target: &Path) -> bool { if ev.need_rescan() { return true; } if !(ev.kind.is_modify() || ev.kind.is_create() || ev.kind.is_remove()) { return false; } ev.paths .iter() .any(|event_path| event_path_matches_file(event_path, target)) } #[cfg(test)] mod tests { use super::*; use notify::EventKind; use std::time::{SystemTime, UNIX_EPOCH}; fn temp_test_dir(name: &str) -> PathBuf { let unique = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); let dir = std::env::temp_dir().join(format!("md-preview-{name}-{}-{unique}", std::process::id())); fs::create_dir_all(&dir).unwrap(); dir } #[test] fn large_document_startup_stays_below_webview2_html_limit() { let dir = temp_test_dir("startup-large"); let file = dir.join("中文 large.md"); fs::write(&file, "x".repeat(3 * 1024 * 1024)).unwrap(); let mut session = DocumentSession::default(); session.open(file, true); let page = build_startup_page(&Strings::for_lang(Lang::En)); assert!( page.len() < 2 * 1024 * 1024, "startup HTML has {} bytes", page.len() ); assert!(session.active().unwrap().edit_on_open); fs::remove_dir_all(dir).unwrap(); } #[test] fn dollar_math_is_protected_from_markdown_escapes() { let html = md_to_html(r"$\{x\}$"); assert!(html.contains(r#"\{x\}"#)); } #[test] fn dollar_math_is_protected_from_markdown_emphasis() { let html = md_to_html(r"$\bar{\mu}_{n}$ and $x_{n}$"); assert!(html.contains(r#"\bar{\mu}_{n}"#)); assert!(html.contains(r#"x_{n}"#)); assert!(!html.contains("")); } #[test] fn multiline_display_math_is_not_split_by_hard_breaks() { let html = md_to_html("$$\na + b\n$$"); assert!(html.contains(r#"class="math math-display""#), "{html}"); assert!(html.contains("a + b"), "{html}"); assert!(!html.contains("
"), "{html}"); } #[test] fn github_alerts_render_as_markdown_alert_blockquotes() { let html = md_to_html("> [!IMPORTANT]\n> This is an alert"); assert!(html.contains(r#"
"#)); assert!(html.contains("

This is an alert

")); assert!(!html.contains("[!IMPORTANT]")); } #[test] fn soft_breaks_render_as_hard_breaks_in_paragraphs() { let html = md_to_html("2.1 默认只读讨论。\n2.2 默认工作流:先读代码。"); assert!( html.contains("2.1 默认只读讨论。
\n2.2 默认工作流"), "{html}" ); } #[test] fn blank_lines_still_create_paragraphs() { let html = md_to_html("first line\n\nsecond line"); assert_eq!(html.matches("

").count(), 2, "{html}"); assert!(!html.contains("
"), "{html}"); } #[test] fn soft_breaks_inside_headings_stay_soft() { let html = md_to_html("First heading line\nsecond heading line\n==="); assert!(html.contains(""), "{html}"); } #[test] fn soft_breaks_in_list_items_become_hard_breaks() { let html = md_to_html("- first line\n second line"); assert!(html.contains("

  • first line
    "), "{html}"); assert!(html.contains("second line
  • "), "{html}"); } #[test] fn code_blocks_keep_newlines_without_br() { let html = md_to_html("~~~text\nline one\nline two\n~~~"); assert!(!html.contains("
    "), "{html}"); assert!(html.contains("line one\nline two"), "{html}"); } #[test] fn gfm_footnotes_render_reference_and_definition() { let html = md_to_html("Text with a note[^1].\n\n[^1]: The footnote body."); assert!(html.contains(r#"class="footnote-reference""#), "{html}"); assert!(html.contains(r#"class="footnote-definition""#), "{html}"); assert!(html.contains("The footnote body."), "{html}"); } #[test] fn definition_lists_render_as_dl_dt_dd() { let html = md_to_html("Term\n: Definition"); assert!(html.contains("
    "), "{html}"); assert!(html.contains("
    Term
    "), "{html}"); assert!(html.contains("
    Definition
    "), "{html}"); } #[test] fn utf8_bom_is_ignored_before_heading_and_front_matter() { let heading = md_to_html("\u{feff}# BOM heading"); assert!( heading.contains(r#"

    BOM heading

    "#), "{heading}" ); let front_matter = md_to_html("\u{feff}---\ntitle: BOM\n---\n# Body"); assert!( front_matter.contains(r#"class="front-matter""#), "{front_matter}" ); assert!(front_matter.contains("title: BOM"), "{front_matter}"); assert!( front_matter.contains(r#"

    Body

    "#), "{front_matter}" ); } #[test] fn double_equals_highlight_renders_mark_without_touching_code() { let html = md_to_html("Use ==highlight & tag== here and `==literal==` there."); assert!(html.contains(r#"Use highlight & tag here"#)); assert!(html.contains("==literal==")); } #[test] fn fenced_code_blocks_keep_double_equals_literal() { let html = md_to_html("```csharp\nif (m_Profile == null) {\n return a == b;\n}\n```"); assert!(html.contains("m_Profile == null"), "comparison must stay literal"); assert!(html.contains("a == b"), "every comparison must be preserved"); 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"); let assets = dir.join("assets"); fs::create_dir_all(&assets).unwrap(); fs::write(assets.join("pixel.png"), b"abc").unwrap(); let html = md_to_html_with_base("![pixel](assets/pixel.png)", Some(&dir)); assert!(html.contains(r#"pixel"#)); let _ = fs::remove_dir_all(dir); } #[test] fn local_relative_images_keep_original_src_when_unreadable() { let dir = temp_test_dir("missing-image"); let html = md_to_html_with_base("![missing](assets/missing.png)", Some(&dir)); assert!(html.contains(r#"missing"#)); let _ = fs::remove_dir_all(dir); } #[test] fn local_relative_images_do_not_embed_parent_traversal() { let dir = temp_test_dir("traversal-image"); let html = md_to_html_with_base("![secret](../secret.png)", Some(&dir)); assert!(html.contains(r#"secret"#)); assert!(!html.contains("data:image/png")); let _ = fs::remove_dir_all(dir); } #[test] fn yaml_front_matter_keeps_metadata_readable_without_blank_lines() { let html = md_to_html( "---\nname: skill-creator-lite\ndescription: Skill 创建封装工具。\n---\n# Body", ); assert!(html.contains(r#"