arf-console 0.5.1

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
//! Experimental features configuration.

use nu_ansi_term::Color;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;

/// A provider for resolving an R installation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "kebab-case")]
pub enum RSourceOverride {
    /// Resolve R using the active pixi environment.
    Pixi,
    /// Read the R version from a version file.
    VersionFile { file: PathBuf },
    /// Read the R version from a TOML key.
    TomlKey { file: PathBuf, key: String },
    /// Read the R version from a JSON key.
    JsonKey { file: PathBuf, key: String },
}

/// Experimental features configuration.
///
/// Features in this section are subject to change or removal.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct ExperimentalConfig {
    /// Sponge-like automatic removal of failed commands from history.
    ///
    /// Similar to fish's sponge plugin, this feature removes commands that
    /// produced errors from the history after a configurable delay.
    #[serde(default)]
    pub history_forget: HistoryForgetConfig,

    /// Minimum characters to trigger automatic completion display.
    ///
    /// When set, the completion menu appears automatically after typing
    /// this many characters, without requiring a Tab key press.
    /// This is similar to radian's `complete_while_typing` feature.
    ///
    /// When not set (null/omitted), completion requires Tab key press
    /// (the default behavior).
    #[serde(default)]
    pub completion_min_chars: Option<usize>,

    /// Spinner configuration for busy indicator during R execution.
    #[serde(default)]
    pub prompt_spinner: SpinnerConfig,

    /// Command duration configuration for the `{duration}` prompt placeholder.
    #[serde(default)]
    pub prompt_duration: PromptDurationConfig,

    /// R code completion configuration (fuzzy matching, package functions).
    #[serde(default)]
    pub r_completion: RCompletionConfig,

    /// Shell mode completion configuration.
    #[serde(default)]
    pub shell_completion: ShellCompletionConfig,

    /// Enable `;` as a shortcut to switch to shell mode.
    ///
    /// When enabled, pressing `;` at an empty R prompt instantly switches to
    /// shell mode without requiring Enter — similar to Julia REPL behavior.
    /// When the buffer is not empty, `;` inserts a semicolon as usual.
    ///
    /// Disabled by default.
    #[serde(default)]
    pub shell_semicolon_shortcut: bool,

    /// Fish-style abbreviations for shell mode.
    ///
    /// Abbreviations are expanded automatically when you press Space or Enter.
    /// Only applies to the shell editor (not the R editor).
    ///
    /// Format: `"abbreviation" = "expansion"`
    /// Example: `"gc" = "git commit"`
    #[serde(default)]
    pub shell_abbreviations: BTreeMap<String, String>,

    /// Ordered providers for experimental R source resolution.
    #[serde(default)]
    pub r_source_overrides: Vec<RSourceOverride>,
}

/// Configuration for shell mode completion.
///
/// Controls what is suggested when Tab is pressed in shell mode.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct ShellCompletionConfig {
    /// Enable completion of executable command names from PATH.
    ///
    /// When enabled, pressing Tab at the start of a shell command suggests
    /// executable names found in PATH directories in addition to path completions.
    /// When disabled (default), only file/directory path completion is provided.
    pub command_names: bool,
}

/// Configuration for R code completion (namespace and library fuzzy matching).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct RCompletionConfig {
    /// Enable fuzzy matching for R code completions.
    ///
    /// When enabled, typing `pkg::partial` uses fuzzy matching against all
    /// exported names from the package, so `sf::geo` can match `sf::st_geometry`.
    /// Also enables fuzzy matching for `library()`/`require()` package names.
    /// When disabled (default), only R's built-in prefix matching is used.
    pub fuzzy: bool,

    /// Function names that trigger package-name completion.
    ///
    /// When fuzzy matching is enabled, typing inside a call to one of these
    /// functions will complete against installed package names.
    /// Default: `["library", "require"]`.
    /// Users can add custom functions like `"box::use"`.
    #[serde(default = "default_package_functions")]
    pub package_functions: Vec<String>,
}

fn default_package_functions() -> Vec<String> {
    vec!["library".to_string(), "require".to_string()]
}

impl Default for RCompletionConfig {
    fn default() -> Self {
        Self {
            fuzzy: false,
            package_functions: default_package_functions(),
        }
    }
}

