arf-console 0.6.0

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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! Meta command completer for commands starting with `:`.

use super::path::PathCompletionOptions;
use super::string_context::path_to_suggestions;
use crate::external::rig;
use crate::fuzzy::fuzzy_match;
use reedline::{Completer, CompletionResult, Span, Suggestion};

/// Definition of a meta command for completion.
struct MetaCommandDef {
    name: &'static str,
    description: &'static str,
    /// Whether this command takes an argument (e.g., `:switch 4.4`).
    /// If true, a trailing space is appended after completion.
    takes_argument: bool,
}

/// Available meta commands.
const META_COMMANDS: &[MetaCommandDef] = &[
    MetaCommandDef {
        name: "help",
        description: "Search R help",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "h",
        description: "Search R help (alias)",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "info",
        description: "Show session information",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "session",
        description: "Show session information (alias)",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "shell",
        description: "Enter shell mode",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "r",
        description: "Return to R mode",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "system",
        description: "Execute system command",
        takes_argument: true,
    },
    MetaCommandDef {
        name: "reprex",
        description: "Set reprex mode (on, off, or format)",
        takes_argument: true,
    },
    MetaCommandDef {
        name: "commands",
        description: "Show available commands",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "cmds",
        description: "Show available commands (alias)",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "restart",
        description: "Restart R session",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "restart!",
        description: "Restart R session (skip confirmation)",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "switch",
        description: "Restart with different R version (requires rig)",
        takes_argument: true,
    },
    MetaCommandDef {
        name: "switch!",
        description: "Restart with different R version, skip confirmation (requires rig)",
        takes_argument: true,
    },
    MetaCommandDef {
        name: "changelog",
        description: "Show arf changelog",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "history",
        description: "Manage command history",
        takes_argument: true,
    },
    MetaCommandDef {
        name: "cd",
        description: "Change working directory",
        takes_argument: true,
    },
    MetaCommandDef {
        name: "pushd",
        description: "Push directory and change to it",
        takes_argument: true,
    },
    MetaCommandDef {
        name: "popd",
        description: "Pop directory from stack",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "ipc",
        description: "IPC server and send-policy management",
        takes_argument: true,
    },
    MetaCommandDef {
        name: "quit",
        description: "Quit arf",
        takes_argument: false,
    },
    MetaCommandDef {
        name: "exit",
        description: "Quit arf",
        takes_argument: false,
    },
];

/// Completer for meta commands (starting with `:`).
pub struct MetaCommandCompleter {
    /// Commands to exclude from completion (e.g., `:r` in R mode, `:shell` in Shell mode).
    excluded_commands: Vec<&'static str>,
}

impl MetaCommandCompleter {
    pub fn new() -> Self {
        MetaCommandCompleter {
            excluded_commands: vec![],
        }
    }

    /// Create a new completer with specified commands excluded from completion.
    pub fn with_exclusions(excluded_commands: Vec<&'static str>) -> Self {
        MetaCommandCompleter { excluded_commands }
    }

