use std::hash::{DefaultHasher, Hash, Hasher};
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use clap::{CommandFactory, Parser};
use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
mod browser;
mod codeblocks;
mod config;
mod docs;
mod editor;
#[cfg(target_os = "macos")]
mod finder;
mod frontmatter;
mod gitdiff;
mod github;
mod instances;
mod links;
mod obsidian;
mod pdf;
mod render;
mod server;
mod site;
mod tasks;
mod theme;
mod toc;
use config::{Config, Prefs};
use render::{FrontMatter, PageOptions, RenderOptions, Renderer, Style, Theme};
#[derive(Debug, Parser)]
#[command(name = "markdown-viewer", version, about)]
struct Cli {
file: Option<PathBuf>,
#[arg(short, long)]
watch: bool,
#[arg(short, long, value_name = "PATH", conflicts_with_all = ["watch", "pdf"])]
output: Option<PathBuf>,
#[arg(long, value_name = "PATH", conflicts_with = "watch")]
pdf: Option<PathBuf>,
#[arg(long, conflicts_with = "file")]
clipboard: bool,
#[arg(long, value_name = "FILE:LINE", conflicts_with_all = ["file", "clipboard", "output", "pdf"])]
goto: Option<String>,
#[arg(long, requires = "goto")]
if_running: bool,
#[arg(long, conflicts_with_all = ["watch", "output", "pdf", "clipboard", "goto"])]
check_links: bool,
#[arg(long, requires = "check_links")]
online: bool,
#[arg(short, long)]
port: Option<u16>,
#[arg(long)]
no_open: bool,
#[arg(long, value_name = "NAME")]
browser: Option<String>,
#[arg(long, group = "open_as")]
app: bool,
#[arg(long, group = "open_as")]
window: bool,
#[arg(long, group = "open_as")]
tab: bool,
#[arg(long)]
exit_when_closed: bool,
#[arg(long, exclusive = true, hide = !cfg!(target_os = "macos"))]
install_finder: bool,
#[arg(long, exclusive = true, hide = !cfg!(target_os = "macos"))]
uninstall_finder: bool,
#[arg(long, value_enum)]
theme: Option<Theme>,
#[arg(long, value_enum)]
style: Option<Style>,
#[arg(long, value_name = "PATH")]
css: Option<PathBuf>,
#[arg(long)]
number_headings: bool,
#[arg(long)]
line_numbers: bool,
#[arg(long, value_enum, value_name = "HOW")]
front_matter: Option<FrontMatter>,
#[arg(long, overrides_with = "no_obsidian")]
obsidian: bool,
#[arg(long, overrides_with = "obsidian")]
no_obsidian: bool,
#[arg(long, value_name = "COMMAND")]
editor: Option<String>,
#[arg(long, value_enum, value_name = "SHELL", exclusive = true, hide = true)]
generate_completions: Option<clap_complete::Shell>,
#[arg(long, exclusive = true, hide = true)]
generate_man: bool,
}
fn main() {
if let Err(err) = run(Cli::parse()) {
eprintln!("markdown-viewer: {err:#}");
std::process::exit(1);
}
}
struct Settings {
style: Style,
css_path: Option<PathBuf>,
css: Option<String>,
open: browser::Mode,
browser: Option<String>,
port: u16,
theme_flag: Option<Theme>,
config_theme: Option<Theme>,
number_headings: bool,
line_numbers: bool,
front_matter: FrontMatter,
obsidian: Option<bool>,
editor: Option<String>,
}
impl Settings {
fn new(cli: &Cli, config: Config) -> Result<Self> {
let css_path = cli.css.clone().or(config.css.clone());
let css = match &css_path {
Some(p) => Some(
std::fs::read_to_string(p)
.with_context(|| format!("cannot read CSS file {}", p.display()))?,
),
None => None,
};
let open = if cli.tab {
browser::Mode::Tab
} else if cli.window {
browser::Mode::Window
} else if cli.app {
browser::Mode::App
} else {
config.open_mode().unwrap_or_default()
};
let obsidian = if cli.obsidian {
Some(true)
} else if cli.no_obsidian {
Some(false)
} else {
config.obsidian
};
Ok(Self {
style: cli.style.or(config.style).unwrap_or_default(),
css_path,
css,
open,
browser: cli.browser.clone().or(config.browser),
port: cli.port.or(config.port).unwrap_or(0),
theme_flag: cli.theme,
config_theme: config.theme,
number_headings: cli.number_headings || config.number_headings.unwrap_or(false),
line_numbers: cli.line_numbers || config.line_numbers.unwrap_or(false),
front_matter: cli.front_matter.or(config.front_matter).unwrap_or_default(),
obsidian,
editor: cli.editor.clone().or(config.editor),
})
}
fn viewing_theme(&self, prefs: &Prefs) -> Theme {
self.theme_flag
.or(prefs.theme)
.or(self.config_theme)
.unwrap_or_default()
}
fn export_theme(&self) -> Theme {
self.theme_flag.or(self.config_theme).unwrap_or_default()
}
fn render_options(&self, sourcepos: bool, at: &Path) -> RenderOptions {
RenderOptions {
sourcepos,
obsidian: self.obsidian.unwrap_or_else(|| obsidian::in_vault(at)),
front_matter: self.front_matter,
line_numbers: self.line_numbers,
}
}
fn page(&self, title: String, theme: Theme) -> PageOptions {
PageOptions {
title,
theme,
style: self.style,
custom_css: self.css.clone(),
fixed_theme: self.theme_flag.is_some(),
number_headings: self.number_headings,
..Default::default()
}
}
}
enum Source {
File(PathBuf),
Folder(PathBuf),
Text {
name: &'static str,
text: String,
},
}
fn run(cli: Cli) -> Result<()> {
if let Some(shell) = cli.generate_completions {
clap_complete::generate(
shell,
&mut docs_command(),
"markdown-viewer",
&mut std::io::stdout(),
);
return Ok(());
}
if cli.generate_man {
clap_mangen::Man::new(docs_command()).render(&mut std::io::stdout())?;
return Ok(());
}
if cli.install_finder || cli.uninstall_finder {
return finder_integration(cli.install_finder);
}
let settings = Settings::new(&cli, Config::load()?)?;
let cwd = std::env::current_dir()?.canonicalize()?;
let goto = cli.goto.as_deref().map(parse_goto).transpose()?;
if let Some((file, line)) = &goto
&& let Some(url) = instances::find_serving(file)
{
if !instances::send_goto(&url, file, *line) {
bail!("couldn't reach the viewer at {url}");
}
say(&format!("Showing {}:{line} at {url}", file.display()));
return Ok(());
}
if goto.is_some() && cli.if_running {
return Ok(());
}
let watch = cli.watch || goto.is_some();
if cli.check_links {
let target = cli.file.clone().unwrap_or_else(|| cwd.clone());
return check_links(&settings, &target, cli.online);
}
let source = if let Some((file, _)) = &goto {
Source::File(file.clone())
} else if cli.clipboard {
Source::Text {
name: "Clipboard",
text: read_clipboard()?,
}
} else {
match &cli.file {
Some(p) if p.as_os_str() == "-" => {
let mut text = String::new();
std::io::stdin()
.read_to_string(&mut text)
.context("cannot read standard input")?;
Source::Text {
name: "stdin",
text,
}
}
Some(p) => {
let path = p
.canonicalize()
.with_context(|| format!("cannot open {}", p.display()))?;
if path.is_dir() {
Source::Folder(path)
} else if path.is_file() {
Source::File(path)
} else {
bail!("{} is not a file", p.display());
}
}
None => Source::Folder(cwd.clone()),
}
};
let (markdown, dir, title) = match &source {
Source::Folder(path) => {
if let Some(out) = &cli.output {
if out.as_os_str() == "-" {
bail!("{} is a folder; -o - needs a Markdown file", path.display());
}
return export_site(&settings, path, out);
}
if cli.pdf.is_some() {
bail!(
"{} is a folder; --pdf needs a Markdown file",
path.display()
);
}
return serve(&cli, &settings, &source, None);
}
Source::File(path) => (
read(path)?,
path.parent()
.context("file has no parent folder")?
.to_path_buf(),
server::file_title(path),
),
Source::Text { name, text } => (text.clone(), cwd.clone(), name.to_string()),
};
if !watch && (cli.exit_when_closed || cli.port.is_some()) {
bail!("--port and --exit-when-closed need --watch");
}
let (renderer, body) = render_standalone(&settings, &markdown, &dir);
if let Some(output) = &cli.output {
let page = settings.page(title, settings.export_theme());
let html = renderer.wrap_page(&body, &page);
if output.as_os_str() == "-" {
std::io::stdout().write_all(html.as_bytes())?;
} else {
std::fs::write(output, html)
.with_context(|| format!("cannot write {}", output.display()))?;
}
return Ok(());
}
if let Some(out) = &cli.pdf {
let page = PageOptions {
base_href: Some(dir_url(&dir)),
..settings.page(title, Theme::Light)
};
pdf::print(&renderer.wrap_page(&body, &page), out)?;
say(&format!("Wrote {}", out.display()));
return Ok(());
}
if watch {
return serve(&cli, &settings, &source, goto.map(|(_, line)| line));
}
let prefs = Prefs::load();
let page = PageOptions {
base_href: Some(dir_url(&dir)),
ui: true,
sidebar: prefs.sidebar.clone(),
..settings.page(title.clone(), settings.viewing_theme(&prefs))
};
let key = match &source {
Source::File(path) => path.clone(),
_ => dir.join(&title),
};
let out = temp_page_path(&key)?;
std::fs::write(&out, renderer.wrap_page(&body, &page))
.with_context(|| format!("cannot write {}", out.display()))?;
say(&out.display().to_string());
if !cli.no_open {
browser::open(&file_url(&out), settings.browser.as_deref(), settings.open)?;
}
Ok(())
}
fn docs_command() -> clap::Command {
Cli::command()
.mut_arg("install_finder", |a| a.hide(false))
.mut_arg("uninstall_finder", |a| a.hide(false))
}
fn render_standalone(settings: &Settings, markdown: &str, dir: &Path) -> (Renderer, String) {
let options = settings.render_options(false, dir);
let renderer = Renderer::with_options(options.clone());
let body = if options.obsidian {
let root = obsidian::vault_root(dir).unwrap_or_else(|| dir.to_path_buf());
let (files, _) = docs::markdown_files(&root);
let ctx = obsidian::LinkContext {
root: &root,
dir,
files: &files,
served: false,
depth: 0,
};
renderer.render_doc(markdown, Some(&ctx))
} else {
renderer.render_body(markdown)
};
(renderer, body)
}
fn export_site(settings: &Settings, root: &Path, out: &Path) -> Result<()> {
let options = settings.render_options(false, root);
let renderer = Renderer::with_options(options.clone());
let page = |title: String| settings.page(title, settings.export_theme());
let summary = site::export(&renderer, options.obsidian, root, out, &page)?;
if summary.truncated {
say("Only the first 2,000 Markdown files were exported.");
}
let files = match summary.files {
0 => String::new(),
1 => " and 1 file".into(),
n => format!(" and {n} files"),
};
say(&format!(
"Wrote {} pages{files} to {} (start at {})",
summary.pages,
out.display(),
out.join("index.html").display()
));
Ok(())
}
fn parse_goto(spec: &str) -> Result<(PathBuf, u32)> {
let (path, line) = match spec.rsplit_once(':') {
Some((p, l)) if !p.is_empty() && l.chars().all(|c| c.is_ascii_digit()) && !l.is_empty() => {
(p, l.parse().unwrap_or(1))
}
_ => (spec, 1),
};
let file = Path::new(path)
.canonicalize()
.with_context(|| format!("cannot open {path}"))?;
if !file.is_file() {
bail!("{path} is not a file");
}
Ok((file, line.max(1)))
}
fn check_links(settings: &Settings, target: &Path, online: bool) -> Result<()> {
let target = target
.canonicalize()
.with_context(|| format!("cannot open {}", target.display()))?;
let (root, files) = if target.is_dir() {
let (files, _) = docs::markdown_files(&target);
let files = files.iter().map(|f| target.join(f)).collect();
(target.clone(), files)
} else {
let parent = target.parent().context("file has no parent folder")?;
let root = obsidian::vault_root(parent).unwrap_or_else(|| parent.to_path_buf());
(root, vec![target.clone()])
};
let renderer = Arc::new(Renderer::with_options(settings.render_options(true, &root)));
let checker = links::Checker::new(renderer, root.clone());
let shown = |f: &Path| -> String {
let base = if target.is_dir() { &target } else { &root };
f.strip_prefix(base)
.map(|p| p.display().to_string())
.unwrap_or_else(|_| f.display().to_string())
};
let mut problems: Vec<(String, u32, String, String)> = Vec::new();
let mut web: Vec<(String, links::Link)> = Vec::new();
let mut total = 0;
for file in &files {
let (broken, external, count) = checker.check(file);
total += count;
for b in broken {
problems.push((shown(file), b.line, b.target, b.reason));
}
web.extend(external.into_iter().map(|l| (shown(file), l)));
}
if online && !web.is_empty() {
let urls = web.iter().map(|(_, l)| l.target.clone()).collect();
let failures = links::check_online(&urls).map_err(anyhow::Error::msg)?;
for (file, link) in &web {
if let Some(reason) = failures.get(&link.target) {
problems.push((file.clone(), link.line, link.target.clone(), reason.clone()));
}
}
}
problems.sort();
for (file, line, target, reason) in &problems {
say(&format!("{file}:{line}: {target} ({reason})"));
}
let not_checked = if online || web.is_empty() {
String::new()
} else {
format!(" {} web links not checked (add --online).", web.len())
};
let files_word = if files.len() == 1 { "file" } else { "files" };
say(&format!(
"Checked {total} links in {} {files_word}: {} broken.{not_checked}",
files.len(),
problems.len()
));
if !problems.is_empty() {
std::process::exit(1);
}
Ok(())
}
fn serve(cli: &Cli, settings: &Settings, source: &Source, start_line: Option<u32>) -> Result<()> {
let cwd = std::env::current_dir()?.canonicalize()?;
let (root, main, identity) = match source {
Source::Folder(dir) => (dir.clone(), None, Some(dir.clone())),
Source::File(file) => {
let parent = file.parent().context("file has no parent folder")?;
let options = settings.render_options(true, parent);
let root = options
.obsidian
.then(|| obsidian::vault_root(parent))
.flatten()
.unwrap_or_else(|| parent.to_path_buf());
(root, Some(file.clone()), Some(file.clone()))
}
Source::Text { name, .. } => (cwd.clone(), Some(cwd.join(format!("({name})"))), None),
};
if let Some(target) = &identity
&& let Some(url) = instances::find(target)
{
if !cli.no_open && !browser::focus(&url, settings.browser.as_deref()) {
browser::open(&url, settings.browser.as_deref(), settings.open)?;
}
say(&format!("Already open at {url}"));
return Ok(());
}
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
rt.block_on(async move {
let renderer = Arc::new(Renderer::with_options(settings.render_options(true, &root)));
let docs = docs::Docs::new(root.clone(), renderer.clone())?;
if let (Source::Text { text, .. }, Some(key)) = (source, &main) {
docs.add_virtual(key, docs.render_text(text, &root));
if cli.clipboard && cli.watch {
follow_clipboard(docs.clone(), key.clone(), root.clone(), text.clone());
}
}
let saved = Prefs::load();
let prefs = Prefs {
theme: Some(settings.viewing_theme(&saved)),
..saved
};
let page = PageOptions {
served: true,
live: true,
ui: true,
custom_css: None,
..settings.page(String::new(), Theme::Auto)
};
let server = server::Server::bind(server::ServeOptions {
port: settings.port,
docs,
renderer,
main: main.clone(),
page,
custom_css: settings.css_path.clone(),
prefs,
remember: true,
editor: settings.editor.clone(),
identity: identity
.as_ref()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default(),
})
.await?;
let url = server.url();
let port = url
.trim_end_matches('/')
.rsplit(':')
.next()
.and_then(|p| p.parse().ok())
.unwrap_or(0);
let _registration = identity.as_ref().and_then(|t| instances::register(t, port));
let handle = server.handle();
let shown = match source {
Source::Text { name, .. } => name.to_string(),
_ => identity
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_default(),
};
say(&format!("Serving {shown} at {url}"));
say("Watching for changes. Press Ctrl-C to stop.");
let mut server = tokio::spawn(server.run());
if !cli.no_open {
handle.set_close_on_exit(settings.open != browser::Mode::Tab);
let page_url = match start_line {
Some(line) => format!("{url}#mdv-line-{line}"),
None => url.clone(),
};
let opened = browser::open(&page_url, settings.browser.as_deref(), settings.open)?;
handle.set_close_on_exit(opened == browser::Opened::Window);
}
let abandoned = async {
if cli.exit_when_closed {
handle
.abandoned(Duration::from_secs(5), Duration::from_secs(60))
.await;
} else {
std::future::pending::<()>().await;
}
};
tokio::select! {
res = &mut server => res?,
_ = abandoned => {
say("Page closed; exiting.");
Ok(())
}
_ = tokio::signal::ctrl_c() => {
handle.announce_shutdown();
tokio::time::sleep(Duration::from_millis(300)).await;
Ok(())
}
}
})
}
fn follow_clipboard(docs: Arc<docs::Docs>, key: PathBuf, root: PathBuf, mut last: String) {
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_millis(800)).await;
let Ok(Ok(text)) = tokio::task::spawn_blocking(read_clipboard).await else {
continue;
};
if text != last && !text.trim().is_empty() {
let html = docs.render_text(&text, &root);
docs.set_virtual(&key, html);
last = text;
}
}
});
}
fn read_clipboard() -> Result<String> {
let candidates: &[(&str, &[&str])] = if cfg!(target_os = "macos") {
&[("pbpaste", &[])]
} else {
&[
("wl-paste", &["--no-newline"]),
("xclip", &["-selection", "clipboard", "-o"]),
("xsel", &["--clipboard", "--output"]),
]
};
for (program, args) in candidates {
if let Ok(out) = std::process::Command::new(program).args(*args).output()
&& out.status.success()
{
return Ok(String::from_utf8_lossy(&out.stdout).into_owned());
}
}
bail!("couldn't read the clipboard (needs pbpaste, wl-paste, xclip or xsel)")
}
#[cfg(target_os = "macos")]
fn finder_integration(install: bool) -> Result<()> {
if install {
finder::install()
} else {
finder::uninstall()
}
}
#[cfg(not(target_os = "macos"))]
fn finder_integration(_install: bool) -> Result<()> {
bail!("Finder integration is only available on macOS")
}
fn say(msg: &str) {
let _ = writeln!(std::io::stdout(), "{msg}");
}
fn read(path: &Path) -> Result<String> {
std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))
}
fn temp_page_path(source: &Path) -> Result<PathBuf> {
let dir = std::env::temp_dir().join("markdown-viewer");
std::fs::create_dir_all(&dir)?;
let mut h = DefaultHasher::new();
source.hash(&mut h);
let stem = source
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| "page".into());
Ok(dir.join(format!("{stem}-{:08x}.html", h.finish() as u32)))
}
const PATH_ENCODE: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'%')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'`')
.add(b'{')
.add(b'}');
fn file_url(path: &Path) -> String {
let path = path.to_string_lossy();
format!("file://{}", utf8_percent_encode(&path, PATH_ENCODE))
}
fn dir_url(dir: &Path) -> String {
let mut url = file_url(dir);
if !url.ends_with('/') {
url.push('/');
}
url
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn file_url_encodes_and_ends_with_slash() {
assert_eq!(
dir_url(Path::new("/tmp/my docs#1")),
"file:///tmp/my%20docs%231/"
);
}
#[test]
fn generates_completions_and_man_page() {
for shell in [
clap_complete::Shell::Bash,
clap_complete::Shell::Zsh,
clap_complete::Shell::Fish,
] {
let mut out = Vec::new();
clap_complete::generate(shell, &mut docs_command(), "markdown-viewer", &mut out);
let text = String::from_utf8(out).unwrap();
assert!(text.contains("number-headings"), "{shell:?}");
}
let mut man = Vec::new();
clap_mangen::Man::new(docs_command())
.render(&mut man)
.unwrap();
assert!(
String::from_utf8(man)
.unwrap()
.contains(".TH markdown-viewer")
);
}
#[test]
fn cli_is_valid() {
use clap::CommandFactory;
Cli::command().debug_assert();
}
}