bmrk 0.4.0

A fast TUI for directory navigation and bookmark management
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use anyhow::{Context, Result};
use crossterm::event::KeyCode;
use ratatui::style::Color;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

use crate::theme::ThemeConfig;

/// Appearance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppearanceConfig {
    /// Theme name (can be expanded later for preset themes)
    #[serde(default = "default_theme")]
    pub theme: String,

    /// Maximum filename length before middle-truncation (0 = disabled)
    #[serde(default = "default_max_name_length")]
    pub max_name_length: usize,

    /// Icon set for the tree: "unicode" (▼/▶) or "ascii" (v/>)
    #[serde(default = "default_icons")]
    pub icons: String,

    /// Show the full path of the currently selected (cursor) item in the header, instead of
    /// just the tree root's path. Applies in Tree Navigation Mode and Quick Jump Mode alike.
    #[serde(default = "default_show_cursor_path")]
    pub show_cursor_path: bool,

    /// Custom theme colors
    #[serde(default)]
    pub colors: ThemeConfig,
}

impl Default for AppearanceConfig {
    fn default() -> Self {
        Self {
            theme: default_theme(),
            max_name_length: default_max_name_length(),
            icons: default_icons(),
            show_cursor_path: default_show_cursor_path(),
            colors: ThemeConfig::default(),
        }
    }
}

fn default_theme() -> String {
    "default".to_string()
}
fn default_max_name_length() -> usize {
    80
}
fn default_icons() -> String {
    "unicode".to_string()
}
fn default_show_cursor_path() -> bool {
    true
}

/// Behavior configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BehaviorConfig {
    /// Show hidden files (dotfiles)
    #[serde(default = "default_show_hidden")]
    pub show_hidden: bool,

    /// Follow symbolic links
    #[serde(default = "default_follow_symlinks")]
    pub follow_symlinks: bool,

    /// Double-click timeout in milliseconds
    #[serde(default = "default_double_click_timeout")]
    pub double_click_timeout_ms: u64,

    /// Number of lines to scroll with mouse wheel
    #[serde(default = "default_mouse_scroll_lines")]
    pub mouse_scroll_lines: usize,
}

impl Default for BehaviorConfig {
    fn default() -> Self {
        Self {
            show_hidden: default_show_hidden(),
            follow_symlinks: default_follow_symlinks(),
            double_click_timeout_ms: default_double_click_timeout(),
            mouse_scroll_lines: default_mouse_scroll_lines(),
        }
    }
}

fn default_show_hidden() -> bool {
    true
}
fn default_follow_symlinks() -> bool {
    true
}
fn default_double_click_timeout() -> u64 {
    800
}
fn default_mouse_scroll_lines() -> usize {
    1
}

/// Background directory index configuration (`.debug/BDP.md` Part 3). Both `Tab` (quick jump)
/// and `/` (search) consult this index as a fast synchronous lookup before falling back to a
/// live disk scan.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexConfig {
    /// Whether the background directory index is built/used at all
    #[serde(default = "default_index_enabled")]
    pub enabled: bool,

    /// Rebuild the index if it's older than this many hours
    #[serde(default = "default_index_refresh_hours")]
    pub refresh_hours: u64,

    /// Root directories to index (defaults to the user's home directory)
    #[serde(default = "default_index_roots")]
    pub roots: Vec<PathBuf>,

    /// Directory basenames to skip entirely while building the index. Setting this in
    /// `config.toml` **replaces** the default list rather than extending it — copy the default
    /// list into your config first if you only want to add one more name.
    #[serde(default = "default_index_ignore_dirs")]
    pub ignore_dirs: Vec<String>,
}

impl Default for IndexConfig {
    fn default() -> Self {
        Self {
            enabled: default_index_enabled(),
            refresh_hours: default_index_refresh_hours(),
            roots: default_index_roots(),
            ignore_dirs: default_index_ignore_dirs(),
        }
    }
}

