arf-console 0.4.3

A cross-platform R console written in Rust
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Meta command processing.

use crate::completion::path::expand_tilde;
use crate::config::RSourceStatus;
use crate::external::formatter;
use crate::pager::HistoryDbMode;
use reedline::{History, SqliteBackedHistory};
use std::path::PathBuf;

use super::shell::confirm_action;
use super::state::PromptRuntimeConfig;
use super::{ARF_PREFIX, arf_println};

/// Result of processing a meta command.
pub enum MetaCommandResult {
    /// Command was handled, continue with new prompt
    Handled,
    /// User wants to exit
    Exit,
    /// Unknown command
    Unknown(String),
    /// Shell command was executed inline (for :system)
    ShellExecuted,
    /// Restart the process with optional R version
    Restart(Option<String>),
    /// Open the help browser with the given query (caller runs pager)
    ShowHelpBrowser(String),
    /// Display session info (caller runs pager)
    ShowSessionInfo,
    /// Display changelog (caller runs pager)
    ShowChangelog,
    /// Open the history browser (caller runs pager)
    ShowHistoryBrowser { path: PathBuf, mode: HistoryDbMode },
    /// Display history schema (caller runs pager)
    ShowHistorySchema,
}

/// Process a meta command (starting with `:`) and return the result.
#[allow(clippy::too_many_arguments)]
pub fn process_meta_command(
    input: &str,
    prompt_config: &mut PromptRuntimeConfig,
    r_history_path: &Option<PathBuf>,
    shell_history_path: &Option<PathBuf>,
    r_source_status: &RSourceStatus,
    dir_stack: &mut Vec<PathBuf>,
    history_session_id: Option<i64>,
) -> Option<MetaCommandResult> {
    let trimmed = input.trim();
    if !trimmed.starts_with(':') {
        return None;
    }

    let parts: Vec<&str> = trimmed[1..].split_whitespace().collect();
    let cmd = parts.first().copied().unwrap_or("");

    match cmd {
        "reprex" => {
            prompt_config.toggle_reprex();
            if prompt_config.is_reprex_enabled() {
                if prompt_config.is_autoformat_enabled() {
                    println!(
                        "# Reprex mode enabled (comment: {:?}, auto-format: on)",
                        prompt_config.reprex_comment
                    );
                } else {
                    arf_println!(
                        "Reprex mode enabled (comment: {:?})",
                        prompt_config.reprex_comment
                    );
                }
            } else {
                arf_println!("Reprex mode disabled");
            }
            Some(MetaCommandResult::Handled)
        }
        "autoformat" | "format" => {
            if prompt_config.is_autoformat_enabled() {
                // Disabling - always allowed
                prompt_config.toggle_autoformat();
                arf_println!("Autoformat disabled");
            } else {
                // Enabling - check if Air is available
                if formatter::is_formatter_available() {
                    prompt_config.toggle_autoformat();
                    if prompt_config.is_reprex_enabled() {
                        arf_println!("Autoformat enabled");
                    } else {
                        arf_println!("Autoformat enabled (activate reprex mode to use)");
                    }
                } else {
                    arf_println!(
                        "Error: Cannot enable autoformat - Air CLI ('air' command) not found in PATH."
                    );
                    arf_println!("Install Air CLI from https://github.com/posit-dev/air");
                }
            }
            Some(MetaCommandResult::Handled)
        }
        "shell" => {
            prompt_config.set_shell(true);
            arf_println!("Shell mode enabled. Type :r to return to R.");
            Some(MetaCommandResult::Handled)
        }
        "r" | "R" => {
            if prompt_config.is_shell_enabled() {
                prompt_config.set_shell(false);
                arf_println!("Returned to R mode.");
            } else {
                arf_println!("Already in R mode.");
            }
            Some(MetaCommandResult::Handled)
        }
        "system" => {
            // Execute the rest of the input as a shell command
            let shell_cmd = trimmed[1..].strip_prefix("system").unwrap_or("").trim();
            if shell_cmd.is_empty() {
                arf_println!("Usage: :system <command>");
            } else {
                if let Some(hint) = dir_command_hint(shell_cmd) {
                    arf_println!("{}", hint);
                }
                super::shell::execute_shell_command(shell_cmd);
            }
            Some(MetaCommandResult::ShellExecuted)
        }
        "restart" | "restart!" => {
            let force = cmd == "restart!";
            if force
                || confirm_action(&format!(
                    "{} Restart R session? Current session will be lost.",
                    ARF_PREFIX
                ))
            {
                arf_println!("Restarting R session...");
                Some(MetaCommandResult::Restart(None))
            } else {
                arf_println!("Restart cancelled.");
                Some(MetaCommandResult::Handled)
            }
        }
        "switch" | "switch!" => {
            // :switch requires rig to be enabled at startup
            if !r_source_status.rig_enabled() {
                arf_println!("Error: :switch requires rig to be available at startup.");
                arf_println!(
                    r#"Start arf with r_source = "auto" (with rig installed) or r_source = "rig"."#
                );
                return Some(MetaCommandResult::Handled);
            }

            // Extract version argument
            let version = parts.get(1).map(|s| s.to_string());
            if version.is_none() {
                arf_println!("Usage: :{cmd} <version>");
                arf_println!("Example: :{cmd} 4.4 or :{cmd} release");
                return Some(MetaCommandResult::Handled);
            }
            let force = cmd == "switch!";
            let ver = version.as_ref().unwrap();
            if force || confirm_action(&format!("Restart with R {}?", ver)) {
                arf_println!("Restarting with R {}...", ver);
                Some(MetaCommandResult::Restart(version))
            } else {
                arf_println!("Switch cancelled.");
                Some(MetaCommandResult::Handled)
            }
        }
        "history" => {
            let subcmd = parts.get(1).copied().unwrap_or("");
            match subcmd {
                "browse" => {
                    let target = parts.get(2).copied().unwrap_or("");
                    process_history_browse(
                        r_history_path,
                        shell_history_path,
                        target,
                        prompt_config.is_shell_enabled(),
                    )
                }
                "clear" => {
                    let target = parts.get(2).copied().unwrap_or("");
                    process_history_clear(
                        r_history_path,
                        shell_history_path,
                        target,
                        prompt_config.is_shell_enabled(),
                    )
                }
                "schema" => Some(MetaCommandResult::ShowHistorySchema),
                "" => {
                    arf_println!("Usage: :history <subcommand>");
                    println!("#   browse - Browse and manage command history");
                    println!("#   clear  - Clear command history");
                    println!("#   schema - Display database schema and R examples");
                    Some(MetaCommandResult::Handled)
                }
                _ => {
                    arf_println!(
                        "Unknown history subcommand: {}. Use :history for help",
                        subcmd
                    );
                    Some(MetaCommandResult::Handled)
                }
            }
        }
        "help" | "h" => {
            // Fuzzy help search for R documentation
            // Inspired by the felp package: https://github.com/atusy/felp
            let query = parts.get(1..).map(|p| p.join(" ")).unwrap_or_default();
            Some(MetaCommandResult::ShowHelpBrowser(query))
        }
        "info" | "session" => Some(MetaCommandResult::ShowSessionInfo),
        "changelog" => Some(MetaCommandResult::ShowChangelog),
        "cd" => {
            let path_arg = trimmed[1..].strip_prefix("cd").unwrap_or("").trim();
            match meta_cd(path_arg) {
                Ok(cwd) => arf_println!("{}", cwd.display()),
                Err(e) => arf_println!("cd: {}", e),
            }
            Some(MetaCommandResult::Handled)
        }
        "pushd" => {
            let path_arg = trimmed[1..].strip_prefix("pushd").unwrap_or("").trim();
            match meta_pushd(dir_stack, path_arg) {
                Ok(cwd) => arf_println!("{}", cwd.display()),
                Err(e) => arf_println!("pushd: {}", e),
            }
            Some(MetaCommandResult::Handled)
        }
        "popd" => {
            match meta_popd(dir_stack) {
                Ok(cwd) => arf_println!("{}", cwd.display()),
                Err(e) => arf_println!("popd: {}", e),
            }
            Some(MetaCommandResult::Handled)
        }
        "ipc" => {
            let subcmd = parts.get(1).copied().unwrap_or("status");
            match subcmd {
                "start" => match crate::ipc::start_server(None, None, history_session_id) {
                    Ok(session) => {
                        arf_println!("IPC server started: {}", session.socket_path)
                    }
                    Err(e) => arf_println!("Failed to start IPC server: {}", e),
                },
                "stop" => {
                    crate::ipc::stop_server();
                    arf_println!("IPC server stopped.");
                }
                "status" => {
                    let sessions = crate::ipc::session::list_sessions();
                    let my_pid = std::process::id();
                    let my_session = sessions.iter().find(|s| s.pid == my_pid);
                    if let Some(session) = my_session {
                        arf_println!("IPC server is running.");
                        println!("#   Socket: {}", session.socket_path);
                        println!("#   PID:    {}", session.pid);
                    } else {
                        arf_println!(
                            "IPC server is not running. Use :ipc start or --with-ipc flag."
                        );
                    }
                }
                _ => {
                    arf_println!("Unknown :ipc subcommand. Available: start, stop, status");
                }
            }
            Some(MetaCommandResult::Handled)
        }
        "commands" | "cmds" => {
            arf_println!("Available commands:");
            println!("#   :help          - Search R help");
            println!("#   :info          - Show session information");
            println!("#   :shell         - Enter shell mode (input goes to system shell)");
            println!("#   :r             - Return to R mode (from shell mode)");
            println!("#   :system <cmd>  - Execute a single system command");
            println!("#   :cd <path>     - Change working directory");
            println!("#   :pushd <path>  - Push directory and change to it");
            println!("#   :popd          - Pop directory from stack");
            println!("#   :reprex        - Toggle reprex mode");
            println!(
                "#   :autoformat    - Toggle auto-formatting in reprex mode (requires Air CLI)"
            );
            println!("#   :history       - History management (browse, clear, schema)");
            println!("#   :restart       - Restart R session");
            println!("#   :restart!      - Restart without confirmation");
            println!("#   :switch <ver>  - Restart with different R version (requires rig)");
            println!("#   :switch! <ver> - Switch without confirmation");
            println!("#   :ipc           - IPC server management (start, stop, status)");
            println!("#   :changelog     - Show arf changelog");
            println!("#   :commands      - Show this list");
            println!("#   :quit          - Exit arf");
            Some(MetaCommandResult::Handled)
        }
        "quit" | "exit" => Some(MetaCommandResult::Exit),
        "" => {
            // Just ":" with nothing after - show help hint
            arf_println!("Type :commands for available commands");
            Some(MetaCommandResult::Handled)
        }
        _ => Some(MetaCommandResult::Unknown(cmd.to_string())),
    }
}