    /// Commands excluded from meta completion while in shell mode.
    pub(crate) fn shell_mode_exclusions() -> Vec<&'static str> {
        vec![
            "shell", "system", "restart", "reprex", "switch", "h", "help",
        ]
    }

    /// Complete meta commands.
    fn complete_commands(&self, line: &str, pos: usize) -> Vec<Suggestion> {
        let trimmed = line.trim_start();
        if !trimmed.starts_with(':') {
            return vec![];
        }

        // Get the part after ':'
        let after_colon = &trimmed[1..];

        // Check if there's a trailing space (user finished typing and wants subcommands)
        let has_trailing_space = after_colon.ends_with(' ') || after_colon.ends_with('\t');
        let parts: Vec<&str> = after_colon.split_whitespace().collect();

        // Calculate the start position for the span
        let leading_whitespace = line.len() - trimmed.len();

        // Handle path completion for :cd and :pushd
        // This is done before the main match so that paths with spaces work correctly
        // (we extract the raw substring instead of using split_whitespace parts).
        if let Some(cmd) = parts.first()
            && (*cmd == "cd" || *cmd == "pushd")
            && (parts.len() > 1 || has_trailing_space)
        {
            let cmd_end = 1 + cmd.len(); // ":" + cmd
            let rest = &trimmed[cmd_end..];
            let ws_after = rest.len() - rest.trim_start().len();
            let arg_start = leading_whitespace + cmd_end + ws_after;
            let partial = if pos > arg_start {
                &line[arg_start..pos]
            } else {
                ""
            };
            return path_to_suggestions(
                partial,
                pos,
                arg_start,
                &PathCompletionOptions {
                    directories_only: true,
                    ..Default::default()
                },
            );
        }

        match (parts.len(), has_trailing_space) {
            (0, _) => {
                // Just ":" - show all commands
                let start = leading_whitespace + 1; // after ':'
                let mut suggestions: Vec<Suggestion> = META_COMMANDS
                    .iter()
                    .filter(|cmd| !self.excluded_commands.contains(&cmd.name))
                    .map(|cmd| Suggestion {
                        value: cmd.name.to_string(),
                        display_override: None,
                        description: Some(cmd.description.to_string()),
                        extra: None,
                        span: Span { start, end: pos },
                        append_whitespace: cmd.takes_argument,
                        style: None,
                        match_indices: None,
                    })
                    .collect();
                // Sort by length so shorter aliases (h, r, cmds) appear before longer forms
                suggestions.sort_by_key(|s| s.value.len());
                suggestions
            }
            (1, false) => {
                // Typing command name, e.g., ":rep" or ":rst" (fuzzy)
                let partial = parts[0];
                let start = leading_whitespace + 1; // after ':'
                let mut suggestions: Vec<Suggestion> = META_COMMANDS
                    .iter()
                    .filter(|cmd| !self.excluded_commands.contains(&cmd.name))
                    .filter_map(|cmd| {
                        fuzzy_match(partial, cmd.name).map(|m| Suggestion {
                            value: cmd.name.to_string(),
                            display_override: None,
                            description: Some(cmd.description.to_string()),
                            extra: None,
                            span: Span { start, end: pos },
                            append_whitespace: cmd.takes_argument,
                            style: None,
                            match_indices: if m.indices.is_empty() {
                                None
                            } else {
                                Some(m.indices)
                            },
                        })
                    })
                    .collect();
                // Sort by length so shorter aliases (h, r, cmds) appear before longer forms
                suggestions.sort_by_key(|s| s.value.len());
                suggestions
            }
            (1, true) => {
                // Command complete with trailing space - check for subcommands
                let cmd = parts[0];
                // Strip `!` suffix so `:switch!` gets version completions like `:switch`
                if cmd == "switch" || cmd == "switch!" {
                    // Complete with R versions from rig
                    self.complete_switch_versions(line, pos, leading_whitespace, "")
                } else if cmd == "history" {
                    // Complete with history subcommands
                    self.complete_history_subcommands(pos, "")
                } else if cmd == "ipc" {
                    self.complete_ipc_subcommands(pos, "")
                } else if cmd == "reprex" {
                    self.complete_targets(
                        pos,
                        "",
                        &[
                            ("on", "Enable reprex output"),
                            ("off", "Disable reprex output"),
                            ("format", "Format code before reprex evaluation"),
                        ],
                    )
                } else {
                    vec![]
                }
            }
            (2, false) => {
                // Typing subcommand argument
                let cmd = parts[0];
                let partial = parts[1];
                if cmd == "switch" || cmd == "switch!" {
                    self.complete_switch_versions(line, pos, leading_whitespace, partial)
                } else if cmd == "history" {
                    self.complete_history_subcommands(pos, partial)
                } else if cmd == "ipc" {
                    self.complete_ipc_subcommands(pos, partial)
                } else if cmd == "reprex" {
                    self.complete_targets(
                        pos,
                        partial,
                        &[
                            ("on", "Enable reprex output"),
                            ("off", "Disable reprex output"),
                            ("format", "Format code before reprex evaluation"),
                        ],
                    )
                } else {
                    vec![]
                }
            }
            (2, true) => {
                // Two parts complete with trailing space - check for third level
                let cmd = parts[0];
                let subcmd = parts[1];
                if cmd == "history" && subcmd == "clear" {
                    // Complete with clear targets (r, shell, all)
                    self.complete_history_clear_targets(pos, "")
                } else if cmd == "history" && subcmd == "browse" {
                    // Complete with browse targets (r, shell)
                    self.complete_history_browse_targets(pos, "")
                } else if cmd == "ipc" && subcmd == "send-policy" {
                    self.complete_targets(
                        pos,
                        "",
                        &[
                            ("prompt", "Require approval for every interactive send"),
                            ("allow", "Allow sends for the current REPL process"),
                        ],
                    )
                } else {
                    vec![]
                }
            }
            (3, false) => {
                // Typing third argument
                let cmd = parts[0];
                let subcmd = parts[1];
                let partial = parts[2];
                if cmd == "history" && subcmd == "clear" {
                    self.complete_history_clear_targets(pos, partial)
                } else if cmd == "history" && subcmd == "browse" {
                    self.complete_history_browse_targets(pos, partial)
                } else if cmd == "ipc" && subcmd == "send-policy" {
                    self.complete_targets(
                        pos,
                        partial,
                        &[
                            ("prompt", "Require approval for every interactive send"),
                            ("allow", "Allow sends for the current REPL process"),
                        ],
                    )
                } else {
                    vec![]
                }
            }
            _ => {
                // No more completions
                vec![]
            }
        }
    }

    /// Complete R versions for the :switch command.
    fn complete_switch_versions(
        &self,
        line: &str,
        pos: usize,
        _leading_whitespace: usize,
        partial: &str,
    ) -> Vec<Suggestion> {
        // Check if rig is available
        if rig::rig_available().is_err() {
            return vec![];
        }

        // Get installed R versions from rig
        let versions = match rig::list_versions() {
            Ok(v) => v,
            Err(_) => return vec![],
        };

        // Calculate span start (after ":switch ")
        let start = if partial.is_empty() {
            pos
        } else {
            // Find where the partial version starts
            line.rfind(partial).unwrap_or(pos)
        };

        // Build suggestions from versions
        let match_len = partial.len();
        let mut suggestions: Vec<Suggestion> = versions
            .iter()
            .filter(|v| v.name.starts_with(partial) || v.version.starts_with(partial))
            .map(|v| {
                let description = if v.default {
                    format!("R {} (default)", v.version)
                } else {
                    format!("R {}", v.version)
                };
                let indices = if match_len > 0 {
                    Some((0..match_len).collect())
                } else {
                    None
                };
                Suggestion {
                    value: v.name.clone(),
                    display_override: None,
                    description: Some(description),
                    extra: None,
                    span: Span { start, end: pos },
                    append_whitespace: false,
                    style: None,
                    match_indices: indices,
                }
            })
            .collect();

        // Also add aliases as suggestions
        for v in &versions {
            for alias in &v.aliases {
                if alias.starts_with(partial) {
                    let indices = if match_len > 0 {
                        Some((0..match_len).collect())
                    } else {
                        None
                    };
                    suggestions.push(Suggestion {
                        value: alias.clone(),
                        display_override: None,
                        description: Some(format!("R {} (alias)", v.version)),
                        extra: None,
                        span: Span { start, end: pos },
                        append_whitespace: false,
                        style: None,
                        match_indices: indices,
                    });
                }
            }
        }

        suggestions
    }

    /// Complete history subcommands (browse, clear, schema).
    fn complete_history_subcommands(&self, pos: usize, partial: &str) -> Vec<Suggestion> {
        let subcommands = [
            ("browse", "Browse and manage command history"),
            ("clear", "Clear command history"),
            ("schema", "Display database schema and R examples"),
        ];

        let match_len = partial.len();
        subcommands
            .iter()
            .filter(|(name, _)| name.starts_with(partial))
            .map(|(name, desc)| {
                let indices = if match_len > 0 {
                    Some((0..match_len).collect())
                } else {
                    None
                };
                Suggestion {
                    value: name.to_string(),
                    display_override: None,
                    description: Some(desc.to_string()),
                    extra: None,
                    span: Span {
                        start: pos - match_len,
                        end: pos,
                    },
                    append_whitespace: true,
                    style: None,
                    match_indices: indices,
                }
            })
            .collect()
    }

    fn complete_ipc_subcommands(&self, pos: usize, partial: &str) -> Vec<Suggestion> {
        let mut suggestions = self.complete_targets(
            pos,
            partial,
            &[
                ("start", "Start the IPC server"),
                ("stop", "Stop the IPC server"),
                ("status", "Show IPC server status"),
                (
                    "send-policy",
                    "Change interactive send approval for this process",
                ),
            ],
        );
        for suggestion in &mut suggestions {
            suggestion.append_whitespace = suggestion.value == "send-policy";
        }
        suggestions
    }

    /// Complete from a list of (name, description) targets.
    fn complete_targets(
        &self,
        pos: usize,
        partial: &str,
        targets: &[(&str, &str)],
    ) -> Vec<Suggestion> {
        let match_len = partial.len();
        targets
            .iter()
            .filter(|(name, _)| name.starts_with(partial))
            .map(|(name, desc)| {
                let indices = if match_len > 0 {
                    Some((0..match_len).collect())
                } else {
                    None
                };
                Suggestion {
                    value: name.to_string(),
                    display_override: None,
                    description: Some(desc.to_string()),
                    extra: None,
                    span: Span {
                        start: pos - match_len,
                        end: pos,
                    },
                    append_whitespace: false,
                    style: None,
                    match_indices: indices,
                }
            })
            .collect()
    }

    /// Complete history clear targets (r, shell, all).
    fn complete_history_clear_targets(&self, pos: usize, partial: &str) -> Vec<Suggestion> {
        self.complete_targets(
            pos,
            partial,
            &[
                ("r", "Clear R mode history"),
                ("shell", "Clear shell mode history"),
                ("all", "Clear all history"),
            ],
        )
    }

    /// Complete history browse targets (r, shell).
    fn complete_history_browse_targets(&self, pos: usize, partial: &str) -> Vec<Suggestion> {
        self.complete_targets(
            pos,
            partial,
            &[
                ("r", "Browse R mode history"),
                ("shell", "Browse shell mode history"),
            ],
        )
    }
}