fn default_index_enabled() -> bool {
    true
}
fn default_index_refresh_hours() -> u64 {
    24
}
fn default_index_roots() -> Vec<PathBuf> {
    dirs::home_dir().map(|h| vec![h]).unwrap_or_default()
}
fn default_index_ignore_dirs() -> Vec<String> {
    [
        ".git",
        "node_modules",
        "target",
        ".cache",
        ".cargo",
        ".rustup",
        "__pycache__",
        ".venv",
        "venv",
        ".tox",
        "dist",
        "build",
        ".next",
        ".gradle",
        ".m2",
    ]
    .into_iter()
    .map(String::from)
    .collect()
}

/// Keybindings configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeybindingsConfig {
    /// Keys to enter search mode
    #[serde(default = "default_search_keys")]
    pub search: Vec<String>,

    /// Keys to create bookmark
    #[serde(default = "default_create_bookmark_keys")]
    pub create_bookmark: Vec<String>,

    /// Keys to select bookmark
    #[serde(default = "default_select_bookmark_keys")]
    pub select_bookmark: Vec<String>,

    /// Keys to open disk selection panel
    #[serde(default = "default_select_disk_keys")]
    pub select_disk: Vec<String>,

    /// Keys to go to parent directory (change root up one level)
    #[serde(default = "default_go_to_parent_keys")]
    pub go_to_parent: Vec<String>,

    /// Keys to copy the selected item's full path to the system clipboard
    #[serde(default = "default_copy_path_keys")]
    pub copy_path: Vec<String>,

    /// Keys to go back (undo last navigation)
    #[serde(default = "default_go_back_keys")]
    pub go_back: Vec<String>,

    /// Keys to quit and output the selected path (navigate the shell)
    #[serde(default = "default_quit_keys")]
    pub quit: Vec<String>,

    /// Keys to exit without output (cancel)
    #[serde(default = "default_exit_keys")]
    pub exit: Vec<String>,
}

impl Default for KeybindingsConfig {
    fn default() -> Self {
        Self {
            search: default_search_keys(),
            create_bookmark: default_create_bookmark_keys(),
            select_bookmark: default_select_bookmark_keys(),
            select_disk: default_select_disk_keys(),
            go_to_parent: default_go_to_parent_keys(),
            copy_path: default_copy_path_keys(),
            go_back: default_go_back_keys(),
            quit: default_quit_keys(),
            exit: default_exit_keys(),
        }
    }
}

fn default_search_keys() -> Vec<String> {
    vec!["/".to_string()]
}
fn default_create_bookmark_keys() -> Vec<String> {
    vec!["m".to_string()]
}
fn default_select_bookmark_keys() -> Vec<String> {
    vec!["'".to_string()]
}
fn default_select_disk_keys() -> Vec<String> {
    vec!["d".to_string()]
}
fn default_go_to_parent_keys() -> Vec<String> {
    vec!["u".to_string()]
}
fn default_copy_path_keys() -> Vec<String> {
    vec!["c".to_string()]
}
fn default_go_back_keys() -> Vec<String> {
    vec!["Backspace".to_string()]
}
fn default_quit_keys() -> Vec<String> {
    vec!["q".to_string()]
}
fn default_exit_keys() -> Vec<String> {
    vec!["Esc".to_string()]
}

impl KeybindingsConfig {
    fn matches_key(&self, key: KeyCode, configured_keys: &[String]) -> bool {
        let key_str = match key {
            KeyCode::Char(c) => c.to_string(),
            KeyCode::Esc => "Esc".to_string(),
            KeyCode::Enter => "Enter".to_string(),
            KeyCode::Backspace => "Backspace".to_string(),
            KeyCode::Left => "Left".to_string(),
            KeyCode::Right => "Right".to_string(),
            KeyCode::Up => "Up".to_string(),
            KeyCode::Down => "Down".to_string(),
            KeyCode::Tab => "Tab".to_string(),
            KeyCode::Delete => "Delete".to_string(),
            KeyCode::Home => "Home".to_string(),
            KeyCode::End => "End".to_string(),
            KeyCode::PageUp => "PageUp".to_string(),
            KeyCode::PageDown => "PageDown".to_string(),
            _ => return false,
        };
        configured_keys
            .iter()
            .any(|k| k.eq_ignore_ascii_case(&key_str))
    }

