oxur-cli 0.2.1

CLI infrastructure and unified command-line tool for Oxur
Documentation
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! Terminal interface for REPL interaction
//!
//! Provides line editing, command history, and terminal handling
//! using reedline.

use crate::config::{paths, EditMode, HistoryConfig, TerminalConfig};
use anyhow::{Context, Result};
use crossterm::{execute, terminal};
use reedline::{
    default_emacs_keybindings, default_vi_insert_keybindings, default_vi_normal_keybindings,
    ColumnarMenu, Emacs, FileBackedHistory, KeyCode, KeyModifiers, Keybindings, MenuBuilder,
    Reedline, ReedlineEvent, ReedlineMenu, Signal, Vi,
};
use std::io;
use std::path::PathBuf;

use crate::repl::completer::OxurCompleter;
use crate::repl::oxur_prompt::OxurPrompt;
use crate::repl::pager;
use crate::repl::sexp_highlighter::SExpHighlighter;
use crate::repl::sexp_validator::SExpValidator;

/// Extract version info from version string (without tool name)
///
/// Converts "rustc 1.75.0 (hash)" to "1.75.0 (hash)", or "cargo 1.75.0 (date)" to "1.75.0 (date)"
/// Keeps the full version string but removes the tool name prefix.
fn format_version(version_str: &str) -> String {
    // Split by whitespace and skip the first element (tool name)
    // e.g., "rustc 1.75.0 (82e1608df 2023-12-21)" -> "1.75.0 (82e1608df 2023-12-21)"
    let parts: Vec<&str> = version_str.split_whitespace().collect();
    if parts.len() > 1 {
        parts[1..].join(" ")
    } else {
        version_str.to_string()
    }
}

/// Calculate the visible width of a string, ignoring ANSI escape codes
///
/// This strips all ANSI escape sequences to get the actual displayed width.
fn visible_width(s: &str) -> usize {
    // Regular expression to match ANSI escape codes: ESC [ ... m
    // Also matches true color codes like ESC[38;2;r;g;bm
    let mut width = 0;
    let mut chars = s.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '\x1b' {
            // Skip the escape sequence
            if chars.peek() == Some(&'[') {
                chars.next(); // consume '['
                              // Skip until we find 'm'
                for esc_ch in chars.by_ref() {
                    if esc_ch == 'm' {
                        break;
                    }
                }
            }
        } else {
            // Count regular character
            width += 1;
        }
    }

    width
}

/// Substitute a placeholder in a line while preserving visual width
///
/// This replaces the placeholder with the actual value and adjusts padding
/// to maintain the same visual column width (accounting for ANSI codes).
fn substitute_placeholder_in_line(line: &str, placeholder: &str, value: &str) -> String {
    if !line.contains(placeholder) {
        return line.to_string();
    }

    // Calculate the original visible width
    let original_visible_width = visible_width(line);

    // Do the replacement
    let result = line.replace(placeholder, value);

    // Calculate new visible width after replacement
    let new_visible_width = visible_width(&result);

    if new_visible_width == original_visible_width {
        // Perfect match, no adjustment needed
        return result;
    }

    // Find the position where we'll adjust spacing
    // Strategy: Look for common border characters (â•‘, |, ]) or last ANSI escape sequence
    let border_pos = result
        .rfind('\x1b')
        .or_else(|| result.rfind('â•‘'))
        .or_else(|| result.rfind('│'))
        .or_else(|| result.rfind('|'))
        .or_else(|| result.rfind(']'));

    let (before_border, border_and_after) = if let Some(pos) = border_pos {
        (&result[..pos], &result[pos..])
    } else {
        // No border found - work with entire string
        (&result[..], "")
    };

    if new_visible_width < original_visible_width {
        // Need to add spaces
        let spaces_needed = original_visible_width - new_visible_width;
        format!("{}{}{}", before_border, " ".repeat(spaces_needed), border_and_after)
    } else {
        // Need to remove spaces (new_visible_width > original_visible_width)
        let spaces_to_remove = new_visible_width - original_visible_width;

        // Count trailing spaces in before_border
        let trimmed = before_border.trim_end();
        let trailing_space_count = before_border.len() - trimmed.len();

        if trailing_space_count >= spaces_to_remove {
            // We have enough spaces to remove
            let keep_len = trimmed.len() + (trailing_space_count - spaces_to_remove);
            format!("{}{}", &before_border[..keep_len], border_and_after)
        } else {
            // Not enough trailing spaces - just remove what we have
            format!("{}{}", trimmed, border_and_after)
        }
    }
}