/// Schema-only version of `SpinnerConfig` that avoids depending on `nu_ansi_term::Color`.
///
/// This type is used solely for JSON Schema generation, so that we can still
/// provide a helpful schema while `Color` does not implement `JsonSchema`.
/// The `color` field uses a manual schema via `color_prop!` for proper oneOf typing.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
struct SpinnerConfigSchema {
    /// Spinner animation frames as a string where each character is one frame.
    /// Empty string disables the spinner.
    ///
    /// Example: `frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"` (braille dots)
    /// Example: `frames = "|/-\\"` (ASCII spinner)
    pub frames: String,

    /// Color for the spinner.
    pub color: String,
}

impl Default for SpinnerConfigSchema {
    fn default() -> Self {
        SpinnerConfigSchema {
            frames: String::new(),
            color: "Cyan".to_string(),
        }
    }
}

// Manual JsonSchema for SpinnerConfigSchema to use proper color oneOf schema.
impl JsonSchema for SpinnerConfigSchema {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("SpinnerConfigSchema")
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        use super::colors::color_prop;
        schemars::json_schema!({
            "type": "object",
            "description": "Spinner configuration for busy indicator during R execution.",
            "properties": {
                "frames": {
                    "type": "string",
                    "description": "Spinner animation frames as a string where each character is one frame. Empty string disables the spinner. Example: \"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏\" (braille dots), \"|/-\\\\\" (ASCII spinner).",
                    "default": ""
                },
                "color": color_prop!("Color for the spinner.", default = "Cyan")
            }
        })
    }
}

/// Schema-only mirror of `ExperimentalConfig` that can derive `JsonSchema`.
///
/// This allows `schemars` to auto-generate detailed metadata (defaults,
/// numeric formats, minimum values, and full documentation), which would
/// otherwise be lost in a fully manual `JsonSchema` implementation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
#[derive(Default)]
struct ExperimentalConfigSchema {
    /// Sponge-like automatic removal of failed commands from history.
    ///
    /// Similar to fish's sponge plugin, this feature removes commands that
    /// produced errors from the history after a configurable delay.
    pub history_forget: HistoryForgetConfig,

    /// Minimum characters to trigger automatic completion display.
    ///
    /// When set, the completion menu appears automatically after typing
    /// this many characters, without requiring a Tab key press.
    /// This is similar to radian's `complete_while_typing` feature.
    ///
    /// When not set (null/omitted), completion requires Tab key press
    /// (the default behavior).
    pub completion_min_chars: Option<usize>,

    /// Spinner configuration for busy indicator during R execution.
    pub prompt_spinner: SpinnerConfigSchema,

    /// Command duration configuration for the `{duration}` prompt placeholder.
    pub prompt_duration: PromptDurationConfig,

    /// R code completion configuration (fuzzy matching, package functions).
    pub r_completion: RCompletionConfig,

    /// Shell mode completion configuration.
    pub shell_completion: ShellCompletionConfig,

    /// Enable `;` as a shortcut to switch to shell mode.
    ///
    /// When enabled, pressing `;` at an empty R prompt instantly switches to
    /// shell mode without requiring Enter — similar to Julia REPL behavior.
    /// When the buffer is not empty, `;` inserts a semicolon as usual.
    ///
    /// Disabled by default.
    pub shell_semicolon_shortcut: bool,

    /// Fish-style abbreviations for shell mode.
    ///
    /// Abbreviations are expanded automatically when you press Space or Enter.
    /// Only applies to the shell editor (not the R editor).
    ///
    /// Format: `"abbreviation" = "expansion"`
    /// Example: `"gc" = "git commit"`
    pub shell_abbreviations: BTreeMap<String, String>,

    /// Ordered providers for experimental R source resolution.
    pub r_source_overrides: Vec<RSourceOverride>,
}

// Manual JsonSchema implementation for ExperimentalConfig since nu_ansi_term::Color
// doesn't implement JsonSchema. We delegate to a schema-only mirror type so that
// schemars can still auto-generate rich metadata (defaults, formats, etc.).
impl JsonSchema for ExperimentalConfig {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("ExperimentalConfig")
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        generator.subschema_for::<ExperimentalConfigSchema>()
    }
}

/// Configuration for automatic removal of failed commands from history.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct HistoryForgetConfig {
    /// Enable automatic removal of failed commands.
    pub enabled: bool,

    /// Number of failed commands to keep before purging older ones.
    /// For example, with delay = 2, the last 2 failed commands are kept
    /// accessible for quick retry, while older ones are deleted.
    pub delay: usize,

    /// If true, only purge failed commands when the session ends.
    /// If false, purge on each prompt redraw.
    pub on_exit_only: bool,
}