    pub fn is_search(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.search)
    }

    pub fn is_create_bookmark(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.create_bookmark)
    }

    pub fn is_select_bookmark(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.select_bookmark)
    }

    pub fn is_select_disk(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.select_disk)
    }

    /// Returns true if `key` is bound to "go to parent directory".
    pub fn is_go_to_parent(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.go_to_parent)
    }

    /// Returns true if `key` is bound to "copy path" (copy the selected item's path to the
    /// clipboard).
    pub fn is_copy_path(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.copy_path)
    }

    /// Returns true if `key` is bound to "go back" (undo last navigation).
    pub fn is_go_back(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.go_back)
    }

    /// Returns true if `key` is bound to "quit" (exit and output selected path).
    pub fn is_quit(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.quit)
    }

    /// Returns true if `key` is bound to "exit" (cancel/quit without output).
    pub fn is_exit(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.exit)
    }
}

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
    #[serde(default)]
    pub appearance: AppearanceConfig,

    #[serde(default)]
    pub behavior: BehaviorConfig,

    #[serde(default)]
    pub keybindings: KeybindingsConfig,

    #[serde(default)]
    pub index: IndexConfig,
}

impl Config {
    /// Parse a color string to ratatui Color
    pub fn parse_color(color_str: &str) -> Color {
        ThemeConfig::parse_color(color_str)
    }

    /// Get a color value (guaranteed to be Some after load())
    pub fn get_color(opt: &Option<String>) -> &str {
        opt.as_ref()
            .expect("Color should be resolved after config load")
    }

    /// Parse TOML content into a `Config`, also returning the dotted-path names of any keys
    /// present in `content` but not recognized by any `Config` field (e.g. left over after a
    /// rename/removal in an update). Such keys are ignored by TOML deserialization rather than
    /// causing an error — this just reports which ones, so callers can warn about them.
    fn parse_with_unknown_keys(content: &str) -> Result<(Self, Vec<String>), toml::de::Error> {
        let de = toml::Deserializer::new(content);
        let mut unknown_keys = Vec::new();
        let config: Config = serde_ignored::deserialize(de, |path| {
            unknown_keys.push(path.to_string());
        })?;
        Ok((config, unknown_keys))
    }

    /// Load configuration from a file.
    ///
    /// Unrecognized keys (see [`Self::parse_with_unknown_keys`]) don't fail the load, but a
    /// one-time warning naming them is printed to stderr so the change doesn't pass silently.
    pub fn from_file(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {}", path.display()))?;

        let (config, unknown_keys) = Self::parse_with_unknown_keys(&content)
            .with_context(|| format!("Failed to parse config file: {}", path.display()))?;

        if !unknown_keys.is_empty() {
            eprintln!(
                "Note: {} not recognized in {} (ignored): {}",
                if unknown_keys.len() == 1 {
                    "key"
                } else {
                    "keys"
                },
                path.display(),
                unknown_keys.join(", ")
            );
            eprintln!("      See CHANGELOG.md for renamed or removed config options.");
        }

        Ok(config)
    }

    /// Get the global config file path
    /// Unix: ~/.config/bmrk/config.toml
    /// Windows: %APPDATA%\bmrk\config.toml
    pub fn global_config_path() -> Option<PathBuf> {
        dirs::config_dir().map(|p| p.join("bmrk").join("config.toml"))
    }