/// Process :history browse command.
fn process_history_browse(
    r_history_path: &Option<PathBuf>,
    shell_history_path: &Option<PathBuf>,
    target: &str,
    is_shell_mode: bool,
) -> Option<MetaCommandResult> {
    // Determine which database to browse
    let (mode, path) = match target {
        "" => {
            // Default: browse based on current mode
            if is_shell_mode {
                (HistoryDbMode::Shell, shell_history_path.as_ref())
            } else {
                (HistoryDbMode::R, r_history_path.as_ref())
            }
        }
        "r" | "R" => (HistoryDbMode::R, r_history_path.as_ref()),
        "shell" => (HistoryDbMode::Shell, shell_history_path.as_ref()),
        _ => {
            arf_println!("Unknown target: {}. Use r or shell.", target);
            return Some(MetaCommandResult::Handled);
        }
    };

    let Some(db_path) = path else {
        arf_println!("History is disabled for {} mode.", mode.display_name());
        return Some(MetaCommandResult::Handled);
    };

    Some(MetaCommandResult::ShowHistoryBrowser {
        path: db_path.clone(),
        mode,
    })
}

/// Process :history clear command.
fn process_history_clear(
    r_history_path: &Option<PathBuf>,
    shell_history_path: &Option<PathBuf>,
    target: &str,
    is_shell_mode: bool,
) -> Option<MetaCommandResult> {
    // Determine what to clear based on target
    let clear_target = match target {
        "" => {
            // Default: clear based on current mode
            if is_shell_mode { "shell" } else { "r" }
        }
        "r" | "R" => "r",
        "shell" => "shell",
        "all" => "all",
        _ => {
            arf_println!("Unknown target: {}. Use r, shell, or all.", target);
            return Some(MetaCommandResult::Handled);
        }
    };

    // Collect paths to clear based on target
    let paths_to_clear: Vec<(&str, &PathBuf)> = match clear_target {
        "r" => r_history_path
            .as_ref()
            .map(|p| vec![("R", p)])
            .unwrap_or_default(),
        "shell" => shell_history_path
            .as_ref()
            .map(|p| vec![("Shell", p)])
            .unwrap_or_default(),
        "all" => {
            let mut paths = Vec::new();
            if let Some(p) = r_history_path.as_ref() {
                paths.push(("R", p));
            }
            if let Some(p) = shell_history_path.as_ref() {
                paths.push(("Shell", p));
            }
            paths
        }
        _ => unreachable!(),
    };

    if paths_to_clear.is_empty() {
        arf_println!("History is disabled.");
        return Some(MetaCommandResult::Handled);
    }

    // Count total entries across all targeted databases
    let mut total_count = 0i64;
    let mut counts: Vec<(&str, i64)> = Vec::new();

    for (name, path) in &paths_to_clear {
        match SqliteBackedHistory::with_file((*path).clone(), None, None) {
            Ok(history) => {
                if let Ok(count) = history.count_all() {
                    counts.push((name, count));
                    total_count += count;
                }
            }
            Err(_) => {
                // Database doesn't exist yet, treat as 0 entries
                counts.push((name, 0));
            }
        }
    }

    if total_count == 0 {
        arf_println!("History is already empty.");
        return Some(MetaCommandResult::Handled);
    }

    // Show what will be cleared
    if counts.len() == 1 {
        arf_println!("{} history: {} entries", counts[0].0, counts[0].1);
    } else {
        for (name, count) in &counts {
            arf_println!("{} history: {} entries", name, count);
        }
        arf_println!("Total: {} entries", total_count);
    }

    // Confirm before clearing
    let prompt = format!("{} Clear {} history entries?", ARF_PREFIX, total_count);
    if !confirm_action(&prompt) {
        arf_println!("Cancelled.");
        return Some(MetaCommandResult::Handled);
    }

    // Perform clear on each database
    let mut cleared_count = 0i64;
    for (name, path) in &paths_to_clear {
        match SqliteBackedHistory::with_file((*path).clone(), None, None) {
            Ok(mut history) => {
                if let Ok(count) = history.count_all()
                    && count > 0
                {
                    if let Err(e) = history.clear() {
                        arf_println!("Failed to clear {} history: {}", name, e);
                    } else {
                        cleared_count += count;
                    }
                }
            }
            Err(_) => {
                // Database doesn't exist, nothing to clear
            }
        }
    }

    arf_println!("Cleared {} history entries.", cleared_count);
    Some(MetaCommandResult::Handled)
}