impl Default for HistoryForgetConfig {
    fn default() -> Self {
        HistoryForgetConfig {
            enabled: false,
            delay: 2,
            on_exit_only: false,
        }
    }
}

/// Command duration configuration for the `{duration}` prompt placeholder.
///
/// Controls when and how command execution time is displayed in the prompt.
/// Only displayed when the command took longer than `threshold_ms`.
///
/// The `format` field uses `{value}` as a sub-placeholder for the time string.
/// The entire format string is conditionally displayed: when the duration exceeds
/// `threshold_ms`, `{value}` is replaced with the time string (e.g., "5s");
/// when below threshold, the `{duration}` prompt placeholder becomes empty.
///
/// Time format follows starship convention: "5s", "1m30s", "2h48m30s"
/// (no spaces between units, leading zero units skipped).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct PromptDurationConfig {
    /// Format string for the duration display.
    ///
    /// Use `{value}` as a sub-placeholder for the time string (e.g., "5s").
    /// If `{value}` is omitted, only the static text in the format is shown.
    ///
    /// Examples:
    /// - `"{value} "` (default) — "5s " after a 5-second command
    /// - `"took {value} "` — "took 5s "
    /// - `"({value}) "` — "(5s) "
    #[serde(default = "default_duration_format")]
    pub format: String,

    /// Minimum duration in milliseconds before showing duration (default: 2000).
    /// Commands faster than this threshold will not show duration.
    #[serde(default = "default_duration_threshold_ms")]
    pub threshold_ms: u64,
}

fn default_duration_format() -> String {
    "{value} ".to_string()
}

fn default_duration_threshold_ms() -> u64 {
    2000
}

impl Default for PromptDurationConfig {
    fn default() -> Self {
        Self {
            format: default_duration_format(),
            threshold_ms: default_duration_threshold_ms(),
        }
    }
}

/// Spinner configuration for showing activity during R code execution.
///
/// The spinner is displayed at the start of the line while R is evaluating code,
/// providing visual feedback that the system is busy.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SpinnerConfig {
    /// Spinner animation frames as a string where each character is one frame.
    /// Empty string disables the spinner.
    ///
    /// Example: `frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"` (braille dots)
    /// Example: `frames = "|/-\\"` (ASCII spinner)
    #[serde(default = "default_spinner_frames")]
    pub frames: String,

    /// Color for the spinner.
    #[serde(default = "default_spinner_color")]
    pub color: Color,
}

fn default_spinner_frames() -> String {
    String::new() // Disabled by default (experimental feature)
}

fn default_spinner_color() -> Color {
    Color::Cyan
}

