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
//! REPL state management.
use crate::config::{
ConfigFileInfo, HistoryForgetConfig, Indicators, ModeIndicatorPosition, PromptDurationConfig,
RSourceStatus, ReprexMode, ResolvedHistoryLocation, SpinnerConfig, StatusColorConfig,
StatusConfig, ViColorConfig, ViConfig,
};
use crate::editor::prompt::PromptFormatter;
use nu_ansi_term::Color;
use reedline::{HistoryItemId, HistorySessionId, Reedline};
use std::path::PathBuf;
use std::time::{Duration, Instant};
mod sponge;
#[cfg(test)]
mod sponge_tests;
pub use sponge::SpongeQueue;
use super::prompt::RPrompt;
use super::reprex::ReprexRuntime;
/// Identifies which history entry should receive the result of the command
/// that just finished evaluating.
///
/// Both interactive and IPC entries carry their database row explicitly. This
/// avoids reedline's mutable "last run" slot, which is overwritten by every
/// Enter-save, including entries created by menu prompts.
#[derive(Default)]
pub enum PendingHistoryContext {
/// The command whose evaluation just completed, if it was persisted.
Command {
store: Option<crate::history::HistoryStore>,
history_id: Option<HistoryItemId>,
},
/// No command needs a history context update.
#[default]
None,
}
/// Convert nu_ansi_term::Color to ANSI escape code string.
fn color_to_ansi_code(color: Color) -> String {
use nu_ansi_term::Style;
match color {
Color::Default => String::new(),
c => {
let style = Style::new().fg(c);
// Get just the prefix (start code) without the suffix
style.prefix().to_string()
}
}
}
/// State shared between the REPL and the ReadConsole callback.
pub struct ReplState {
/// Line editor for R mode.
pub line_editor: Reedline,
/// Line editor for shell mode (with separate history).
pub shell_line_editor: Reedline,
pub prompt_config: PromptRuntimeConfig,
pub reprex: ReprexRuntime,
pub should_exit: bool,
/// Whether the previous ReadConsole invocation had identical R prompt options.
pub r_prompt_options_ambiguous: bool,
/// Config file path, load status, and source (for :info command).
pub config_file_info: ConfigFileInfo,
/// How R was resolved at startup (for :info display and :switch gating).
pub r_source_status: RSourceStatus,
/// R_HOME reported by the running R at startup, if R initialized successfully.
pub r_home: Option<PathBuf>,
/// Effective persistent/volatile history location resolved at REPL startup.
pub history_location: ResolvedHistoryLocation,
/// Configuration for the sponge-like "forget failed commands" feature.
pub forget_config: HistoryForgetConfig,
/// Queue for the sponge feature (tracks commands to potentially delete).
pub sponge_queue: SpongeQueue,
/// Directory stack for :pushd/:popd navigation.
pub dir_stack: Vec<PathBuf>,
/// History session ID for R history entries and IPC metadata.
pub history_session_id: Option<HistorySessionId>,
/// R history store and adapter save receipt for the active runtime.
pub r_history: crate::history::HistoryRuntime,
/// Shell history store and adapter save receipt for the active runtime.
pub shell_history: crate::history::HistoryRuntime,
/// History context for the command whose evaluation just completed.
pub pending_history_context: PendingHistoryContext,
/// Whether initial R error-handler setup has been attempted after R startup.
pub error_handler_setup_attempted: bool,
}
/// Runtime configuration for prompts that can be modified during the session.
pub struct PromptRuntimeConfig {
/// Prompt formatter for expanding placeholders.
prompt_formatter: PromptFormatter,
/// Main prompt template (unexpanded, e.g., "{status}R {version}> ").
main_template: String,
/// Continuation prompt template (unexpanded).
continuation_template: String,
/// Shell mode prompt template (unexpanded, e.g., "[{shell}] $ ").
shell_template: String,
mode_indicator_position: ModeIndicatorPosition,
indicators: Indicators,
/// Shell mode enabled (input goes to system shell instead of R).
shell_enabled: bool,
/// Color for the main R prompt.
main_color: Color,
/// Color for the continuation prompt.
continuation_color: Color,
/// Color for the shell prompt.
shell_color: Color,
/// Color for mode indicators.
mode_indicator_color: Color,
/// Command status indicator configuration.
status_config: StatusConfig,
/// Colors for command status indicator.
status_colors: StatusColorConfig,
/// Last command outcome: `Some(true)` is failure, `Some(false)` is success,
/// and `None` means the outcome could not be observed reliably.
last_command_failed: Option<bool>,
/// Command duration configuration (format and threshold).
duration_config: PromptDurationConfig,
/// Color for command duration indicator.
duration_color: Color,
/// When the last command started executing.
last_command_start: Option<Instant>,
/// How long the last command took to execute.
last_command_duration: Option<Duration>,
/// Spinner configuration for busy indicator.
spinner_config: SpinnerConfig,
/// Vi mode configuration (symbols).
vi_config: ViConfig,
/// Vi mode colors for prompt indicator.
vi_colors: ViColorConfig,
}
impl PromptRuntimeConfig {
/// Create a builder for `PromptRuntimeConfig`.
///
/// Required parameters are the prompt formatter and template strings.
/// All other fields default to sensible values and can be set via builder methods.
pub fn builder(
prompt_formatter: PromptFormatter,
main_template: impl Into<String>,
continuation_template: impl Into<String>,
shell_template: impl Into<String>,
) -> PromptRuntimeConfigBuilder {
PromptRuntimeConfigBuilder::new(
prompt_formatter,
main_template,
continuation_template,
shell_template,
)
}
pub fn build_main_prompt(&self, reprex_mode: ReprexMode) -> RPrompt {
if self.shell_enabled {
// In shell mode, use shell_template as the main prompt (no mode indicator)
// Expand placeholders (including {cwd}) dynamically each time
let shell_format = self.prompt_formatter.format(&self.shell_template);
let cont_format = self.prompt_formatter.format(&self.continuation_template);
RPrompt::new(shell_format, cont_format)
.with_colors(
self.shell_color,
self.continuation_color,
self.mode_indicator_color,
)
.with_vi_symbol(self.vi_config.symbol.clone())
.with_vi_colors(self.vi_colors.clone())
} else {
// In R mode, use main_template with optional mode indicator
// Expand placeholders (including {cwd}) dynamically each time
let main_format = self.prompt_formatter.format(&self.main_template);
let cont_format = self.prompt_formatter.format(&self.continuation_template);
let mode_indicator = self.current_mode_indicator(reprex_mode);
// Determine prompt color based on status mode
let prompt_color = self.get_status_prompt_color();
// Expand {status} placeholder, passing prompt_color to restore after symbol
let main_format = self.expand_status_placeholder(&main_format, prompt_color);
// Expand {duration} placeholder for command execution time
let main_format = self.expand_duration_placeholder(&main_format, prompt_color);
RPrompt::new(main_format, cont_format)
.with_mode_indicator(mode_indicator, self.mode_indicator_position)
.with_colors(
prompt_color,
self.continuation_color,
self.mode_indicator_color,
)
.with_vi_symbol(self.vi_config.symbol.clone())
.with_vi_colors(self.vi_colors.clone())
}
}
/// Expand the {status} placeholder based on status config and last command result.
///
/// The symbol is colored with the status color.
/// After the symbol, the prompt_color is applied to ensure the rest of the prompt
/// maintains its color (otherwise the symbol's ANSI reset would clear all colors).
fn expand_status_placeholder(&self, template: &str, prompt_color: Color) -> String {
use nu_ansi_term::Style;
if !template.contains("{status}") {
return template.to_string();
}
let symbol = match self.last_command_failed {
Some(true) => &self.status_config.symbol.error,
Some(false) => &self.status_config.symbol.success,
None => "",
};
let colored_symbol = if symbol.is_empty() {
String::new()
} else {
// Color the symbol with status color
let status_color = match self.last_command_failed {
Some(true) => self.status_colors.error,
Some(false) => self.status_colors.success,
None => return template.replace("{status}", ""),
};
let status_style = match status_color {
Color::Default => Style::new(),
c => Style::new().fg(c),
};
// After the symbol, apply prompt_color so the rest of the prompt
// maintains its color (prefix() doesn't add reset at end)
let prompt_style = match prompt_color {
Color::Default => Style::new(),
c => Style::new().fg(c),
};
format!("{}{}", status_style.paint(symbol), prompt_style.prefix())
};
template.replace("{status}", &colored_symbol)
}
/// Get the prompt color based on status config.
///
/// When `override_prompt_color` is true, returns status-based color.
/// Otherwise, returns the normal main prompt color.
fn get_status_prompt_color(&self) -> Color {
if self.status_config.override_prompt_color {
match self.last_command_failed {
Some(true) => self.status_colors.error,
Some(false) => self.status_colors.success,
None => self.main_color,
}
} else {
self.main_color
}
}
/// Set whether the last command failed.
pub fn set_last_command_failed(&mut self, failed: bool) {
self.last_command_failed = Some(failed);
}
/// Clear the status when the last command outcome could not be observed.
pub fn set_last_command_outcome_unknown(&mut self) {
self.last_command_failed = None;
}
/// Record the start time of a command execution.
pub fn set_command_start(&mut self) {
self.last_command_start = Some(Instant::now());
}
/// Calculate and store the duration since the last command start.
///
/// Should be called when R returns to the command prompt (alongside `set_last_command_failed`).
pub fn set_command_duration(&mut self) {
self.last_command_duration = self.last_command_start.take().map(|start| start.elapsed());
}
/// Clear the stored command duration.
///
/// Should be called when a meta command is executed so that the previous
/// R command's duration does not persist in the prompt.
pub fn clear_command_duration(&mut self) {
self.last_command_duration = None;
}
/// Expand the {duration} placeholder based on duration config and last command duration.
///
/// Shows the duration only when it exceeds the configured threshold.
/// The format string from config is used to wrap the time value (e.g., "{value} " → "5s ").
/// The formatted text is colored with the duration color.
/// After the text, the prompt_color is restored so the rest of the prompt keeps its color.
fn expand_duration_placeholder(&self, template: &str, prompt_color: Color) -> String {
use nu_ansi_term::Style;
if !template.contains("{duration}") {
return template.to_string();
}
let duration_str = match self.last_command_duration {
Some(duration)
if duration.as_millis() >= u128::from(self.duration_config.threshold_ms) =>
{
let time_str = render_time(duration);
// Apply format string: replace {value} with the time string
let formatted = self.duration_config.format.replace("{value}", &time_str);
let duration_style = match self.duration_color {
Color::Default => Style::new(),
c => Style::new().fg(c),
};
let prompt_style = match prompt_color {
Color::Default => Style::new(),
c => Style::new().fg(c),
};
format!(
"{}{}",
duration_style.paint(&formatted),
prompt_style.prefix()
)
}
_ => String::new(),
};
template.replace("{duration}", &duration_str)
}
pub fn build_cont_prompt(&self, reprex_mode: ReprexMode) -> RPrompt {
let cont_format = self.prompt_formatter.format(&self.continuation_template);
let mode_indicator = self.current_mode_indicator(reprex_mode);
RPrompt::new(cont_format.clone(), cont_format)
.with_mode_indicator(mode_indicator, self.mode_indicator_position)
.with_colors(
self.continuation_color,
self.continuation_color,
self.mode_indicator_color,
)
}
fn current_mode_indicator(&self, reprex_mode: ReprexMode) -> Option<String> {
if self.mode_indicator_position == ModeIndicatorPosition::None {
return None;
}
// Note: shell mode uses shell_format directly, so no indicator here
match reprex_mode {
ReprexMode::Off => None,
ReprexMode::On => Some(self.indicators.reprex.clone()),
ReprexMode::Format => Some(self.indicators.reprex_format.clone()),
}
}
pub fn is_shell_enabled(&self) -> bool {
self.shell_enabled
}
pub fn set_shell(&mut self, enabled: bool) {
self.shell_enabled = enabled;
crate::ipc::set_in_alternate_mode(enabled);
}
/// Start the spinner if enabled and not in shell mode.
///
/// The spinner provides visual feedback that R is evaluating code.
/// It is automatically stopped when R produces output or the next prompt appears.
pub fn start_spinner(&self) {
// Don't show spinner in shell mode (shell commands have their own feedback)
if self.shell_enabled {
return;
}
// Don't show spinner if frames are empty (disabled)
if self.spinner_config.frames.is_empty() {
return;
}
arf_libr::start_spinner();
}
}
/// Format a duration into a human-readable string (starship-style).
///
/// Examples:
/// - 800ms → "800ms"
/// - 5.2s → "5s"
/// - 90s → "1m30s"
/// - 3661s → "1h1m1s"
/// - 86400s → "1d0h0m0s"
///
/// For durations under 1 second, milliseconds are shown (e.g., "800ms").
/// For longer durations, leading zero units are skipped, but once a non-zero unit
/// appears, all subsequent units are included (even if zero).
fn render_time(duration: Duration) -> String {
let total_secs = duration.as_secs();
// Show milliseconds for sub-second durations to avoid confusing "0s"
if total_secs == 0 {
return format!("{}ms", duration.as_millis());
}
let days = total_secs / 86400;
let hours = (total_secs % 86400) / 3600;
let minutes = (total_secs % 3600) / 60;
let seconds = total_secs % 60;
let mut result = String::new();
let mut started = false;
if days > 0 {
result.push_str(&format!("{}d", days));
started = true;
}
if started || hours > 0 {
result.push_str(&format!("{}h", hours));
started = true;
}
if started || minutes > 0 {
result.push_str(&format!("{}m", minutes));
}
result.push_str(&format!("{}s", seconds));
result
}
/// Builder for [`PromptRuntimeConfig`].
///
/// Created via [`PromptRuntimeConfig::builder()`]. Only the prompt formatter
/// and template strings are required; all other fields have sensible defaults.
pub struct PromptRuntimeConfigBuilder {
prompt_formatter: PromptFormatter,
main_template: String,
continuation_template: String,
shell_template: String,
mode_indicator_position: ModeIndicatorPosition,
indicators: Indicators,
main_color: Color,
continuation_color: Color,
shell_color: Color,
mode_indicator_color: Color,
status_config: StatusConfig,
status_colors: StatusColorConfig,
duration_config: PromptDurationConfig,
duration_color: Color,
spinner_config: SpinnerConfig,
vi_config: ViConfig,
vi_colors: ViColorConfig,
}
impl PromptRuntimeConfigBuilder {
fn new(
prompt_formatter: PromptFormatter,
main_template: impl Into<String>,
continuation_template: impl Into<String>,
shell_template: impl Into<String>,
) -> Self {
Self {
prompt_formatter,
main_template: main_template.into(),
continuation_template: continuation_template.into(),
shell_template: shell_template.into(),
mode_indicator_position: ModeIndicatorPosition::default(),
indicators: Indicators::default(),
main_color: Color::Default,
continuation_color: Color::Default,
shell_color: Color::Default,
mode_indicator_color: Color::Default,
status_config: StatusConfig::default(),
status_colors: StatusColorConfig::default(),
duration_config: PromptDurationConfig::default(),
duration_color: Color::Default,
spinner_config: SpinnerConfig::default(),
vi_config: ViConfig::default(),
vi_colors: ViColorConfig::default(),
}
}
pub fn mode_indicator_position(mut self, position: ModeIndicatorPosition) -> Self {
self.mode_indicator_position = position;
self
}
pub fn indicators(mut self, indicators: Indicators) -> Self {
self.indicators = indicators;
self
}
pub fn main_color(mut self, color: Color) -> Self {
self.main_color = color;
self
}
pub fn continuation_color(mut self, color: Color) -> Self {
self.continuation_color = color;
self
}
pub fn shell_color(mut self, color: Color) -> Self {
self.shell_color = color;
self
}
pub fn mode_indicator_color(mut self, color: Color) -> Self {
self.mode_indicator_color = color;
self
}
pub fn status(mut self, config: StatusConfig, colors: StatusColorConfig) -> Self {
self.status_config = config;
self.status_colors = colors;
self
}
pub fn duration(mut self, config: PromptDurationConfig, color: Color) -> Self {
self.duration_config = config;
self.duration_color = color;
self
}
pub fn spinner(mut self, config: SpinnerConfig) -> Self {
self.spinner_config = config;
self
}
pub fn vi(mut self, config: ViConfig, colors: ViColorConfig) -> Self {
self.vi_config = config;
self.vi_colors = colors;
self
}
pub fn build(self) -> PromptRuntimeConfig {
// Initialize spinner in arf-libr
arf_libr::set_spinner_frames(&self.spinner_config.frames);
let color_code = color_to_ansi_code(self.spinner_config.color);
arf_libr::set_spinner_color(&color_code);
PromptRuntimeConfig {
prompt_formatter: self.prompt_formatter,
main_template: self.main_template,
continuation_template: self.continuation_template,
shell_template: self.shell_template,
mode_indicator_position: self.mode_indicator_position,
indicators: self.indicators,
shell_enabled: false,
main_color: self.main_color,
continuation_color: self.continuation_color,
shell_color: self.shell_color,
mode_indicator_color: self.mode_indicator_color,
status_config: self.status_config,
status_colors: self.status_colors,
last_command_failed: Some(false),
duration_config: self.duration_config,
duration_color: self.duration_color,
last_command_start: None,
last_command_duration: None,
spinner_config: self.spinner_config,
vi_config: self.vi_config,
vi_colors: self.vi_colors,
}
}
}
#[cfg(test)]
#[path = "state/tests.rs"]
mod tests;