    /// Load configuration with fallback to defaults.
    /// If config file doesn't exist, it will be created automatically.
    /// If config file has parse errors, returns an error with details.
    pub fn load() -> anyhow::Result<Self> {
        let mut config = Config::default();

        if let Some(global_path) = Self::global_config_path() {
            if !global_path.exists() {
                let _ = Self::create_default_file(&global_path);
            }

            if global_path.exists() {
                match Self::from_file(&global_path) {
                    Ok(global_config) => {
                        config = global_config;
                    }
                    Err(e) => {
                        anyhow::bail!(
                            "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\
                            Configuration file error!\n\
                            ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\
                            \n\
                            Config file: {}\n\
                            \n\
                            Error details:\n\
                            {:#}\n\
                            \n\
                            To fix:\n\
                              1. Edit the config file and fix the syntax error\n\
                              2. Or delete the file - it will be recreated with defaults\n\
                            \n\
                            ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
                            global_path.display(),
                            e
                        );
                    }
                }
            }
        }

        // Resolve color values from preset theme + fallbacks
        let preset = ThemeConfig::get_preset_theme(&config.appearance.theme);
        let fallback = ThemeConfig::fallback_colors();

        macro_rules! resolve_color {
            ($field:ident) => {
                config.appearance.colors.$field = config
                    .appearance
                    .colors
                    .$field
                    .or_else(|| preset.as_ref().and_then(|p| p.$field.clone()))
                    .or_else(|| fallback.$field.clone());
            };
        }

        resolve_color!(selected_color);
        resolve_color!(directory_color);
        resolve_color!(file_color);
        resolve_color!(error_color);
        resolve_color!(highlight_color);
        resolve_color!(cursor_color);
        resolve_color!(tree_cursor_color);
        resolve_color!(tree_cursor_bg_color);
        resolve_color!(header_path_color);
        resolve_color!(header_hints_color);

        Ok(config)
    }