/// Change the current working directory.
///
/// If `path_arg` is empty, changes to the home directory.
/// Tilde (`~`) is expanded to the home directory.
pub(crate) fn meta_cd(path_arg: &str) -> Result<PathBuf, String> {
    let target = if path_arg.is_empty() {
        dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?
    } else {
        PathBuf::from(expand_tilde(path_arg))
    };
    std::env::set_current_dir(&target).map_err(|e| format!("{}: {}", target.display(), e))?;
    std::env::current_dir().map_err(|e| e.to_string())
}

/// Push the current directory onto the stack and change to a new directory.
///
/// Requires a path argument. Unlike bash's `pushd` (which swaps the top two
/// stack entries when called without arguments), this always requires an
/// explicit destination.
pub(crate) fn meta_pushd(dir_stack: &mut Vec<PathBuf>, path_arg: &str) -> Result<PathBuf, String> {
    if path_arg.is_empty() {
        return Err("Usage: :pushd <path>".to_string());
    }
    let current = std::env::current_dir().map_err(|e| e.to_string())?;
    let new_dir = meta_cd(path_arg)?;
    dir_stack.push(current);
    Ok(new_dir)
}

/// Pop the top directory from the stack and change to it.
pub(crate) fn meta_popd(dir_stack: &mut Vec<PathBuf>) -> Result<PathBuf, String> {
    let target = dir_stack
        .last()
        .cloned()
        .ok_or_else(|| "Directory stack is empty".to_string())?;
    std::env::set_current_dir(&target).map_err(|e| format!("{}", e))?;
    dir_stack.pop();
    std::env::current_dir().map_err(|e| e.to_string())
}