impl Default for MetaCommandCompleter {
    fn default() -> Self {
        Self::new()
    }
}

impl Completer for MetaCommandCompleter {
    fn complete(&mut self, line: &str, pos: usize) -> CompletionResult {
        CompletionResult::fresh(self.complete_commands(line, pos))
    }
}

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

    fn completion_suggestions(
        completer: &mut MetaCommandCompleter,
        line: &str,
        pos: usize,
    ) -> Vec<Suggestion> {
        completer.complete(line, pos).suggestions().to_vec()
    }

    #[test]
    fn test_meta_command_completer_empty_colon() {
        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":", 1);
        assert!(!suggestions.is_empty());
        let values: Vec<&str> = suggestions.iter().map(|s| s.value.as_str()).collect();
        assert!(values.contains(&"shell"));
        assert!(values.contains(&"r"));
        assert!(values.contains(&"system"));
        assert!(values.contains(&"reprex"));
        assert!(values.contains(&"commands"));
        assert!(values.contains(&"cmds"));
        assert!(values.contains(&"restart"));
        assert!(values.contains(&"restart!"));
        assert!(values.contains(&"switch"));
        assert!(values.contains(&"switch!"));
        assert!(values.contains(&"quit"));
        assert!(values.contains(&"exit"));
    }

    #[test]
    fn test_meta_command_completer_partial_command() {
        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":rep", 4);
        assert_eq!(suggestions.len(), 1);
        assert_eq!(suggestions[0].value, "reprex");
    }

    #[test]
    fn test_meta_command_completer_no_subcommands() {
        let mut completer = MetaCommandCompleter::new();
        // Reprex accepts the format subcommand.
        let suggestions = completion_suggestions(&mut completer, ":reprex ", 8);
        assert_eq!(
            suggestions
                .iter()
                .map(|s| s.value.as_str())
                .collect::<Vec<_>>(),
            ["on", "off", "format"]
        );
        let suggestions = completion_suggestions(&mut completer, ":commands ", 10);
        assert!(suggestions.is_empty());
    }

    #[test]
    fn test_meta_command_completer_not_meta_command() {
        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, "print(x)", 8);
        assert!(suggestions.is_empty());
    }

    #[test]
    fn test_meta_command_completer_has_descriptions() {
        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":", 1);
        let reprex = suggestions.iter().find(|s| s.value == "reprex").unwrap();
        assert!(reprex.description.is_some());
        assert!(reprex.description.as_ref().unwrap().contains("reprex"));
    }

    #[test]
    fn test_meta_command_completer_excludes_r_command() {
        // In R mode, `:r` should be excluded from completion
        let mut completer = MetaCommandCompleter::with_exclusions(vec!["r"]);
        let suggestions = completion_suggestions(&mut completer, ":", 1);
        let values: Vec<&str> = suggestions.iter().map(|s| s.value.as_str()).collect();
        assert!(!values.contains(&"r"), "`:r` should be excluded in R mode");
        assert!(
            values.contains(&"shell"),
            "`:shell` should still be present"
        );
    }

    #[test]
    fn test_meta_command_completer_excludes_shell_mode_commands() {
        // In Shell mode, R-specific commands should be excluded from completion
        let mut completer =
            MetaCommandCompleter::with_exclusions(MetaCommandCompleter::shell_mode_exclusions());
        let suggestions = completion_suggestions(&mut completer, ":", 1);
        let values: Vec<&str> = suggestions.iter().map(|s| s.value.as_str()).collect();

        // These should be excluded in Shell mode
        assert!(!values.contains(&"shell"), "`:shell` should be excluded");
        assert!(!values.contains(&"system"), "`:system` should be excluded");
        assert!(
            !values.contains(&"restart"),
            "`:restart` should be excluded"
        );
        assert!(!values.contains(&"reprex"), "`:reprex` should be excluded");
        assert!(!values.contains(&"switch"), "`:switch` should be excluded");
        assert!(!values.contains(&"h"), "`:h` should be excluded");
        assert!(!values.contains(&"help"), "`:help` should be excluded");

        // These should still be present in Shell mode
        assert!(values.contains(&"r"), "`:r` should be present");
        assert!(
            values.contains(&"commands"),
            "`:commands` should be present"
        );
        assert!(values.contains(&"quit"), "`:quit` should be present");
        assert!(values.contains(&"exit"), "`:exit` should be present");
    }

    #[test]
    fn test_meta_command_completer_exclusion_affects_partial_match() {
        // Even with partial match, excluded commands should not appear
        let mut completer = MetaCommandCompleter::with_exclusions(vec!["r"]);
        // Typing ":r" should not match excluded "r" command
        let suggestions = completion_suggestions(&mut completer, ":r", 2);
        let values: Vec<&str> = suggestions.iter().map(|s| s.value.as_str()).collect();
        assert!(
            !values.contains(&"r"),
            "`:r` should not appear even with partial match"
        );
        // But "restart" and "reprex" should still appear
        assert!(values.contains(&"restart"));
        assert!(values.contains(&"reprex"));
    }

    #[test]
    fn test_meta_command_append_whitespace_for_commands_with_arguments() {
        // Commands that take arguments should have append_whitespace: true
        let mut completer = MetaCommandCompleter::new();

        // :switch takes an argument (R version)
        let suggestions = completion_suggestions(&mut completer, ":sw", 3);
        let switch = suggestions.iter().find(|s| s.value == "switch").unwrap();
        assert!(
            switch.append_whitespace,
            "`:switch` should append whitespace because it takes an argument"
        );

        // :system takes an argument (shell command)
        let suggestions = completion_suggestions(&mut completer, ":sys", 4);
        let system = suggestions.iter().find(|s| s.value == "system").unwrap();
        assert!(
            system.append_whitespace,
            "`:system` should append whitespace because it takes an argument"
        );
    }

    #[test]
    fn test_meta_command_no_append_whitespace_for_commands_without_arguments() {
        // Commands that don't take arguments should have append_whitespace: false
        let mut completer = MetaCommandCompleter::new();

        let suggestions = completion_suggestions(&mut completer, ":", 1);

        // Commands without arguments
        for cmd_name in &["shell", "r", "commands", "cmds", "restart", "quit", "exit"] {
            if let Some(cmd) = suggestions.iter().find(|s| s.value == *cmd_name) {
                assert!(
                    !cmd.append_whitespace,
                    "`:{}` should NOT append whitespace because it takes no argument",
                    cmd_name
                );
            }
        }
    }

    #[test]
    fn test_meta_command_match_indices_for_partial_command() {
        // When typing a partial command, match_indices should highlight the matched prefix
        let mut completer = MetaCommandCompleter::new();

        // Typing ":rep" should match "reprex" and highlight positions 0,1,2
        let suggestions = completion_suggestions(&mut completer, ":rep", 4);
        assert_eq!(suggestions.len(), 1);
        let reprex = &suggestions[0];
        assert_eq!(reprex.value, "reprex");
        assert_eq!(reprex.match_indices, Some(vec![0, 1, 2]));
    }

    #[test]
    fn test_meta_command_match_indices_none_for_empty_input() {
        // When just ":" is typed, no prefix to highlight
        let mut completer = MetaCommandCompleter::new();

        let suggestions = completion_suggestions(&mut completer, ":", 1);
        assert!(!suggestions.is_empty());
        for suggestion in &suggestions {
            assert_eq!(
                suggestion.match_indices, None,
                "`:` with no partial input should have match_indices: None"
            );
        }
    }

    #[test]
    fn test_meta_command_match_indices_single_char() {
        // Single character fuzzy match - 'r' matches at different positions in different commands
        let mut completer = MetaCommandCompleter::new();

        let suggestions = completion_suggestions(&mut completer, ":r", 2);
        // With fuzzy matching, `:r` matches any command containing 'r':
        // - "r" at position 0
        // - "reprex" at position 0
        // - "restart" at position 0
        // Formatter aliases are not completion candidates.
        let values: Vec<&str> = suggestions.iter().map(|s| s.value.as_str()).collect();
        assert!(values.contains(&"r"));
        assert!(values.contains(&"reprex"));
        assert!(values.contains(&"restart"));

        // Verify match_indices are correct for each
        for suggestion in &suggestions {
            let expected_pos = suggestion
                .value
                .find('r')
                .or_else(|| suggestion.value.find('R'));
            assert_eq!(
                suggestion.match_indices,
                expected_pos.map(|p| vec![p]),
                "`:r` should highlight first 'r' position in `{}`",
                suggestion.value
            );
        }
    }

    // --- Fuzzy matching integration tests ---
    // Note: Direct fuzzy_match tests are in fuzzy.rs module

    #[test]
    fn test_meta_command_fuzzy_matching() {
        let mut completer = MetaCommandCompleter::new();

        // ":rst" should fuzzy match "restart"
        let suggestions = completion_suggestions(&mut completer, ":rst", 4);
        let values: Vec<&str> = suggestions.iter().map(|s| s.value.as_str()).collect();
        assert!(
            values.contains(&"restart"),
            "`:rst` should fuzzy match `restart`, got: {:?}",
            values
        );

        // Check match_indices for fuzzy match
        let restart = suggestions.iter().find(|s| s.value == "restart").unwrap();
        assert_eq!(
            restart.match_indices,
            Some(vec![0, 2, 3]),
            "`:rst` should highlight positions 0, 2, 3 in `restart`"
        );
    }

    #[test]
    fn test_meta_command_fuzzy_matching_cms_cmds() {
        let mut completer = MetaCommandCompleter::new();

        // ":cms" should match "cmds" - c=0, m=1, d=2, s=3
        let suggestions = completion_suggestions(&mut completer, ":cms", 4);
        let values: Vec<&str> = suggestions.iter().map(|s| s.value.as_str()).collect();
        assert!(values.contains(&"cmds"), "`:cms` should fuzzy match `cmds`");

        let cmds = suggestions.iter().find(|s| s.value == "cmds").unwrap();
        assert_eq!(
            cmds.match_indices,
            Some(vec![0, 1, 3]),
            "`:cms` should highlight positions 0, 1, 3 in `cmds`"
        );
    }

    #[test]
    fn test_meta_command_fuzzy_no_match() {
        let mut completer = MetaCommandCompleter::new();

        // ":xyz" should not match any command
        let suggestions = completion_suggestions(&mut completer, ":xyz", 4);
        assert!(
            suggestions.is_empty(),
            "`:xyz` should not match any command"
        );
    }

    #[test]
    fn test_meta_command_help_no_append_whitespace() {
        // :help and :h should NOT append whitespace after completion
        // because they open an interactive help browser (no argument needed)
        let mut completer = MetaCommandCompleter::new();

        let suggestions = completion_suggestions(&mut completer, ":hel", 4);
        let help = suggestions.iter().find(|s| s.value == "help").unwrap();
        assert!(
            !help.append_whitespace,
            "`:help` should NOT append whitespace"
        );

        let suggestions = completion_suggestions(&mut completer, ":h", 2);
        let h = suggestions.iter().find(|s| s.value == "h").unwrap();
        assert!(!h.append_whitespace, "`:h` should NOT append whitespace");
    }

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

    #[test]
    fn test_meta_cd_completes_directories() {
        let _guard = crate::test_utils::lock_cwd();
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir(tmp.path().join("subdir")).unwrap();
        std::fs::File::create(tmp.path().join("file.txt")).unwrap();
        std::env::set_current_dir(tmp.path()).unwrap();

        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":cd ", 4);

        // Should only contain directories (directories_only: true)
        assert!(!suggestions.is_empty(), "Should have directory completions");
        for s in &suggestions {
            assert!(
                s.value.ends_with('/'),
                "cd completion should only show directories, got: {}",
                s.value
            );
        }
        assert!(
            suggestions.iter().any(|s| s.value == "subdir/"),
            "Should contain subdir/"
        );
        assert!(
            !suggestions.iter().any(|s| s.value == "file.txt"),
            "Should not contain files"
        );
    }

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

        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":cd su", 6);

        assert!(
            suggestions.iter().any(|s| s.value == "subdir/"),
            "Should fuzzy-match subdir/, got: {:?}",
            suggestions.iter().map(|s| &s.value).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_meta_pushd_completes_directories() {
        let _guard = crate::test_utils::lock_cwd();
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir(tmp.path().join("mydir")).unwrap();
        std::env::set_current_dir(tmp.path()).unwrap();

        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":pushd ", 7);

        assert!(
            suggestions.iter().any(|s| s.value == "mydir/"),
            "Should contain mydir/"
        );
    }

    #[test]
    fn test_meta_popd_no_completion() {
        // ":popd " should NOT show path completions (takes no argument)
        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":popd ", 6);
        assert!(
            suggestions.is_empty(),
            "popd should not have completions, got: {:?}",
            suggestions.iter().map(|s| &s.value).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_meta_cd_nested_path() {
        let _guard = crate::test_utils::lock_cwd();
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir(&src).unwrap();
        std::fs::create_dir(src.join("inner")).unwrap();
        std::env::set_current_dir(tmp.path()).unwrap();

        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":cd src/", 8);

        assert!(
            suggestions.iter().any(|s| s.value == "src/inner/"),
            "Should list src/inner/, got: {:?}",
            suggestions.iter().map(|s| &s.value).collect::<Vec<_>>()
        );
    }

    // --- :switch! / :restart! completion tests ---

    #[test]
    fn test_meta_command_switch_bang_appears_in_completions() {
        let mut completer = MetaCommandCompleter::new();
        // ":sw" should fuzzy match both "switch" and "switch!"
        let suggestions = completion_suggestions(&mut completer, ":sw", 3);
        let values: Vec<&str> = suggestions.iter().map(|s| s.value.as_str()).collect();
        assert!(values.contains(&"switch"), "should match :switch");
        assert!(values.contains(&"switch!"), "should match :switch!");

        // Both should append whitespace (they take arguments)
        let switch_bang = suggestions.iter().find(|s| s.value == "switch!").unwrap();
        assert!(
            switch_bang.append_whitespace,
            ":switch! should append whitespace because it takes an argument"
        );
    }

    #[test]
    fn test_meta_command_restart_bang_appears_in_completions() {
        let mut completer = MetaCommandCompleter::new();
        // ":restart" should fuzzy match both "restart" and "restart!"
        let suggestions = completion_suggestions(&mut completer, ":restart", 8);
        let values: Vec<&str> = suggestions.iter().map(|s| s.value.as_str()).collect();
        assert!(values.contains(&"restart"), "should match :restart");
        assert!(values.contains(&"restart!"), "should match :restart!");

        // restart! should NOT append whitespace (it takes no argument)
        let restart_bang = suggestions.iter().find(|s| s.value == "restart!").unwrap();
        assert!(
            !restart_bang.append_whitespace,
            ":restart! should NOT append whitespace"
        );
    }

    #[test]
    fn test_meta_command_switch_bang_subcommand_completion() {
        // ":switch! " should enter the version completion branch (same as ":switch ")
        // Without rig installed, both return empty, but the key thing is they take
        // the same code path (not falling through to the default empty vec).
        let mut completer = MetaCommandCompleter::new();
        let switch_suggestions = completion_suggestions(&mut completer, ":switch ", 8);
        let switch_bang_suggestions = completion_suggestions(&mut completer, ":switch! ", 9);
        assert_eq!(
            switch_suggestions.len(),
            switch_bang_suggestions.len(),
            ":switch! should produce the same version completions as :switch"
        );

        // Partial version input should also work
        let switch_partial = completion_suggestions(&mut completer, ":switch 4", 9);
        let switch_bang_partial = completion_suggestions(&mut completer, ":switch! 4", 10);
        assert_eq!(
            switch_partial.len(),
            switch_bang_partial.len(),
            ":switch! with partial version should match :switch"
        );
    }

    #[test]
    fn test_meta_command_reprex_format_subcommand() {
        // ":reprex " offers all supported subcommands.
        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":reprex ", 8);
        assert_eq!(
            suggestions
                .iter()
                .map(|s| s.value.as_str())
                .collect::<Vec<_>>(),
            ["on", "off", "format"]
        );
    }

    #[test]
    fn test_meta_command_history_bang_no_subcommands() {
        // ":history! " should NOT offer history subcommands (history! is not a valid command)
        let mut completer = MetaCommandCompleter::new();
        let suggestions = completion_suggestions(&mut completer, ":history! ", 10);
        assert!(
            suggestions.is_empty(),
            ":history! should not offer subcommands, got: {:?}",
            suggestions.iter().map(|s| &s.value).collect::<Vec<_>>()
        );
    }
}