    /// Create a default config file with comments
    pub fn create_default_file(path: &Path) -> Result<()> {
        let default_config = r#"# bmrk configuration file
# This file uses TOML format: https://toml.io

[appearance]
# Theme name - preset color schemes
# Available themes:
#   "default"    - Classic terminal colors (blue dirs, cyan selection)
#   "gruvbox"    - Warm, high contrast theme inspired by Gruvbox
#   "nord"       - Cold, muted colors inspired by Nord theme
#   "tokyonight" - Modern dark theme with vibrant colors
#   "dracula"    - Popular dark theme with high contrast
#   "obsidian"   - Dark theme inspired by Obsidian app with subtle cursor
theme = "default"

# Maximum filename length in the tree before middle-truncation
# Example (with max_name_length = 20): "very_long_project_name.rs" -> "very_long..._name.rs"
# Set to 0 to disable truncation
max_name_length = 80

# Icon set used for the directory tree
# "unicode" - filled triangles: ▼ (expanded)  ▶ (collapsed)
# "ascii"   - plain characters: v (expanded)  > (collapsed)
icons = "unicode"

# Show the full path of the currently selected item in the header (instead of just the tree
# root's path). Applies in Tree Navigation Mode and Quick Jump Mode alike.
show_cursor_path = true

# Custom theme colors (override preset theme)
[appearance.colors]
# Color formats: name (red, blue...), #RRGGBB hex, 0-255 indexed
#
# selected_color = "cyan"
# directory_color = "gray"
# file_color = "white"
# error_color = "gray"
# highlight_color = "yellow"
# cursor_color = "yellow"
# tree_cursor_color = "dim"
# tree_cursor_bg_color = "dim"
# header_path_color = "cyan"
# header_hints_color = "darkgray"

[behavior]
# Show hidden files (dotfiles)
show_hidden = true

# Follow symbolic links
follow_symlinks = true

# Double-click timeout in milliseconds
double_click_timeout_ms = 800

# Number of lines to scroll with mouse wheel
mouse_scroll_lines = 1

[keybindings]
# Key bindings — each entry is a list; multiple keys can trigger the same action.
# Supported key names: letters (a-z), symbols, Esc, Enter, Backspace, Tab,
#   Up, Down, Left, Right, Home, End, PageUp, PageDown, Delete
search = ["/"]
create_bookmark = ["m"]
select_bookmark = ["'"]
select_disk = ["d"]
go_to_parent = ["u"]
copy_path = ["c"]
go_back = ["Backspace"]
quit = ["q"]
exit = ["Esc"]

[index]
# Background directory index — both Tab (quick jump) and / (search) consult this index as a
# fast synchronous lookup before falling back to a live disk scan of the current directory.
# Whether the index is built/used at all
# enabled = true

# Rebuild the index if it's older than this many hours
# refresh_hours = 24

# Root directories to index (defaults to the user's home directory)
# roots = ["/home/username"]

# Directory basenames to skip entirely while building the index.
# Setting this replaces the default list below rather than extending it.
# ignore_dirs = [".git", "node_modules", "target", ".cache", ".cargo", ".rustup",
#   "__pycache__", ".venv", "venv", ".tox", "dist", "build", ".next", ".gradle", ".m2"]
"#;

        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).with_context(|| {
                format!("Failed to create config directory: {}", parent.display())
            })?;
        }

        fs::write(path, default_config)
            .with_context(|| format!("Failed to write config file: {}", path.display()))?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.appearance.max_name_length, 80);
        assert!(config.behavior.show_hidden);
        assert!(config.index.enabled);
        assert_eq!(config.index.refresh_hours, 24);
        assert!(config
            .index
            .ignore_dirs
            .contains(&"node_modules".to_string()));
        assert!(config.appearance.show_cursor_path);
    }

    #[test]
    fn test_create_default_file_output_parses_back() {
        let tmp = std::env::temp_dir().join("bmrk_test_create_default_file");
        let path = tmp.join("config.toml");
        std::fs::create_dir_all(&tmp).unwrap();

        Config::create_default_file(&path).unwrap();
        let loaded = Config::from_file(&path).unwrap();

        // Everything under [index] is commented out in the generated file, so parsing must
        // fall back to the same defaults as `IndexConfig::default()`.
        assert_eq!(loaded.index.enabled, default_index_enabled());
        assert_eq!(loaded.index.refresh_hours, default_index_refresh_hours());
        assert_eq!(loaded.index.roots, default_index_roots());
        assert_eq!(loaded.index.ignore_dirs, default_index_ignore_dirs());
        assert!(loaded.appearance.show_cursor_path);

        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn test_unknown_key_detected_but_does_not_fail_parsing() {
        let toml_str = r#"
[appearance]
theme = "default"
old_removed_option = true

[behavior]
show_hidden = false
"#;
        let (config, unknown_keys) = Config::parse_with_unknown_keys(toml_str).unwrap();

        assert_eq!(unknown_keys, vec!["appearance.old_removed_option"]);
        // Known keys are still applied, and unknown ones don't stop the rest from loading.
        assert!(!config.behavior.show_hidden);
    }

    #[test]
    fn test_default_file_has_no_unknown_keys() {
        let tmp = std::env::temp_dir().join("bmrk_test_no_unknown_keys");
        let path = tmp.join("config.toml");
        std::fs::create_dir_all(&tmp).unwrap();

        Config::create_default_file(&path).unwrap();
        let content = std::fs::read_to_string(&path).unwrap();
        let (_, unknown_keys) = Config::parse_with_unknown_keys(&content).unwrap();

        assert!(
            unknown_keys.is_empty(),
            "default config file should not contain any unrecognized keys: {:?}",
            unknown_keys
        );

        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn test_color_parsing() {
        assert!(matches!(ThemeConfig::parse_color("red"), Color::Red));
        assert!(matches!(ThemeConfig::parse_color("blue"), Color::Blue));
        assert!(matches!(
            ThemeConfig::parse_color("#FF0000"),
            Color::Rgb(255, 0, 0)
        ));
    }
}