/// Substitute version placeholders in banner text
///
/// Replaces template placeholders with actual version information while
/// preserving the visual column alignment of borders and decorative elements.
///
/// - `N.N.N` → Oxur version (e.g., "0.1.0")
/// - `M.M.M` → Rust version info (e.g., "1.75.0 (82e1608df 2023-12-21)")
/// - `L.L.L` → Cargo version info (e.g., "1.75.0 (1d8b05cdd 2023-11-20)")
fn substitute_banner_versions(
    banner: &str,
    metadata: &oxur_repl::metadata::SystemMetadata,
) -> String {
    banner
        .lines()
        .map(|line| {
            let line = substitute_placeholder_in_line(line, "N.N.N", &metadata.oxur_version);
            let line = substitute_placeholder_in_line(
                &line,
                "M.M.M",
                &format_version(&metadata.rust_version),
            );
            substitute_placeholder_in_line(&line, "L.L.L", &format_version(&metadata.cargo_version))
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Add Tab keybinding for completion menu
fn add_completion_keybinding(keybindings: &mut Keybindings) {
    keybindings.add_binding(
        KeyModifiers::NONE,
        KeyCode::Tab,
        ReedlineEvent::UntilFound(vec![
            ReedlineEvent::Menu("completion_menu".to_string()),
            ReedlineEvent::MenuNext,
        ]),
    );
}

/// REPL terminal interface with line editing and history
pub struct ReplTerminal {
    editor: Reedline,
    #[allow(dead_code)] // Kept for API compatibility and future use
    history_path: PathBuf,
    terminal_config: TerminalConfig,
}

impl ReplTerminal {
    /// Create a new REPL terminal with configuration
    ///
    /// # Arguments
    ///
    /// * `terminal_config` - Terminal appearance configuration
    /// * `history_config` - Command history configuration
    ///
    /// # Errors
    ///
    /// Returns error if reedline initialization fails.
    pub fn with_config(
        terminal_config: TerminalConfig,
        history_config: HistoryConfig,
    ) -> Result<Self> {
        // Convert edit mode to reedline's EditMode trait object with Tab completion
        let edit_mode: Box<dyn reedline::EditMode> = match terminal_config.edit_mode {
            EditMode::Emacs => {
                let mut keybindings = default_emacs_keybindings();
                add_completion_keybinding(&mut keybindings);
                Box::new(Emacs::new(keybindings))
            }
            EditMode::Vi => {
                let mut insert_keybindings = default_vi_insert_keybindings();
                let mut normal_keybindings = default_vi_normal_keybindings();
                add_completion_keybinding(&mut insert_keybindings);
                add_completion_keybinding(&mut normal_keybindings);
                Box::new(Vi::new(insert_keybindings, normal_keybindings))
            }
        };

        // Determine history file path
        let history_path = history_config.path.unwrap_or_else(paths::default_history_path);

        // Create history backend
        // Note: FileBackedHistory is used for both enabled and disabled cases.
        // When disabled, we use a temp path that won't persist between sessions.
        let history_path_for_backend = if history_config.enabled {
            history_path.clone()
        } else {
            // Use a temporary path that won't be loaded or saved
            std::env::temp_dir().join("oxur-repl-temp-history")
        };

        let history = Box::new(
            FileBackedHistory::with_file(
                history_config.max_size.unwrap_or(10000),
                history_path_for_backend,
            )
            .context("Failed to create history backend")?,
        );

        // Create completion menu
        let completion_menu = ColumnarMenu::default()
            .with_name("completion_menu")
            .with_columns(4)
            .with_column_width(Some(20))
            .with_column_padding(2);

        // Build reedline editor with syntax highlighting, validation, and completion
        let editor = Reedline::create()
            .with_history(history)
            .with_edit_mode(edit_mode)
            .with_highlighter(Box::new(SExpHighlighter::new(terminal_config.color_enabled)))
            .with_validator(Box::new(SExpValidator::new()))
            .with_completer(Box::new(OxurCompleter::new()))
            .with_menu(ReedlineMenu::EngineCompleter(Box::new(completion_menu)));

        Ok(Self { editor, history_path, terminal_config })
    }

    /// Read a line of input from the user
    ///
    /// Returns:
    /// - `Ok(Some(line))` - User entered a line
    /// - `Ok(None)` - User pressed Ctrl-C (interrupt)
    /// - `Err(_)` - User pressed Ctrl-D (exit) or other error
    pub fn read_line(&mut self, prompt: &str) -> Result<Option<String>> {
        let oxur_prompt = OxurPrompt::new(
            prompt.to_string(),
            self.terminal_config.formatted_continuation_prompt(),
        );

        match self.editor.read_line(&oxur_prompt) {
            Ok(Signal::Success(line)) => Ok(Some(line)),
            Ok(Signal::CtrlC) => Ok(None),
            Ok(Signal::CtrlD) => Err(anyhow::anyhow!("EOF")),
            Err(e) => Err(anyhow::anyhow!("Input error: {}", e)),
        }
    }

    /// Read a line using the default prompt
    pub fn read_line_default(&mut self) -> Result<Option<String>> {
        let prompt = self.prompt();
        self.read_line(&prompt)
    }

    /// Get the formatted prompt string
    pub fn prompt(&self) -> String {
        self.terminal_config.formatted_prompt()
    }

    /// Get the formatted continuation prompt for multi-line input
    #[allow(dead_code)]
    pub fn continuation_prompt(&self) -> String {
        self.terminal_config.formatted_continuation_prompt()
    }

    /// Save command history to disk
    ///
    /// With FileBackedHistory, history is automatically saved.
    /// This method is retained for API compatibility.
    pub fn save_history(&mut self) -> Result<()> {
        // FileBackedHistory auto-saves - this is a no-op
        Ok(())
    }

    /// Check if colors are enabled
    #[allow(dead_code)]
    pub fn color_enabled(&self) -> bool {
        self.terminal_config.color_enabled
    }

    /// Print an error message with appropriate formatting
    pub fn print_error(&self, msg: &str) {
        if self.terminal_config.color_enabled {
            eprintln!("\x1b[31mError:\x1b[0m {}", msg);
        } else {
            eprintln!("Error: {}", msg);
        }
    }

    /// Print a result value with appropriate formatting
    pub fn print_result(&self, value: &str) {
        if self.terminal_config.color_enabled {
            println!("\x1b[36m{}\x1b[0m", value);
        } else {
            println!("{}", value);
        }
    }

    /// Print output (stdout from evaluation)
    pub fn print_output(&self, output: &str) {
        print!("{}", output);
    }

    /// Print help content with appropriate formatting
    ///
    /// Automatically pages content if it exceeds terminal height.
    pub fn print_help(&self, content: &str) {
        if let Err(e) = pager::page_text(content) {
            // Fallback to direct print if paging fails
            eprintln!("Warning: Pager failed ({}), printing directly", e);
            println!("{}", content);
        }
    }

    /// Print the welcome banner with system metadata
    pub fn print_banner(&self, metadata: &oxur_repl::metadata::SystemMetadata) {
        if let Some(ref banner) = self.terminal_config.banner {
            // Custom banner with version substitution
            let banner_with_versions = substitute_banner_versions(banner, metadata);
            println!("{}", banner_with_versions);
        } else {
            // Default banner with version information
            if self.terminal_config.color_enabled {
                println!(
                    "\x1b[1mOxur REPL\x1b[0m v{} | \x1b[90mRust: {} | Cargo: {}\x1b[0m",
                    metadata.oxur_version,
                    format_version(&metadata.rust_version),
                    format_version(&metadata.cargo_version)
                );
            } else {
                println!(
                    "Oxur REPL v{} | Rust: {} | Cargo: {}",
                    metadata.oxur_version,
                    format_version(&metadata.rust_version),
                    format_version(&metadata.cargo_version)
                );
            }
            println!("Type (help) for assistance, Ctrl-D to exit.");
        }
        println!();
    }

    /// Print a goodbye message
    pub fn print_goodbye(&self) {
        println!();
        if self.terminal_config.color_enabled {
            println!("\x1b[33mGoodbye!\x1b[0m");
        } else {
            println!("Goodbye!");
        }
    }

    /// Clear the terminal screen and move cursor to top
    pub fn clear_screen(&self) -> Result<()> {
        execute!(io::stdout(), terminal::Clear(terminal::ClearType::All))?;
        execute!(io::stdout(), crossterm::cursor::MoveTo(0, 0))?;
        Ok(())
    }

    /// Get the terminal configuration
    pub fn config(&self) -> &TerminalConfig {
        &self.terminal_config
    }
}

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

    #[test]
    fn test_default_history_path() {
        let path = paths::default_history_path();
        assert!(path.ends_with("repl_history"));
    }

    #[test]
    fn test_terminal_config_prompt() {
        let config = TerminalConfig::builder().prompt("test> ").color(false).build();
        assert_eq!(config.formatted_prompt(), "test> ");
    }

    #[test]
    #[serial_test::serial]
    fn test_terminal_config_colored_prompt() {
        // Force colors on for testing
        colored::control::set_override(true);

        // Non-oxur prompt uses standard green
        let config = TerminalConfig::builder().prompt("test> ").color(true).build();
        let test_prompt = config.formatted_prompt();
        assert_ne!(test_prompt, "test> ");
        assert!(test_prompt.contains("\x1b["));
        assert!(test_prompt.contains("test> "));

        // oxur prompt uses special coloring (bright yellow, yellow, bright red, dark red, bright green)
        let oxur_config = TerminalConfig::builder().prompt("oxur> ").color(true).build();
        let oxur_prompt = oxur_config.formatted_prompt();
        // Colored output should be different from plain text
        assert_ne!(oxur_prompt, "oxur> ");
        // Should contain ANSI escape codes
        assert!(oxur_prompt.contains("\x1b["));
        // Should contain all letters
        assert!(oxur_prompt.contains("o"));
        assert!(oxur_prompt.contains("x"));
        assert!(oxur_prompt.contains("u"));
        assert!(oxur_prompt.contains("r"));

        // Reset color override
        colored::control::unset_override();
    }

    #[test]
    fn test_continuation_prompt() {
        let config = TerminalConfig::builder().continuation_prompt("... ").color(false).build();
        assert_eq!(config.formatted_continuation_prompt(), "... ");
    }

    #[test]
    fn test_custom_banner() {
        let config = TerminalConfig::builder().banner("Custom Welcome!").build();
        assert_eq!(config.banner, Some("Custom Welcome!".to_string()));
    }

    #[test]
    fn test_format_version_rustc() {
        let version = "rustc 1.75.0 (82e1608df 2023-12-21)";
        assert_eq!(format_version(version), "1.75.0 (82e1608df 2023-12-21)");
    }

    #[test]
    fn test_format_version_cargo() {
        let version = "cargo 1.75.0 (1d8b05cdd 2023-11-20)";
        assert_eq!(format_version(version), "1.75.0 (1d8b05cdd 2023-11-20)");
    }

    #[test]
    fn test_format_version_unknown() {
        let version = "unknown";
        assert_eq!(format_version(version), "unknown");
    }

    #[test]
    fn test_visible_width_plain_text() {
        assert_eq!(visible_width("Hello"), 5);
        assert_eq!(visible_width(""), 0);
        assert_eq!(visible_width("Test 123"), 8);
    }

    #[test]
    fn test_visible_width_with_ansi_codes() {
        // Basic color codes
        assert_eq!(visible_width("\x1b[31mRed\x1b[0m"), 3); // "Red"
        assert_eq!(visible_width("\x1b[1;32mGreen\x1b[0m"), 5); // "Green"

        // True color codes (like in the banner)
        assert_eq!(visible_width("\x1b[38;2;255;0;0mRed\x1b[0m"), 3); // "Red"
        assert_eq!(visible_width("\x1b[38;2;138;59;13mâ•‘\x1b[0m"), 1); // "â•‘"
    }

    #[test]
    fn test_visible_width_complex_banner_line() {
        // Simplified version of actual banner line structure
        let line = "\x1b[38;2;138;59;13mâ•‘\x1b[0m text \x1b[38;2;138;59;13mâ•‘\x1b[0m";
        // Should count: â•‘ + " text " (6 chars) + â•‘ = 8
        assert_eq!(visible_width(line), 8);
    }

    #[test]
    fn test_substitute_placeholder_in_line_no_placeholder() {
        let line = "This is a test line";
        let result = substitute_placeholder_in_line(line, "N.N.N", "1.2.3");
        assert_eq!(result, line);
    }

    #[test]
    fn test_substitute_placeholder_in_line_simple() {
        let line = "Version: N.N.N    â•‘";
        let result = substitute_placeholder_in_line(line, "N.N.N", "1.2.3");
        assert_eq!(visible_width(&result), visible_width(line));
        assert!(result.contains("1.2.3"));
        assert!(!result.contains("N.N.N"));
    }

    #[test]
    fn test_substitute_placeholder_in_line_shorter_value() {
        let line = "oxur: N.N.N     â•‘";
        let result = substitute_placeholder_in_line(line, "N.N.N", "1.0");
        // "N.N.N" (5 chars) -> "1.0" (3 chars) = need to add 2 spaces
        assert_eq!(visible_width(&result), visible_width(line));
        assert!(result.contains("1.0"));
    }

    #[test]
    fn test_substitute_placeholder_in_line_longer_value() {
        let line = "oxur: N.N.N     â•‘";
        let result = substitute_placeholder_in_line(line, "N.N.N", "1.0.0-beta");
        // "N.N.N" (5 chars) -> "1.0.0-beta" (10 chars) = need to remove 5 spaces
        assert_eq!(visible_width(&result), visible_width(line));
        assert!(result.contains("1.0.0-beta"));
    }

    #[test]
    fn test_substitute_placeholder_in_line_with_ansi() {
        let line = "\x1b[32moxur: N.N.N\x1b[37m     \x1b[38;2;138;59;13mâ•‘\x1b[0m";
        let result = substitute_placeholder_in_line(line, "N.N.N", "1.2.3");
        // Visual width should remain the same
        assert_eq!(visible_width(&result), visible_width(line));
        assert!(result.contains("1.2.3"));
        assert!(!result.contains("N.N.N"));
    }

    #[test]
    fn test_substitute_banner_versions() {
        let banner = "oxur: N.N.N\nrustc: M.M.M\ncargo: L.L.L";
        let metadata = oxur_repl::metadata::SystemMetadata {
            oxur_version: "0.1.0".to_string(),
            rust_version: "rustc 1.75.0 (82e1608df 2023-12-21)".to_string(),
            cargo_version: "cargo 1.75.0 (1d8b05cdd 2023-11-20)".to_string(),
            os_name: "Test".to_string(),
            os_version: "1.0".to_string(),
            arch: "x86_64".to_string(),
            hostname: "test".to_string(),
            pid: 1234,
            cwd: std::path::PathBuf::from("/test"),
            started_at: std::time::SystemTime::now(),
        };

        let result = substitute_banner_versions(banner, &metadata);
        assert!(result.contains("oxur: 0.1.0"));
        assert!(result.contains("rustc: 1.75.0 (82e1608df 2023-12-21)"));
        assert!(result.contains("cargo: 1.75.0 (1d8b05cdd 2023-11-20)"));
        assert!(!result.contains("N.N.N"));
        assert!(!result.contains("M.M.M"));
        assert!(!result.contains("L.L.L"));
    }

    #[test]
    fn test_substitute_banner_versions_preserves_width() {
        // Test with lines that have borders at specific columns
        let banner = "â•‘ oxur: N.N.N     â•‘\nâ•‘ rustc: M.M.M    â•‘\nâ•‘ cargo: L.L.L    â•‘";
        let metadata = oxur_repl::metadata::SystemMetadata {
            oxur_version: "0.2.0".to_string(),
            rust_version: "rustc 1.76.0".to_string(),
            cargo_version: "cargo 1.76.0".to_string(),
            os_name: "Test".to_string(),
            os_version: "1.0".to_string(),
            arch: "x86_64".to_string(),
            hostname: "test".to_string(),
            pid: 1234,
            cwd: std::path::PathBuf::from("/test"),
            started_at: std::time::SystemTime::now(),
        };

        let result = substitute_banner_versions(banner, &metadata);
        let original_lines: Vec<&str> = banner.lines().collect();
        let result_lines: Vec<&str> = result.lines().collect();

        // Each line should maintain the same visible width
        assert_eq!(original_lines.len(), result_lines.len());
        for (orig, res) in original_lines.iter().zip(result_lines.iter()) {
            assert_eq!(
                visible_width(orig),
                visible_width(res),
                "Line width mismatch:\nOriginal: {}\nResult: {}",
                orig,
                res
            );
        }
    }

    #[test]
    fn test_substitute_banner_versions_with_real_banner() {
        // Test with the actual default banner to ensure it works in practice
        let config = crate::config::TerminalConfig::default();
        let banner = config.banner.expect("Default banner should exist");

        let metadata = oxur_repl::metadata::SystemMetadata {
            oxur_version: "0.2.0".to_string(),
            rust_version: "rustc 1.76.0 (07dca489a 2024-02-04)".to_string(),
            cargo_version: "cargo 1.76.0 (c84b36747 2024-01-18)".to_string(),
            os_name: "Test".to_string(),
            os_version: "1.0".to_string(),
            arch: "x86_64".to_string(),
            hostname: "test".to_string(),
            pid: 1234,
            cwd: std::path::PathBuf::from("/test"),
            started_at: std::time::SystemTime::now(),
        };

        let result = substitute_banner_versions(&banner, &metadata);
        let original_lines: Vec<&str> = banner.lines().collect();
        let result_lines: Vec<&str> = result.lines().collect();

        // Check that line count matches
        assert_eq!(original_lines.len(), result_lines.len());

        // Check that version lines maintain their width
        for (i, (orig, res)) in original_lines.iter().zip(result_lines.iter()).enumerate() {
            let orig_width = visible_width(orig);
            let res_width = visible_width(res);
            assert_eq!(
                orig_width,
                res_width,
                "Line {} width mismatch (orig={}, res={}):\nOriginal: {}\nResult: {}",
                i + 1,
                orig_width,
                res_width,
                orig,
                res
            );
        }

        // Verify substitutions happened
        assert!(result.contains("0.2.0"));
        assert!(result.contains("1.76.0"));
        assert!(!result.contains("N.N.N"));
        assert!(!result.contains("M.M.M"));
        assert!(!result.contains("L.L.L"));
    }

    // ===== Additional coverage tests =====

    #[test]
    fn test_format_version_empty() {
        let version = "";
        assert_eq!(format_version(version), "");
    }

    #[test]
    fn test_format_version_single_word() {
        let version = "1.75.0";
        assert_eq!(format_version(version), "1.75.0");
    }

    #[test]
    fn test_format_version_many_parts() {
        let version = "tool 1.0.0 extra info here";
        assert_eq!(format_version(version), "1.0.0 extra info here");
    }

    #[test]
    fn test_substitute_banner_no_placeholders() {
        let banner = "Welcome to the REPL!";
        let metadata = oxur_repl::metadata::SystemMetadata {
            oxur_version: "0.1.0".to_string(),
            rust_version: "rustc 1.75.0".to_string(),
            cargo_version: "cargo 1.75.0".to_string(),
            os_name: "Test".to_string(),
            os_version: "1.0".to_string(),
            arch: "x86_64".to_string(),
            hostname: "test".to_string(),
            pid: 1234,
            cwd: std::path::PathBuf::from("/test"),
            started_at: std::time::SystemTime::now(),
        };

        let result = substitute_banner_versions(banner, &metadata);
        assert_eq!(result, "Welcome to the REPL!");
    }

    #[test]
    fn test_substitute_banner_partial_placeholders() {
        let banner = "Oxur N.N.N only";
        let metadata = oxur_repl::metadata::SystemMetadata {
            oxur_version: "0.2.0".to_string(),
            rust_version: "rustc 1.76.0".to_string(),
            cargo_version: "cargo 1.76.0".to_string(),
            os_name: "Test".to_string(),
            os_version: "1.0".to_string(),
            arch: "x86_64".to_string(),
            hostname: "test".to_string(),
            pid: 1234,
            cwd: std::path::PathBuf::from("/test"),
            started_at: std::time::SystemTime::now(),
        };

        let result = substitute_banner_versions(banner, &metadata);
        assert_eq!(result, "Oxur 0.2.0 only");
    }

    #[test]
    fn test_add_completion_keybinding() {
        let mut keybindings = default_emacs_keybindings();
        // Should not panic
        add_completion_keybinding(&mut keybindings);
    }

    #[test]
    fn test_add_completion_keybinding_vi_insert() {
        let mut keybindings = default_vi_insert_keybindings();
        add_completion_keybinding(&mut keybindings);
    }

    #[test]
    fn test_add_completion_keybinding_vi_normal() {
        let mut keybindings = default_vi_normal_keybindings();
        add_completion_keybinding(&mut keybindings);
    }

    #[test]
    fn test_terminal_config_default_banner() {
        let config = TerminalConfig::default();
        // Default config has the DEFAULT_BANNER set
        assert!(config.banner.is_some());
    }

    #[test]
    fn test_terminal_config_color_disabled() {
        let config = TerminalConfig::builder().color(false).build();
        assert!(!config.color_enabled);
    }

    #[test]
    fn test_terminal_config_color_enabled() {
        let config = TerminalConfig::builder().color(true).build();
        assert!(config.color_enabled);
    }

    #[test]
    fn test_terminal_config_edit_mode_emacs() {
        let config = TerminalConfig::builder().edit_mode(EditMode::Emacs).build();
        assert!(matches!(config.edit_mode, EditMode::Emacs));
    }

    #[test]
    fn test_terminal_config_edit_mode_vi() {
        let config = TerminalConfig::builder().edit_mode(EditMode::Vi).build();
        assert!(matches!(config.edit_mode, EditMode::Vi));
    }

    #[test]
    fn test_history_config_default() {
        let config = HistoryConfig::default();
        assert!(config.enabled);
        assert!(config.path.is_none());
        // Default has max_size of 10000
        assert_eq!(config.max_size, Some(10000));
    }

    #[test]
    fn test_history_config_disabled() {
        let config = HistoryConfig { enabled: false, path: None, max_size: None };
        assert!(!config.enabled);
    }

    #[test]
    fn test_history_config_custom_path() {
        let path = PathBuf::from("/custom/history");
        let config = HistoryConfig { enabled: true, path: Some(path.clone()), max_size: None };
        assert_eq!(config.path, Some(path));
    }

    #[test]
    fn test_history_config_custom_max_size() {
        let config = HistoryConfig { enabled: true, path: None, max_size: Some(5000) };
        assert_eq!(config.max_size, Some(5000));
    }

    // Tests for ReplTerminal that don't require actual terminal interaction
    // These test the creation path and configuration access

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_with_config_emacs() {
        // Create with emacs mode - tests line 91-94
        let terminal_config =
            TerminalConfig::builder().edit_mode(EditMode::Emacs).color(false).build();
        let history_config = HistoryConfig { enabled: false, path: None, max_size: Some(100) };

        let result = ReplTerminal::with_config(terminal_config, history_config);
        assert!(result.is_ok());
        let terminal = result.unwrap();
        assert!(!terminal.config().color_enabled);
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_with_config_vi() {
        // Create with vi mode - tests line 96-102
        let terminal_config =
            TerminalConfig::builder().edit_mode(EditMode::Vi).color(false).build();
        let history_config = HistoryConfig { enabled: false, path: None, max_size: Some(100) };

        let result = ReplTerminal::with_config(terminal_config, history_config);
        assert!(result.is_ok());
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_with_history_enabled() {
        // Test with history enabled - tests line 111-112
        let terminal_config = TerminalConfig::builder().color(false).build();
        let temp_dir = std::env::temp_dir();
        let history_path = temp_dir.join("test-oxur-history");
        let history_config =
            HistoryConfig { enabled: true, path: Some(history_path.clone()), max_size: Some(500) };

        let result = ReplTerminal::with_config(terminal_config, history_config);
        assert!(result.is_ok());

        // Cleanup
        let _ = std::fs::remove_file(history_path);
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_with_history_disabled() {
        // Test with history disabled - tests line 114-116
        let terminal_config = TerminalConfig::builder().color(false).build();
        let history_config = HistoryConfig { enabled: false, path: None, max_size: None };

        let result = ReplTerminal::with_config(terminal_config, history_config);
        assert!(result.is_ok());
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_config_accessor() {
        let terminal_config = TerminalConfig::builder()
            .prompt("test> ")
            .continuation_prompt("..> ")
            .color(false)
            .build();
        let history_config = HistoryConfig::default();

        let terminal = ReplTerminal::with_config(terminal_config.clone(), history_config).unwrap();

        // Test config() accessor - line 277-279
        let config = terminal.config();
        assert_eq!(config.prompt, "test> ");
        assert_eq!(config.continuation_prompt, "..> ");
        assert!(!config.color_enabled);
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_prompt() {
        let terminal_config = TerminalConfig::builder().prompt("custom> ").color(false).build();
        let history_config = HistoryConfig::default();

        let terminal = ReplTerminal::with_config(terminal_config, history_config).unwrap();

        // Test prompt() method - line 172-174
        let prompt = terminal.prompt();
        assert_eq!(prompt, "custom> ");
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_continuation_prompt() {
        let terminal_config =
            TerminalConfig::builder().continuation_prompt(">>> ").color(false).build();
        let history_config = HistoryConfig::default();

        let terminal = ReplTerminal::with_config(terminal_config, history_config).unwrap();

        // Test continuation_prompt() method - line 178-180
        let cont_prompt = terminal.continuation_prompt();
        assert_eq!(cont_prompt, ">>> ");
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_color_enabled() {
        let terminal_config = TerminalConfig::builder().color(true).build();
        let history_config = HistoryConfig::default();

        let terminal = ReplTerminal::with_config(terminal_config, history_config).unwrap();

        // Test color_enabled() method - line 193-195
        assert!(terminal.color_enabled());
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_color_disabled() {
        let terminal_config = TerminalConfig::builder().color(false).build();
        let history_config = HistoryConfig::default();

        let terminal = ReplTerminal::with_config(terminal_config, history_config).unwrap();

        assert!(!terminal.color_enabled());
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_terminal_save_history() {
        let terminal_config = TerminalConfig::builder().color(false).build();
        let history_config = HistoryConfig::default();

        let mut terminal = ReplTerminal::with_config(terminal_config, history_config).unwrap();

        // Test save_history() method - line 186-189
        let result = terminal.save_history();
        assert!(result.is_ok());
    }
}