/// Return a hint message if the shell command is a directory navigation command
/// that won't work as expected in a subprocess.
pub(crate) fn dir_command_hint(shell_cmd: &str) -> Option<&'static str> {
    match shell_cmd.split_whitespace().next()? {
        "cd" => Some("Hint: Use the :cd meta command instead to change directory."),
        "pushd" => Some("Hint: Use the :pushd meta command instead to change directory."),
        "popd" => Some("Hint: Use the :popd meta command instead to restore directory."),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::editor::prompt::PromptFormatter;

    fn create_test_prompt_config() -> PromptRuntimeConfig {
        PromptRuntimeConfig::builder(PromptFormatter::default(), "r> ", "+  ", "[bash] $ ").build()
    }

    /// Default r_source_status for tests (PATH mode, rig not enabled).
    fn default_r_source_status() -> RSourceStatus {
        RSourceStatus::Path
    }

    /// Helper to call process_meta_command with default dir_stack.
    fn call_meta(
        input: &str,
        config: &mut PromptRuntimeConfig,
        r_history_path: &Option<PathBuf>,
        shell_history_path: &Option<PathBuf>,
        status: &RSourceStatus,
    ) -> Option<MetaCommandResult> {
        let mut dir_stack = Vec::new();
        process_meta_command(
            input,
            config,
            r_history_path,
            shell_history_path,
            status,
            &mut dir_stack,
            None,
        )
    }

    #[test]
    fn test_process_meta_command_not_meta() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta("print(x)", &mut config, &None, &None, &status);
        assert!(result.is_none());
    }

    #[test]
    fn test_process_meta_command_reprex_toggle() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        assert!(!config.is_reprex_enabled());

        let result = call_meta(":reprex", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
        assert!(config.is_reprex_enabled());

        let result = call_meta(":reprex", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
        assert!(!config.is_reprex_enabled());
    }

    #[test]
    fn test_process_meta_command_commands() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta(":commands", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));

        // Test alias
        let result = call_meta(":cmds", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
    }

    #[test]
    fn test_process_meta_command_info() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta(":info", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::ShowSessionInfo)));

        // Test alias
        let result = call_meta(":session", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::ShowSessionInfo)));
    }

    #[test]
    fn test_process_meta_command_quit() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta(":quit", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Exit)));

        let result = call_meta(":exit", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Exit)));
    }

    #[test]
    fn test_process_meta_command_unknown() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta(":unknown", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Unknown(_))));
    }

    #[test]
    fn test_process_meta_command_empty_colon() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta(":", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
    }

    #[test]
    fn test_process_meta_command_with_whitespace() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta("  :reprex  ", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
        assert!(config.is_reprex_enabled());
    }

    #[test]
    fn test_process_meta_command_shell_enter() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        assert!(!config.is_shell_enabled());

        let result = call_meta(":shell", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
        assert!(config.is_shell_enabled());
    }

    #[test]
    fn test_process_meta_command_shell_exit_with_r() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        config.set_shell(true);
        assert!(config.is_shell_enabled());

        let result = call_meta(":r", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
        assert!(!config.is_shell_enabled());
    }

    #[test]
    fn test_process_meta_command_shell_exit_with_uppercase_r() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        config.set_shell(true);
        assert!(config.is_shell_enabled());

        let result = call_meta(":R", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
        assert!(!config.is_shell_enabled());
    }

    #[test]
    fn test_process_meta_command_r_when_not_in_shell() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        assert!(!config.is_shell_enabled());

        let result = call_meta(":r", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
        assert!(!config.is_shell_enabled()); // Still not in shell
    }

    #[test]
    fn test_process_meta_command_system() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta(":system echo hello", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::ShellExecuted)));
    }

    #[test]
    fn test_process_meta_command_system_empty() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta(":system", &mut config, &None, &None, &status);
        // Empty :system should still be handled
        assert!(matches!(result, Some(MetaCommandResult::ShellExecuted)));
    }

    #[test]
    fn test_process_meta_command_switch_requires_rig() {
        let mut config = create_test_prompt_config();

        // With PATH mode (rig not enabled), :switch should show error
        let status_path = RSourceStatus::Path;
        let result = call_meta(":switch 4.4", &mut config, &None, &None, &status_path);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));

        // With Rig mode (rig enabled), :switch should work (but needs confirmation which we can't test here)
        // Just verify it doesn't immediately reject
        let status_rig = RSourceStatus::Rig {
            version: "4.4.0".to_string(),
        };
        // Note: This will prompt for confirmation, so we can't fully test it in unit tests
        // Just testing the setup path here
        let result = call_meta(":switch", &mut config, &None, &None, &status_rig);
        // Without version argument, it should show usage
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
    }

    // --- cd/pushd/popd tests ---

    #[test]
    fn test_meta_cd_relative_path() {
        let _guard = crate::test_utils::lock_cwd();
        let tmp = tempfile::tempdir().unwrap();
        let subdir = tmp.path().join("sub");
        std::fs::create_dir(&subdir).unwrap();

        std::env::set_current_dir(tmp.path()).unwrap();
        let result = meta_cd("sub");

        assert!(result.is_ok());
        assert!(result.unwrap().ends_with("sub"));
    }

    #[test]
    fn test_meta_cd_absolute_path() {
        let _guard = crate::test_utils::lock_cwd();
        let tmp = tempfile::tempdir().unwrap();

        let result = meta_cd(&tmp.path().to_string_lossy());

        assert!(result.is_ok());
    }

    #[test]
    fn test_meta_cd_tilde() {
        let _guard = crate::test_utils::lock_cwd();
        let result = meta_cd("~");

        assert!(result.is_ok());
        if let Some(home) = dirs::home_dir() {
            assert_eq!(
                result.unwrap().canonicalize().ok(),
                home.canonicalize().ok()
            );
        }
    }

    #[test]
    fn test_meta_cd_no_args() {
        let _guard = crate::test_utils::lock_cwd();
        let result = meta_cd("");

        assert!(result.is_ok());
        // Should go to home
        if let Some(home) = dirs::home_dir() {
            assert_eq!(
                result.unwrap().canonicalize().ok(),
                home.canonicalize().ok()
            );
        }
    }

    #[test]
    fn test_meta_cd_nonexistent() {
        let result = meta_cd("/nonexistent_path_12345");
        assert!(result.is_err());
    }

    #[test]
    fn test_meta_pushd_popd() {
        let _guard = crate::test_utils::lock_cwd();
        let tmp = tempfile::tempdir().unwrap();
        let mut dir_stack = Vec::new();

        std::env::set_current_dir(tmp.path()).unwrap();
        let subdir = tmp.path().join("sub");
        std::fs::create_dir(&subdir).unwrap();

        // pushd into sub
        let result = meta_pushd(&mut dir_stack, "sub");
        assert!(result.is_ok());
        assert_eq!(dir_stack.len(), 1);
        assert!(std::env::current_dir().unwrap().ends_with("sub"));

        // popd back
        let result = meta_popd(&mut dir_stack);
        assert!(result.is_ok());
        assert!(dir_stack.is_empty());
        assert_eq!(
            std::env::current_dir().unwrap().canonicalize().ok(),
            tmp.path().canonicalize().ok()
        );
    }

    #[test]
    fn test_meta_popd_empty_stack() {
        let mut dir_stack: Vec<PathBuf> = Vec::new();
        let result = meta_popd(&mut dir_stack);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("empty"));
    }

    #[test]
    fn test_meta_pushd_no_args_returns_error() {
        let mut dir_stack: Vec<PathBuf> = Vec::new();
        let result = meta_pushd(&mut dir_stack, "");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Usage"));
        // Stack should not be modified
        assert!(dir_stack.is_empty());
    }

    #[test]
    fn test_meta_pushd_saves_previous() {
        let _guard = crate::test_utils::lock_cwd();
        let tmp = tempfile::tempdir().unwrap();
        let subdir = tmp.path().join("sub");
        std::fs::create_dir(&subdir).unwrap();
        let mut dir_stack = Vec::new();

        std::env::set_current_dir(tmp.path()).unwrap();
        let before_pushd = std::env::current_dir().unwrap();

        let _ = meta_pushd(&mut dir_stack, "sub");
        assert_eq!(dir_stack.len(), 1);
        assert_eq!(
            dir_stack[0].canonicalize().ok(),
            before_pushd.canonicalize().ok()
        );
    }

    #[test]
    fn test_process_meta_command_cd() {
        let _guard = crate::test_utils::lock_cwd();
        let tmp = tempfile::tempdir().unwrap();
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let mut dir_stack = Vec::new();

        let result = process_meta_command(
            &format!(":cd {}", tmp.path().display()),
            &mut config,
            &None,
            &None,
            &status,
            &mut dir_stack,
            None,
        );
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
    }

    #[test]
    fn test_process_meta_command_pushd_popd() {
        let _guard = crate::test_utils::lock_cwd();
        let tmp = tempfile::tempdir().unwrap();
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let mut dir_stack = Vec::new();

        let result = process_meta_command(
            &format!(":pushd {}", tmp.path().display()),
            &mut config,
            &None,
            &None,
            &status,
            &mut dir_stack,
            None,
        );
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
        assert_eq!(dir_stack.len(), 1);

        let result = process_meta_command(
            ":popd",
            &mut config,
            &None,
            &None,
            &status,
            &mut dir_stack,
            None,
        );
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
        assert!(dir_stack.is_empty());
    }

    // --- dir_command_hint tests ---

    #[test]
    fn test_dir_command_hint_cd() {
        assert!(dir_command_hint("cd /tmp").unwrap().contains(":cd"));
    }

    #[test]
    fn test_dir_command_hint_pushd() {
        assert!(dir_command_hint("pushd /tmp").unwrap().contains(":pushd"));
    }

    #[test]
    fn test_dir_command_hint_popd() {
        assert!(dir_command_hint("popd").unwrap().contains(":popd"));
    }

    #[test]
    fn test_dir_command_hint_other() {
        assert!(dir_command_hint("ls -la").is_none());
        assert!(dir_command_hint("echo cd").is_none());
    }

    #[test]
    fn test_dir_command_hint_empty() {
        assert!(dir_command_hint("").is_none());
    }

    // --- Force (!) option tests ---

    #[test]
    fn test_process_meta_command_restart_force() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        // :restart! should skip confirmation and return Restart directly
        let result = call_meta(":restart!", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Restart(None))));
    }

    #[test]
    fn test_process_meta_command_restart_force_with_whitespace() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        let result = call_meta("  :restart!  ", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Restart(None))));
    }

    #[test]
    fn test_process_meta_command_switch_force() {
        let mut config = create_test_prompt_config();
        let status_rig = RSourceStatus::Rig {
            version: "4.4.0".to_string(),
        };
        let result = call_meta(":switch! 4.4", &mut config, &None, &None, &status_rig);
        assert!(matches!(result, Some(MetaCommandResult::Restart(Some(ref v))) if v == "4.4"));
    }

    #[test]
    fn test_process_meta_command_switch_force_no_version() {
        let mut config = create_test_prompt_config();
        let status_rig = RSourceStatus::Rig {
            version: "4.4.0".to_string(),
        };
        // :switch! without version should still show usage
        let result = call_meta(":switch!", &mut config, &None, &None, &status_rig);
        assert!(matches!(result, Some(MetaCommandResult::Handled)));
    }

    #[test]
    fn test_process_meta_command_unknown_with_bang() {
        let mut config = create_test_prompt_config();
        let status = default_r_source_status();
        // :shell! is not a valid command (! only supported on restart/switch)
        let result = call_meta(":shell!", &mut config, &None, &None, &status);
        assert!(matches!(result, Some(MetaCommandResult::Unknown(_))));
    }
}