impl Default for SpinnerConfig {
    fn default() -> Self {
        Self {
            frames: default_spinner_frames(),
            color: default_spinner_color(),
        }
    }
}

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

    #[test]
    fn test_spinner_config_default() {
        let config = SpinnerConfig::default();
        assert!(config.frames.is_empty()); // Disabled by default
        assert_eq!(config.color, Color::Cyan);
    }

    #[test]
    fn test_spinner_config_disabled() {
        let config = SpinnerConfig {
            frames: String::new(),
            color: Color::Default,
        };
        assert!(config.frames.is_empty());
    }

    #[test]
    fn test_spinner_config_custom_frames() {
        let config = SpinnerConfig {
            frames: "|/-\\".to_string(),
            color: Color::Green,
        };
        assert_eq!(config.frames, "|/-\\");
        assert_eq!(config.color, Color::Green);
    }

    #[test]
    fn test_experimental_config_default() {
        let config = ExperimentalConfig::default();
        assert!(!config.history_forget.enabled);
        assert!(config.completion_min_chars.is_none());
        assert!(config.prompt_spinner.frames.is_empty()); // Disabled by default
        assert!(!config.r_completion.fuzzy); // Disabled by default
        assert_eq!(
            config.r_completion.package_functions,
            vec!["library".to_string(), "require".to_string()]
        );
        assert!(!config.shell_completion.command_names); // Disabled by default
        assert!(config.r_source_overrides.is_empty());
    }

    #[test]
    fn test_parse_spinner_config() {
        let toml_str = r#"
[experimental.prompt_spinner]
frames = "abc"
color = "Red"
"#;
        let config: crate::config::Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.experimental.prompt_spinner.frames, "abc");
        assert_eq!(config.experimental.prompt_spinner.color, Color::Red);
    }

    #[test]
    fn test_parse_spinner_disabled() {
        let toml_str = r#"
[experimental.prompt_spinner]
frames = ""
"#;
        let config: crate::config::Config = toml::from_str(toml_str).unwrap();
        assert!(config.experimental.prompt_spinner.frames.is_empty());
    }

    #[test]
    fn test_r_completion_default() {
        let config = RCompletionConfig::default();
        assert!(!config.fuzzy);
        assert_eq!(
            config.package_functions,
            vec!["library".to_string(), "require".to_string()]
        );
    }

    #[test]
    fn test_parse_r_completion() {
        let toml_str = r#"
[experimental.r_completion]
fuzzy = true
package_functions = ["library", "require", "box::use"]
"#;
        let config: crate::config::Config = toml::from_str(toml_str).unwrap();
        assert!(config.experimental.r_completion.fuzzy);
        assert_eq!(
            config.experimental.r_completion.package_functions,
            vec![
                "library".to_string(),
                "require".to_string(),
                "box::use".to_string()
            ]
        );
    }

    #[test]
    fn test_parse_r_completion_fuzzy_only() {
        // When only fuzzy is specified, package_functions should use defaults
        let toml_str = r#"
[experimental.r_completion]
fuzzy = true
"#;
        let config: crate::config::Config = toml::from_str(toml_str).unwrap();
        assert!(config.experimental.r_completion.fuzzy);
        assert_eq!(
            config.experimental.r_completion.package_functions,
            vec!["library".to_string(), "require".to_string()]
        );
    }

    #[test]
    fn test_shell_completion_default() {
        let config = ShellCompletionConfig::default();
        assert!(!config.command_names);
    }

    #[test]
    fn test_parse_shell_completion() {
        let toml_str = r#"
[experimental.shell_completion]
command_names = true
"#;
        let config: crate::config::Config = toml::from_str(toml_str).unwrap();
        assert!(config.experimental.shell_completion.command_names);
    }

    #[test]
    fn test_shell_semicolon_shortcut_default() {
        let config = ExperimentalConfig::default();
        assert!(!config.shell_semicolon_shortcut);
    }

    #[test]
    fn test_parse_shell_semicolon_shortcut() {
        let toml_str = r#"
[experimental]
shell_semicolon_shortcut = true
"#;
        let config: crate::config::Config = toml::from_str(toml_str).unwrap();
        assert!(config.experimental.shell_semicolon_shortcut);
    }

    #[test]
    fn test_parse_r_source_overrides() {
        let toml_str = r#"
[experimental]
r_source_overrides = [
  { type = "toml-key", file = "rproject.toml", key = "project.r_version" },
  { type = "json-key", file = "renv.lock", key = "R.Version" },
  { type = "version-file", file = ".r-version" },
  { type = "pixi" },
]
"#;
        let config: crate::config::Config = toml::from_str(toml_str).unwrap();

        assert!(matches!(
            &config.experimental.r_source_overrides[0],
            RSourceOverride::TomlKey { file, key }
                if file == &PathBuf::from("rproject.toml") && key == "project.r_version"
        ));
        assert!(matches!(
            &config.experimental.r_source_overrides[1],
            RSourceOverride::JsonKey { file, key }
                if file == &PathBuf::from("renv.lock") && key == "R.Version"
        ));
        assert!(matches!(
            &config.experimental.r_source_overrides[2],
            RSourceOverride::VersionFile { file } if file == &PathBuf::from(".r-version")
        ));
        assert!(matches!(
            config.experimental.r_source_overrides[3],
            RSourceOverride::Pixi
        ));
    }

    #[test]
    fn test_parse_r_source_override_unknown_type_fails() {
        let toml_str = r#"
[experimental]
r_source_overrides = [{ type = "unknown-thing" }]
"#;
        let result: Result<crate::config::Config, _> = toml::from_str(toml_str);
        let error = result.expect_err("unknown R source override types should fail");
        assert!(error.to_string().contains("unknown variant"));
    }

    #[test]
    fn test_parse_existing_config_without_r_source_overrides() {
        let toml_str = r#"
[startup]
show_banner = false
"#;
        let config: crate::config::Config = toml::from_str(toml_str).unwrap();
        assert!(!config.startup.show_banner);
        assert!(config.experimental.r_source_overrides.is_empty());
    }
}