diff --git a/Cargo.lock b/Cargo.lock index 6c8c860..d4c6adf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -855,7 +855,9 @@ dependencies = [ "notify", "open", "ratatui", + "serde", "syntect", + "toml", "unicode-segmentation", "unicode-width", "ureq", @@ -1347,6 +1349,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -1369,6 +1372,15 @@ dependencies = [ "syn", ] +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + [[package]] name = "shlex" version = "1.3.0" @@ -1575,6 +1587,37 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +dependencies = [ + "winnow 1.0.2", +] + [[package]] name = "typed-arena" version = "2.0.2" @@ -1902,6 +1945,18 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee1708bef14716a11bae175f579062d4554d95be2c6829f518df847b7b3fdd0" + [[package]] name = "writeable" version = "0.6.3" diff --git a/Cargo.toml b/Cargo.toml index 31b619e..95e84a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,9 @@ crossterm = "0.29" notify = "8" open = "5" ratatui = { version = "0.30", default-features = false, features = ["crossterm"] } +serde = { version = "1", features = ["derive"] } syntect = { version = "5", default-features = false, features = ["default-syntaxes", "default-themes", "parsing", "regex-fancy"] } +toml = { version = "0.9", default-features = false, features = ["parse", "serde"] } unicode-segmentation = "1" unicode-width = "0.2" ureq = "3" diff --git a/README.md b/README.md index a74bb61..5ffab35 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,30 @@ Press `?` inside the TUI for the same list shown here. | `Enter` (in yank mode) | Copy selection to OS clipboard | | `Esc` (in yank mode) | Cancel yank | +### Customizing + +Drop a TOML file at `$XDG_CONFIG_HOME/markdown-browser/config.toml` (default +`~/.config/markdown-browser/config.toml`) to override or extend the defaults. +Modes: `normal`, `yank`, `toc`, `help`, `dir`. Action names are the +snake_case form of the variants in `src/cli/keymap.rs`. + +```toml +[keys.normal] +"shift+h" = "history_back" +"shift+l" = "history_forward" +"ctrl+e" = "toggle_shortcodes" + +[keys.dir] +"backspace" = "dir_go_up" +``` + +Key syntax: modifiers as `ctrl+` / `alt+` / `shift+` prefixes (any order, +case-insensitive); the key is either a single character (case-sensitive), +a named key (`esc`, `enter`, `tab`, `backtab`, `space`, `left`, `up`, +`pageup`, ...) or `f1`–`f12`. Unknown keys or actions surface as a +startup warning in the status bar — markdown-browser never aborts on a +bad config. + ## License [MIT](LICENSE-MIT). diff --git a/src/cli/keymap.rs b/src/cli/keymap.rs index 8da40ac..89b023d 100644 --- a/src/cli/keymap.rs +++ b/src/cli/keymap.rs @@ -1,9 +1,11 @@ -//! Keyboard bindings for the TUI. Phase 1: every key handler is -//! refactored to look up a single [`Action`] in a per-mode [`Keymap`] -//! and dispatch it. The defaults reproduce the previous hard-coded -//! match arms exactly; user-supplied overrides land in Phase 2. +//! Keyboard bindings for the TUI. Per-mode [`Keymap`]s map [`Chord`]s +//! to [`Action`]s, the dispatcher in `tui.rs` is the only place that +//! turns an `Action` into a side effect. Defaults are built in code; +//! `~/.config/markdown-browser/config.toml` can override or extend +//! them via [`load`]. use std::collections::HashMap; +use std::path::PathBuf; use crossterm::event::{KeyCode, KeyModifiers}; @@ -205,3 +207,401 @@ pub fn default_dir() -> Keymap { m.insert(ch('h'), DirGoUp); m } + +impl Action { + /// Resolve a config-file action name (snake_case) to a variant. + /// Kept exhaustive on purpose so the compiler shouts if a new + /// `Action` is added without exposing it to config. + pub fn from_name(name: &str) -> Option { + Some(match name { + "quit" => Self::Quit, + "open_toc" => Self::OpenToc, + "open_help" => Self::OpenHelp, + "open_dir" => Self::OpenDir, + "toggle_line_numbers" => Self::ToggleLineNumbers, + "toggle_shortcodes" => Self::ToggleShortcodes, + "start_search" => Self::StartSearch, + "search_next" => Self::SearchNext, + "search_prev" => Self::SearchPrev, + "link_next" => Self::LinkNext, + "link_prev" => Self::LinkPrev, + "activate_link" => Self::ActivateLink, + "history_back" => Self::HistoryBack, + "history_forward" => Self::HistoryForward, + "cursor_down" => Self::CursorDown, + "cursor_up" => Self::CursorUp, + "cursor_half_page_down" => Self::CursorHalfPageDown, + "cursor_half_page_up" => Self::CursorHalfPageUp, + "cursor_page_down" => Self::CursorPageDown, + "cursor_page_up" => Self::CursorPageUp, + "cursor_top" => Self::CursorTop, + "cursor_bottom" => Self::CursorBottom, + "section_next" => Self::SectionNext, + "section_prev" => Self::SectionPrev, + "enter_yank" => Self::EnterYank, + "yank_cancel" => Self::YankCancel, + "yank_expand" => Self::YankExpand, + "yank_shrink" => Self::YankShrink, + "yank_copy" => Self::YankCopy, + "toc_close" => Self::TocClose, + "toc_select_next" => Self::TocSelectNext, + "toc_select_prev" => Self::TocSelectPrev, + "toc_select_top" => Self::TocSelectTop, + "toc_select_bottom" => Self::TocSelectBottom, + "toc_confirm" => Self::TocConfirm, + "help_close" => Self::HelpClose, + "dir_close" => Self::DirClose, + "dir_select_next" => Self::DirSelectNext, + "dir_select_prev" => Self::DirSelectPrev, + "dir_select_top" => Self::DirSelectTop, + "dir_select_bottom" => Self::DirSelectBottom, + "dir_activate" => Self::DirActivate, + "dir_go_up" => Self::DirGoUp, + _ => return None, + }) + } +} + +/// Parse a chord description like `"ctrl+d"`, `"alt+left"`, `"esc"`, +/// `"G"`, or `"shift+tab"`. Modifiers can be combined (`"ctrl+alt+x"`) +/// and are case-insensitive; the key name is case-sensitive for +/// single characters and case-insensitive for named keys. The result +/// is fed through [`normalize_chord`] so storage matches what the +/// runtime delivers. +pub fn parse_chord(s: &str) -> Result { + let parts: Vec<&str> = s.split('+').collect(); + if parts.is_empty() || parts.iter().any(|p| p.is_empty()) { + return Err(format!("`{s}` is not a valid chord")); + } + let (key_str, prefixes) = parts.split_last().unwrap(); + let mut mods = KeyModifiers::NONE; + for prefix in prefixes { + match prefix.to_ascii_lowercase().as_str() { + "ctrl" | "control" => mods |= KeyModifiers::CONTROL, + "alt" | "meta" | "opt" | "option" => mods |= KeyModifiers::ALT, + "shift" => mods |= KeyModifiers::SHIFT, + other => return Err(format!("unknown modifier `{other}`")), + } + } + let mut code = parse_key_code(key_str)?; + // `shift+tab` is the conventional name for `BackTab`. Convert + // before normalization, otherwise we'd just strip the shift and + // lose the distinction from a plain Tab. + if mods.contains(KeyModifiers::SHIFT) && code == KeyCode::Tab { + code = KeyCode::BackTab; + mods -= KeyModifiers::SHIFT; + } + // `shift+` is the same key the user would write uppercase. + if mods.contains(KeyModifiers::SHIFT) + && let KeyCode::Char(c) = code + && c.is_ascii_lowercase() + { + code = KeyCode::Char(c.to_ascii_uppercase()); + mods -= KeyModifiers::SHIFT; + } + Ok(normalize_chord(code, mods)) +} + +fn parse_key_code(s: &str) -> Result { + let lower = s.to_ascii_lowercase(); + Ok(match lower.as_str() { + "esc" | "escape" => KeyCode::Esc, + "enter" | "return" | "ret" => KeyCode::Enter, + "tab" => KeyCode::Tab, + "backtab" => KeyCode::BackTab, + "backspace" | "bs" => KeyCode::Backspace, + "space" | "spc" => KeyCode::Char(' '), + "left" => KeyCode::Left, + "right" => KeyCode::Right, + "up" => KeyCode::Up, + "down" => KeyCode::Down, + "home" => KeyCode::Home, + "end" => KeyCode::End, + "pageup" | "pgup" => KeyCode::PageUp, + "pagedown" | "pgdn" => KeyCode::PageDown, + "delete" | "del" => KeyCode::Delete, + "insert" | "ins" => KeyCode::Insert, + _ => { + // F1..F12. + if let Some(n) = lower.strip_prefix('f') + && let Ok(n) = n.parse::() + && (1..=12).contains(&n) + { + return Ok(KeyCode::F(n)); + } + // Single character (case-sensitive). + let mut chars = s.chars(); + if let Some(c) = chars.next() + && chars.next().is_none() + { + return Ok(KeyCode::Char(c)); + } + return Err(format!("unknown key `{s}`")); + } + }) +} + +#[derive(serde::Deserialize, Default)] +struct ConfigFile { + #[serde(default)] + keys: HashMap>, +} + +/// Result of merging user config into the built-in defaults. +pub struct LoadedKeymaps { + pub normal: Keymap, + pub yank: Keymap, + pub toc: Keymap, + pub help: Keymap, + pub dir: Keymap, + /// Human-readable problems collected while parsing config — bad + /// modifiers, unknown actions, etc. The TUI surfaces these in the + /// status bar at startup; we never abort on a config problem. + pub warnings: Vec, + /// `Some` when a config file was found (regardless of whether it + /// parsed). Lets the UI mention the path in warnings. + pub config_path: Option, +} + +/// Build the per-mode keymaps for an App. Loads +/// `$XDG_CONFIG_HOME/markdown-browser/config.toml` (or the `~/.config` +/// fallback) if it exists. Missing file is silent; parse errors and +/// bad bindings come back via `warnings`. +pub fn load() -> LoadedKeymaps { + let mut out = LoadedKeymaps { + normal: default_normal(), + yank: default_yank(), + toc: default_toc(), + help: default_help(), + dir: default_dir(), + warnings: Vec::new(), + config_path: None, + }; + let Some(path) = config_path() else { + return out; + }; + out.config_path = Some(path.clone()); + let content = match std::fs::read_to_string(&path) { + Ok(c) => c, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return out, + Err(e) => { + out.warnings.push(format!("read config: {e}")); + return out; + } + }; + let cfg: ConfigFile = match toml::from_str(&content) { + Ok(c) => c, + Err(e) => { + out.warnings.push(format!("parse config: {e}")); + return out; + } + }; + for (mode, table) in cfg.keys { + let map = match mode.as_str() { + "normal" => &mut out.normal, + "yank" => &mut out.yank, + "toc" => &mut out.toc, + "help" => &mut out.help, + "dir" => &mut out.dir, + _ => { + out.warnings.push(format!("unknown mode `{mode}`")); + continue; + } + }; + for (key, action_name) in table { + let chord = match parse_chord(&key) { + Ok(c) => c, + Err(e) => { + out.warnings.push(format!("[{mode}] `{key}`: {e}")); + continue; + } + }; + let Some(action) = Action::from_name(&action_name) else { + out.warnings + .push(format!("[{mode}] `{key}`: unknown action `{action_name}`")); + continue; + }; + map.insert(chord, action); + } + } + out +} + +fn config_path() -> Option { + if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") + && !xdg.is_empty() + { + return Some(PathBuf::from(xdg).join("markdown-browser/config.toml")); + } + let home = std::env::var("HOME").ok()?; + Some(PathBuf::from(home).join(".config/markdown-browser/config.toml")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_simple_keys() { + assert_eq!( + parse_chord("j").unwrap(), + (KeyCode::Char('j'), KeyModifiers::NONE) + ); + assert_eq!( + parse_chord("G").unwrap(), + (KeyCode::Char('G'), KeyModifiers::NONE) + ); + assert_eq!( + parse_chord("?").unwrap(), + (KeyCode::Char('?'), KeyModifiers::NONE) + ); + } + + #[test] + fn parse_modifiers() { + assert_eq!( + parse_chord("ctrl+d").unwrap(), + (KeyCode::Char('d'), KeyModifiers::CONTROL) + ); + assert_eq!( + parse_chord("alt+left").unwrap(), + (KeyCode::Left, KeyModifiers::ALT) + ); + assert_eq!( + parse_chord("Ctrl+Alt+x").unwrap(), + ( + KeyCode::Char('x'), + KeyModifiers::CONTROL | KeyModifiers::ALT + ) + ); + } + + #[test] + fn parse_named_keys() { + assert_eq!( + parse_chord("esc").unwrap(), + (KeyCode::Esc, KeyModifiers::NONE) + ); + assert_eq!( + parse_chord("enter").unwrap(), + (KeyCode::Enter, KeyModifiers::NONE) + ); + assert_eq!( + parse_chord("tab").unwrap(), + (KeyCode::Tab, KeyModifiers::NONE) + ); + assert_eq!( + parse_chord("backtab").unwrap(), + (KeyCode::BackTab, KeyModifiers::NONE) + ); + assert_eq!( + parse_chord("space").unwrap(), + (KeyCode::Char(' '), KeyModifiers::NONE) + ); + assert_eq!( + parse_chord("f5").unwrap(), + (KeyCode::F(5), KeyModifiers::NONE) + ); + } + + #[test] + fn shift_normalization() { + // shift+tab → BackTab + assert_eq!( + parse_chord("shift+tab").unwrap(), + (KeyCode::BackTab, KeyModifiers::NONE) + ); + // shift+g → G + assert_eq!( + parse_chord("shift+g").unwrap(), + (KeyCode::Char('G'), KeyModifiers::NONE) + ); + // shift modifier dropped from named keys; left over because crossterm reports it. + assert_eq!( + parse_chord("shift+left").unwrap(), + (KeyCode::Left, KeyModifiers::NONE) + ); + } + + #[test] + fn rejects_garbage() { + assert!(parse_chord("").is_err()); + assert!(parse_chord("ctrl+").is_err()); + assert!(parse_chord("unknown+x").is_err()); + assert!(parse_chord("f99").is_err()); + } + + #[test] + fn action_names_round_trip_through_defaults() { + // Every Action variant that appears in a default map should + // round-trip from name → enum, so a user can rebind anything + // we ship by default. + for map in [ + default_normal(), + default_yank(), + default_toc(), + default_help(), + default_dir(), + ] { + for action in map.values() { + let name = action_name(*action); + assert_eq!( + Action::from_name(name), + Some(*action), + "action {action:?} → {name:?} did not round-trip" + ); + } + } + } + + fn action_name(a: Action) -> &'static str { + // Mirror of `from_name` for the round-trip test only — + // intentionally local so a missing entry in either direction + // fails the test. + match a { + Action::Quit => "quit", + Action::OpenToc => "open_toc", + Action::OpenHelp => "open_help", + Action::OpenDir => "open_dir", + Action::ToggleLineNumbers => "toggle_line_numbers", + Action::ToggleShortcodes => "toggle_shortcodes", + Action::StartSearch => "start_search", + Action::SearchNext => "search_next", + Action::SearchPrev => "search_prev", + Action::LinkNext => "link_next", + Action::LinkPrev => "link_prev", + Action::ActivateLink => "activate_link", + Action::HistoryBack => "history_back", + Action::HistoryForward => "history_forward", + Action::CursorDown => "cursor_down", + Action::CursorUp => "cursor_up", + Action::CursorHalfPageDown => "cursor_half_page_down", + Action::CursorHalfPageUp => "cursor_half_page_up", + Action::CursorPageDown => "cursor_page_down", + Action::CursorPageUp => "cursor_page_up", + Action::CursorTop => "cursor_top", + Action::CursorBottom => "cursor_bottom", + Action::SectionNext => "section_next", + Action::SectionPrev => "section_prev", + Action::EnterYank => "enter_yank", + Action::YankCancel => "yank_cancel", + Action::YankExpand => "yank_expand", + Action::YankShrink => "yank_shrink", + Action::YankCopy => "yank_copy", + Action::TocClose => "toc_close", + Action::TocSelectNext => "toc_select_next", + Action::TocSelectPrev => "toc_select_prev", + Action::TocSelectTop => "toc_select_top", + Action::TocSelectBottom => "toc_select_bottom", + Action::TocConfirm => "toc_confirm", + Action::HelpClose => "help_close", + Action::DirClose => "dir_close", + Action::DirSelectNext => "dir_select_next", + Action::DirSelectPrev => "dir_select_prev", + Action::DirSelectTop => "dir_select_top", + Action::DirSelectBottom => "dir_select_bottom", + Action::DirActivate => "dir_activate", + Action::DirGoUp => "dir_go_up", + } + } +} diff --git a/src/cli/tui.rs b/src/cli/tui.rs index ce1e5e3..b0c3bdb 100644 --- a/src/cli/tui.rs +++ b/src/cli/tui.rs @@ -71,8 +71,11 @@ pub fn run(arg: Option<&Path>, emoji: bool) -> io::Result<()> { }) .ok(); + let loaded = keymap::load(); + ratatui::run(move |terminal| { let mut app = App::new(doc, title, source, input, emoji); + app.install_keymaps(loaded); if let Some(w) = watcher { app.attach_watcher(w, rx); } @@ -330,6 +333,32 @@ impl App { self.refresh_watch(); } + /// Replace the per-mode keymaps with the merged result from + /// `keymap::load`. Any warnings collected while parsing the user + /// config are funneled into the status bar so the user finds out + /// about a bad config without having to dig through logs. + fn install_keymaps(&mut self, loaded: keymap::LoadedKeymaps) { + self.keymap_normal = loaded.normal; + self.keymap_yank = loaded.yank; + self.keymap_toc = loaded.toc; + self.keymap_help = loaded.help; + self.keymap_dir = loaded.dir; + if !loaded.warnings.is_empty() { + let path = loaded + .config_path + .as_deref() + .map(|p| p.display().to_string()) + .unwrap_or_else(|| "config".into()); + let head = &loaded.warnings[0]; + let extra = loaded.warnings.len().saturating_sub(1); + self.status_message = Some(if extra == 0 { + format!("{path}: {head}") + } else { + format!("{path}: {head} (+{extra} more)") + }); + } + } + /// Re-target the filesystem watcher at `self.source`, replacing any /// prior watch. No-op when no watcher is attached, or when the active /// source is a URL (nothing on the local filesystem to watch).