Repository navigation
Expand file tree
/
Copy pathprompt_manager.rs
More file actions
3058 lines (2828 loc) · 117 KB
/
Copy pathprompt_manager.rs
File metadata and controls
3058 lines (2828 loc) · 117 KB
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
#[cfg(test)]
use crate::content::SpanTag;
use crate::content::{Tag, TaggedLine, TaggedSpan};
use crate::kill_on_drop_child::KillOnDropChild;
use crate::settings::{Placeholder, PromptAnimation, PromptWidget, PromptWidgetCustom};
use crate::shell;
use ansi_to_tui::IntoText;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use std::collections::HashMap;
use std::ops::Range;
use std::sync::{Arc, Mutex};
/// An animation whose frames have been processed through
/// [`expand_prompt_through_bash`]. Embedded directly inside
/// [`PromptSegment::Animation`] so that each animation carries its own render
/// logic without requiring a separate lookup table on [`PromptManager`].
#[derive(Debug, Clone)]
struct ProcessedAnimation {
/// The animation name as it appears literally in the raw PS1 string
/// (e.g. `COOL_SPINNER`). Retained for debugging.
name: String,
/// Playback speed in frames per second.
fps: f64,
/// Pre-processed frames. Each frame has been run through
/// [`expand_prompt_through_bash`] so bash prompt escapes (e.g. `\u`, `\w`)
/// and ANSI colour codes are already resolved into [`Span`]s.
frames: Vec<Vec<Span<'static>>>,
/// When true the animation reverses direction at each end instead of
/// wrapping around (ping-pong / bounce mode).
ping_pong: bool,
}
impl ProcessedAnimation {
pub fn patch_style(mut self, style: Style) -> Self {
for frame in &mut self.frames {
for span in frame {
span.style = style.patch(span.style);
}
}
self
}
}
/// State of a running custom widget command.
///
/// Held directly inside `PromptSegment::WidgetCustom`. Each segment is fully
/// independent: the same widget name appearing in PS1 and RPS1 produces two
/// independent segments that each run the command separately.
enum WidgetCustomState {
/// Command is still running (or has not yet been polled).
Pending {
placeholder: Vec<TaggedSpan<'static>>,
child: KillOnDropChild,
/// The command that was spawned, retained for log messages.
command: Vec<String>,
/// Shared storage to write the output into when the command finishes,
/// so that `Placeholder::Prev` can use it on the next render cycle.
prev_output_cell: Arc<Mutex<Vec<TaggedSpan<'static>>>>,
},
/// Command finished successfully; pre-tagged output spans are stored here
/// so that the tag is applied only once rather than on every render.
Done(Vec<TaggedSpan<'static>>),
/// Command exited with a non-zero exit code or could not be spawned.
Failed(WidgetFailure),
}
impl std::fmt::Debug for WidgetCustomState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
WidgetCustomState::Pending { .. } => f.write_str("WidgetCustomState::Pending"),
WidgetCustomState::Done(_) => f.write_str("WidgetCustomState::Done"),
WidgetCustomState::Failed(_) => f.write_str("WidgetCustomState::Failed"),
}
}
}
/// Failure details returned by a custom widget command.
struct WidgetFailure {
exit_code: Option<i32>,
#[allow(dead_code)]
stdout: String,
#[allow(dead_code)]
stderr: String,
}
impl WidgetFailure {
/// Build a set of error [`TaggedSpan`]s that visualise this failure in the
/// prompt. The label is `"command failed (exit N)"` when an exit code is
/// available, or `"command failed"` for spawn errors. The full stdout and
/// stderr are emitted at `debug` level.
fn to_error_spans(&self) -> Vec<TaggedSpan<'static>> {
let style = Style::default()
.fg(Color::Red)
.add_modifier(Modifier::BOLD | Modifier::SLOW_BLINK);
let label = match self.exit_code {
Some(code) => format!("command failed (exit {})", code),
None => "command failed".to_string(),
};
vec![TaggedSpan::new(Span::styled(label, style), Tag::Prompt)]
}
}
/// A segment of a rendered prompt line.
///
/// Prompt strings are parsed into sequences of `PromptSegment`s at
/// construction time. At render time each segment is cheaply converted to a
/// ratatui [`Span`]: static segments are used as-is, dynamic-time segments are
/// formatted with the current wall-clock time, and animation segments render
/// the appropriate frame for the current time.
#[derive(Debug)]
enum PromptSegment {
/// A fully-resolved span (text + style) with no further substitution needed.
Static(Span<'static>),
/// A bash time escape sequence (`\t`, `\T`, `\@`, `\A`, `\D{…}`).
/// Rendered by formatting the current time with the stored chrono
/// format string and applying the span's style.
DynamicTime {
strftime: String,
style: ratatui::style::Style,
},
/// A custom animation. Rendered by selecting the appropriate frame for the
/// current time and emitting its pre-resolved [`Span`]s directly.
///
/// Boxed to keep the `PromptSegment` enum size small.
Animation(Box<ProcessedAnimation>),
/// The detected current-working-directory substring in the prompt.
/// Holds one span per path segment, where each segment owns the slash
/// to its left. E.g. `~/foo/bar` is stored as `["~", "/foo", "/bar"]`.
/// At render time the spans are emitted in order with per-segment tags.
Cwd(Vec<Span<'static>>),
/// A mouse-mode widget. Rendered as `enabled_text` when mouse capture is
/// active, otherwise `disabled_text`.
///
/// Both texts are stored as pre-tagged [`TaggedSpan`]s so that the tag is
/// applied once at construction rather than on every render.
WidgetMouseMode {
enabled_text: Vec<TaggedSpan<'static>>,
disabled_text: Vec<TaggedSpan<'static>>,
},
/// A leader-mode widget. Rendered as `active_text` when the leader key is active.
WidgetLeaderMode {
active_text: Vec<TaggedSpan<'static>>,
inactive_text: Vec<TaggedSpan<'static>>,
},
/// A clickable widget that copies the current command buffer to the clipboard.
WidgetCopyBuffer { text: Vec<TaggedSpan<'static>> },
/// A widget that displays how long ago the flyline app last closed.
///
/// The formatted text is computed once at construction time (when the
/// `PromptStringBuilder` processes the widget name) and stored as a
/// static string. At render time the stored text is emitted directly
/// without any further computation.
///
/// The widget's text is styled with `base_style` (the surrounding prompt
/// span's style).
WidgetLastCommandDuration { text: String, base_style: Style },
/// A custom-command widget. On each render the child process is polled
/// with `try_wait`; once it exits the output (processed through
/// `expand_prompt_through_bash`) is shown. While still pending the
/// placeholder string is shown.
///
/// Each segment is fully independent: two occurrences of the same widget
/// name in a prompt string each run their own process.
///
/// `base_style` is the style of the prompt span in which the widget name
/// appeared. At render time each output span's own style overrides this
/// base (i.e. `base_style.patch(span.style)`).
WidgetCustom {
state: WidgetCustomState,
base_style: Style,
},
/// A widget that displays the line number in PS2 continuation prompt.
WidgetBufferLineNumber { base_style: Style },
}
#[derive(Debug, Default)]
enum PromptRuler {
#[default]
None,
EmptyLine,
Pattern(Vec<PromptSegment>),
}
#[derive(Debug)]
pub enum FormattedPromptRuler {
EmptyLine,
Line(TaggedLine<'static>),
}
pub struct PromptManager {
prompt: Vec<Vec<PromptSegment>>,
prompt_final: Option<Vec<Vec<PromptSegment>>>,
ps2: Vec<PromptSegment>,
rprompt: Vec<Vec<PromptSegment>>,
rprompt_final: Option<Vec<Vec<PromptSegment>>>,
fill_span: Vec<PromptSegment>,
fill_span_final: Option<Vec<PromptSegment>>,
prompt_ruler: PromptRuler,
prompt_ruler_final: Option<PromptRuler>,
/// Time captured at construction; used when animations are disabled so
/// that time-based prompt fields show the session-start time rather than
/// updating on every render.
construction_time: chrono::DateTime<chrono::Local>,
/// The current working directory at the time the prompt was constructed.
/// Used by `PromptCwdEdit` mode to compute the path for a given CWD segment index.
cwd: String,
}
/// Pass a raw bash prompt string (with any time-code placeholders already
/// substituted) through bash's `decode_prompt_string`, then convert the
/// decoded output to a `Vec<Line<'static>>` via [`IntoText`].
///
/// `\[` / `\]` non-printing-sequence markers are stripped before the string is
/// handed to `decode_prompt_string` because they are Bash-specific and not
/// meaningful to ANSI parsers. Trailing newlines and carriage returns are
/// stripped from each span.
///
/// Returns `None` when the string cannot be processed (e.g. contains interior
/// NUL bytes or bash returns a null pointer).
fn expand_prompt_through_bash(raw: String) -> Option<Vec<Line<'static>>> {
if raw.is_empty() {
return Some(vec![]);
}
// Strip literal `\[` / `\]` non-printing-sequence markers before handing
// the string to `decode_prompt`.
let raw = raw.replace("\\[", "").replace("\\]", "");
let decoded = shell::backend().decode_prompt(&raw, true)?;
let mut lines = decoded.into_text().ok()?.lines;
for line in &mut lines {
for span in &mut line.spans {
let raw = span.content.as_ref();
let stripped = raw.trim_end_matches(&['\n', '\r'][..]);
if stripped.len() != raw.len() {
log::debug!("Stripping trailing newline/carriage return from prompt line span");
span.content = stripped.to_owned().into();
}
}
}
Some(lines)
}
/// Builds expanded prompt segment lines from raw bash prompt strings while
/// accumulating a shared map of time-placeholder identifiers to chrono format
/// strings and holding pre-processed animation data.
///
/// A single `PromptStringBuilder` should be used for all prompt variables
/// (PS1, RPS1 / RPROMPT, PS1_FILL, PROMPT_RULER) so that placeholder identifiers are unique
/// across all of them.
struct PromptStringBuilder<'a> {
/// Monotonically increasing counter used to generate unique placeholder IDs.
counter: u32,
/// Accumulated map of placeholder → chrono format string.
/// Used during `expand_prompt_string` to recognise which spans contain
/// time placeholders and convert them into [`PromptSegment::DynamicTime`].
time_map: HashMap<String, String>,
/// Pre-processed animations. Used by [`expand_span_to_segments`] to
/// recognise animation-name placeholders and produce
/// [`PromptSegment::Animation`] segments in the same pass.
animations: Vec<ProcessedAnimation>,
/// Raw prompt widget definitions. Used by [`expand_span_to_segments`] to
/// recognise widget-name placeholders and produce the appropriate
/// `PromptSegment::Widget*` segments. Each occurrence of a widget name in
/// the prompt text produces a fully independent segment (and, for custom
/// widgets, a separate process invocation).
widgets: &'a [PromptWidget],
/// Current working directory, used to detect CWD substrings in prompt spans.
cwd: Option<String>,
/// Home directory, used to recognise `~`-prefixed path representations.
home: Option<String>,
/// Timestamp of the most recent flyline app session close.
/// Passed through to [`PromptSegment::WidgetLastCommandDuration`] so that
/// the elapsed duration can be computed at render time.
last_app_closed_at: Option<std::time::Instant>,
}
impl<'a> PromptStringBuilder<'a> {
fn new(animations: Vec<ProcessedAnimation>, widgets: &'a [PromptWidget]) -> Self {
Self {
counter: 0,
time_map: HashMap::new(),
animations,
widgets,
cwd: None,
home: None,
last_app_closed_at: None,
}
}
/// Set the current working directory and home directory for CWD detection.
fn with_cwd(mut self, cwd: String, home: Option<String>) -> Self {
self.cwd = Some(cwd);
self.home = home;
self
}
/// Set the timestamp of the most recent flyline app session close.
fn with_last_app_closed_at(mut self, t: Option<std::time::Instant>) -> Self {
self.last_app_closed_at = t;
self
}
/// Scan a raw bash prompt string and replace every time format escape
/// sequence with a unique 8-character placeholder, recording the mapping
/// in `self.time_map`. Returns the modified string.
///
/// Recognised bash time escape sequences (see
/// <https://www.gnu.org/software/bash/manual/html_node/Controlling-the-Prompt.html>):
///
/// | Sequence | Meaning | Chrono format |
/// |--------------|--------------------------------|---------------|
/// | `\t` | 24-hour HH:MM:SS | `%H:%M:%S` |
/// | `\T` | 12-hour HH:MM:SS | `%I:%M:%S` |
/// | `\@` | 12-hour am/pm | `%I:%M %p` |
/// | `\A` | 24-hour HH:MM | `%H:%M` |
/// | `\D{format}` | chrono format string (custom) | `format` |
fn extract_time_codes(&mut self, s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c != '\\' {
result.push(c);
continue;
}
match chars.peek().copied() {
Some('\\') => {
// Escaped backslash — pass both through so `decode_prompt_string`
// still sees `\\` as a literal `\`.
result.push('\\');
result.push('\\');
chars.next();
}
Some('t') => {
chars.next();
let id = self.next_id();
self.time_map.insert(id.clone(), "%H:%M:%S".to_string());
result.push_str(&id);
}
Some('T') => {
chars.next();
let id = self.next_id();
self.time_map.insert(id.clone(), "%I:%M:%S".to_string());
result.push_str(&id);
}
Some('@') => {
chars.next();
let id = self.next_id();
self.time_map.insert(id.clone(), "%I:%M %p".to_string());
result.push_str(&id);
}
Some('A') => {
chars.next();
let id = self.next_id();
self.time_map.insert(id.clone(), "%H:%M".to_string());
result.push_str(&id);
}
Some('D') => {
chars.next(); // consume 'D'
if chars.peek().copied() == Some('{') {
chars.next(); // consume '{'
let mut fmt = String::new();
for nc in chars.by_ref() {
if nc == '}' {
break;
}
fmt.push(nc);
}
// An empty \D{} falls back to 24-hour HH:MM:SS (%T).
// Bash would use strftime with the locale's time format here,
// but chrono does not expose a locale-aware equivalent, so %T
// is used as a reasonable default.
let chrono_fmt = if fmt.is_empty() {
"%T".to_string()
} else {
fmt
};
let id = self.next_id();
self.time_map.insert(id.clone(), chrono_fmt);
result.push_str(&id);
} else {
// Not \D{...} — pass through unchanged.
result.push('\\');
result.push('D');
}
}
_ => {
// Not a time code — pass the backslash through so
// `decode_prompt_string` can handle the sequence.
result.push('\\');
}
}
}
result
}
/// Expand a raw prompt string (e.g. from `PS1`, `RPS1`, `PS1_FILL`, or `PROMPT_RULER`)
/// into a sequence of lines, each line being a sequence of
/// [`PromptSegment`]s.
///
/// The pipeline is:
/// 1. [`extract_time_codes`] — replace bash time escape sequences with
/// unique placeholders, recording the mapping in `self.time_map`.
/// 2. [`expand_prompt_through_bash`] — run the modified string through
/// bash's `decode_prompt_string` and parse ANSI colour codes into
/// `Line<'static>` values.
/// 3. [`expand_span_to_segments`] — split each decoded span at
/// time-placeholder boundaries, producing `Static` or `DynamicTime`
/// segments.
///
/// Returns `None` when the string cannot be processed.
fn expand_prompt_string(&mut self, raw: String) -> Option<Vec<Vec<PromptSegment>>> {
let modified = self.extract_time_codes(&raw);
let lines = expand_prompt_through_bash(modified)?;
let result = lines
.into_iter()
.map(|line| {
let mut segs: Vec<PromptSegment> = line
.spans
.into_iter()
.flat_map(|span| self.expand_span_to_segments(span))
.collect();
// If multiple Cwd segments are present (because the same path
// substring appeared in more than one prompt span), keep only
// the longest one and convert the rest back to Static segments.
dedup_cwd_segments(&mut segs);
segs
})
.collect();
Some(result)
}
/// Split a single decoded [`Span`] into a sequence of [`PromptSegment`]s.
///
/// Performs four successive passes, each replacing matching substrings
/// inside any remaining [`PromptSegment::Static`] segments with the
/// appropriate richer segment kind:
/// 1. Time-placeholder strings → [`PromptSegment::DynamicTime`].
/// 2. Animation names → [`PromptSegment::Animation`].
/// 3. Widget names → `PromptSegment::Widget*`.
/// 4. CWD substrings → [`PromptSegment::Cwd`].
fn expand_span_to_segments(&self, span: Span<'static>) -> Vec<PromptSegment> {
// Pass 1: time placeholders.
let style = span.style;
let segs = split_span_by(span, |text| {
self.time_map
.iter()
.filter_map(|(id, fmt)| text.find(id.as_str()).map(|pos| (pos, id.len(), fmt)))
.min_by_key(|(pos, _, _)| *pos)
.map(|(pos, len, fmt)| {
(
pos,
len,
PromptSegment::DynamicTime {
strftime: fmt.clone(),
style,
},
)
})
});
// Pass 2: animations.
let segs = split_static_segments(segs, |s| {
let style = s.style;
split_span_by(s, |text| {
self.animations
.iter()
.filter_map(|anim| {
text.find(anim.name.as_str())
.map(|pos| (pos, anim.name.len(), anim))
})
.min_by_key(|(pos, _, _)| *pos)
.map(|(pos, len, anim)| {
(
pos,
len,
PromptSegment::Animation(Box::new(anim.clone().patch_style(style))),
)
})
})
});
// Pass 3: widgets. Custom widgets with an empty command are excluded
// (they have no valid name to match) so their placeholder text stays
// literal. Each match spawns a fresh independent widget segment.
let last_app_closed_at = self.last_app_closed_at;
let segs = split_static_segments(segs, |s| {
let style = s.style;
split_span_by(s, |text| {
self.widgets
.iter()
.filter_map(|widget| {
// Custom widgets with an empty command line are inert and should not
// be matched in the prompt text.
if let PromptWidget::Custom(w) = widget
&& w.command.is_empty()
{
return None;
}
let name = widget.name();
text.find(name).map(|pos| (pos, name.len(), widget))
})
.min_by_key(|(pos, _, _)| *pos)
.map(|(pos, len, widget)| {
(
pos,
len,
make_widget_segment(widget, style, last_app_closed_at),
)
})
})
});
// Pass 4: CWD detection.
match self.cwd.as_deref() {
Some(cwd) => {
let home = self.home.as_deref();
split_static_segments(segs, |s| split_static_span_by_cwd(s, cwd, home))
}
None => segs,
}
}
/// Allocate the next placeholder identifier and advance the counter.
fn next_id(&mut self) -> String {
let id = format!("FLYT{:04X}", self.counter);
self.counter += 1;
id
}
}
/// Apply `split` to every [`PromptSegment::Static`] in `segs`, leaving every
/// other segment untouched. Used by the time/animation/widget/cwd passes in
/// [`PromptStringBuilder::expand_span_to_segments`] to chain successive
/// substring-splitting passes over the still-unmatched portions of text.
fn split_static_segments<F>(segs: Vec<PromptSegment>, mut split: F) -> Vec<PromptSegment>
where
F: FnMut(Span<'static>) -> Vec<PromptSegment>,
{
segs.into_iter()
.flat_map(|seg| match seg {
PromptSegment::Static(s) => split(s),
other => vec![other],
})
.collect()
}
/// Generic substring-splitting helper used by the time, animation and widget
/// passes. Repeatedly invokes `find_next` on the unmatched tail of `span` to
/// locate the next match (returning byte position, byte length and the
/// replacement segment), and emits a [`PromptSegment::Static`] for the text
/// between matches. Always returns at least one segment.
fn split_span_by(
span: Span<'static>,
mut find_next: impl FnMut(&str) -> Option<(usize, usize, PromptSegment)>,
) -> Vec<PromptSegment> {
let style = span.style;
let mut result: Vec<PromptSegment> = Vec::new();
let mut remaining: String = span.content.into_owned();
while let Some((pos, len, segment)) = find_next(&remaining) {
if pos > 0 {
result.push(PromptSegment::Static(Span::styled(
remaining[..pos].to_owned(),
style,
)));
}
result.push(segment);
remaining = remaining[pos + len..].to_owned();
}
if !remaining.is_empty() {
result.push(PromptSegment::Static(Span::styled(remaining, style)));
}
// Ensure at least one segment is always returned (e.g. for an empty span
// with no matches).
if result.is_empty() {
result.push(PromptSegment::Static(Span::styled(String::new(), style)));
}
result
}
/// Build a [`PromptSegment`] for the given [`PromptWidget`].
///
/// For mouse-mode widgets the enabled/disabled texts are expanded through
/// bash and stored as pre-tagged [`TaggedSpan`]s.
///
/// For custom widgets the command is spawned directly as a child process.
/// A `block` timeout of 0 (the default when `block` is not specified) means
/// we do a single non-blocking `try_wait` and immediately put the child in
/// `Pending` if it hasn't finished yet. Any positive value (including
/// `i32::MAX` ≈ 24.8 days, which is effectively indefinite) polls up to that
/// many milliseconds before moving on.
fn make_widget_segment(
widget: &PromptWidget,
base_style: Style,
last_app_closed_at: Option<std::time::Instant>,
) -> PromptSegment {
match widget {
PromptWidget::MouseMode {
enabled_text,
disabled_text,
..
} => PromptSegment::WidgetMouseMode {
enabled_text: stdout_to_tagged_spans(enabled_text.clone()),
disabled_text: stdout_to_tagged_spans(disabled_text.clone()),
},
PromptWidget::LeaderMode {
active_text,
inactive_text,
..
} => PromptSegment::WidgetLeaderMode {
active_text: stdout_to_tagged_spans(active_text.clone()),
inactive_text: stdout_to_tagged_spans(inactive_text.clone()),
},
PromptWidget::CopyBuffer { text, .. } => {
// Apply the surrounding prompt span's base style to each span of
// the widget output so the widget visually inherits the styling
// of the span it appears in (matching Animation/Cwd behaviour).
// The widget output's own style takes precedence
// (`base_style.patch(span.style)`).
let text = stdout_to_tagged_spans_with_tag(text.clone(), Tag::PromptCopyBufferWidget)
.into_iter()
.map(|mut ts| {
ts.span.style = base_style.patch(ts.span.style);
ts
})
.collect();
PromptSegment::WidgetCopyBuffer { text }
}
PromptWidget::Custom(w) => {
let state = match spawn_widget_child(&w.command) {
Err(failure) => WidgetCustomState::Failed(failure),
Ok(mut child) => {
// Default to 0 ms when `block` is not specified; a 0 ms
// timeout performs a single non-blocking try_wait and moves
// on immediately. i32::MAX polls for ~24.8 days, which is
// effectively indefinite.
let timeout_ms = w.block.unwrap_or(0);
let timeout = std::time::Duration::from_millis(timeout_ms as u64);
let start = std::time::Instant::now();
let done_status = loop {
match child.try_wait() {
Ok(Some(status)) => break Some(Ok(status)),
Ok(None) => {
if start.elapsed() >= timeout {
break None;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
Err(e) => break Some(Err(e)),
}
};
match done_status {
Some(Ok(status)) => {
collect_and_finalize(&mut child, status, &w.command, &w.prev_output)
}
Some(Err(e)) => {
log::error!("Custom prompt widget: try_wait error: {}", e);
WidgetCustomState::Failed(WidgetFailure {
exit_code: None,
stdout: String::new(),
stderr: e.to_string(),
})
}
None => {
// Timed out: keep the child running in the background.
let placeholder = resolve_placeholder(w);
WidgetCustomState::Pending {
placeholder,
child: KillOnDropChild::new(child),
command: w.command.clone(),
prev_output_cell: w.prev_output.clone(),
}
}
}
}
};
PromptSegment::WidgetCustom { state, base_style }
}
PromptWidget::LastCommandDuration { .. } => {
// Compute elapsed duration once at construction time; the result
// is stored as a static string in the segment and reused on every
// render without further computation.
let elapsed = last_app_closed_at.map(|t| t.elapsed()).unwrap_or_default();
let text = crate::content::format_duration(elapsed);
PromptSegment::WidgetLastCommandDuration { text, base_style }
}
PromptWidget::BufferLineNumber { .. } => {
PromptSegment::WidgetBufferLineNumber { base_style }
}
}
}
/// If a prompt line has more than one [`PromptSegment::Cwd`] segment
/// (because the same path substring appeared in several prompt spans),
/// keep only the longest one and convert the shorter duplicates back to
/// plain [`PromptSegment::Static`] segments.
fn dedup_cwd_segments(segs: &mut [PromptSegment]) {
// Collect indices and text lengths of every Cwd segment.
let cwd_indices: Vec<(usize, usize)> = segs
.iter()
.enumerate()
.filter_map(|(i, seg)| {
if let PromptSegment::Cwd(spans) = seg {
let len: usize = spans.iter().map(|s| s.content.len()).sum();
Some((i, len))
} else {
None
}
})
.collect();
if cwd_indices.len() <= 1 {
return;
}
// Index of the Cwd segment with the most text content.
let longest_idx = cwd_indices
.iter()
.max_by_key(|(_, len)| *len)
.map(|(i, _)| *i)
.unwrap();
// Convert all shorter Cwd segments back to Static.
for (i, _) in &cwd_indices {
if *i != longest_idx
&& let PromptSegment::Cwd(spans) = &segs[*i]
{
let content: String = spans.iter().map(|s| s.content.as_ref()).collect();
let style = spans.first().map(|s| s.style).unwrap_or_default();
segs[*i] = PromptSegment::Static(Span::styled(content, style));
}
}
}
/// Resolve the placeholder string for a custom widget that is not yet done.
fn resolve_placeholder(w: &PromptWidgetCustom) -> Vec<TaggedSpan<'static>> {
match &w.placeholder {
Placeholder::Spaces(n) => vec![TaggedSpan::new(Span::raw(" ".repeat(*n)), Tag::Prompt)],
Placeholder::Prev => w.prev_output.lock().unwrap().clone(),
}
}
/// Return the CWD representations we should look for in the prompt text.
///
/// The search prefers the fully expanded path and, when possible, the home
///-relative `~` form of that same path.
fn cwd_representations(cwd: &str, home: Option<&str>) -> Vec<String> {
let cwd = normalize_cwd_for_matching(cwd);
if cwd.is_empty() {
return vec![];
}
let mut representations = vec![cwd.clone()];
if let Some(home) = home {
let home = normalize_cwd_for_matching(home);
if !home.is_empty()
&& let Some(rest) = cwd.strip_prefix(&home)
&& (rest.is_empty() || rest.starts_with('/'))
{
let tilde = if rest.is_empty() {
"~".to_string()
} else {
format!("~{}", rest)
};
if tilde != cwd {
representations.push(tilde);
}
}
}
representations
}
fn normalize_cwd_for_matching(path: &str) -> String {
if path == "/" {
"/".to_string()
} else {
path.trim_end_matches('/').to_string()
}
}
fn current_folder_name(cwd: &str) -> Option<&str> {
let cwd = cwd.trim_end_matches('/');
if cwd.is_empty() || cwd == "/" {
Some("/")
} else {
cwd.rsplit('/').find(|segment| !segment.is_empty())
}
}
fn extend_cwd_match_start_for_ellipsis(text: &str, start: usize) -> usize {
let prefix = &text[..start];
if prefix.ends_with('…') {
return prefix.len() - '…'.len_utf8();
}
let dot_start = prefix
.as_bytes()
.iter()
.rposition(|byte| *byte != b'.')
.map(|idx| idx + 1)
.unwrap_or(0);
if dot_start < prefix.len() {
dot_start
} else {
start
}
}
fn extend_cwd_match_end_for_trailing_slash(text: &str, end: usize) -> usize {
if text[end..].starts_with('/') {
end + 1
} else {
end
}
}
fn best_range_for_suffix(text: &str, suffix: &str) -> Option<Range<usize>> {
let mut best = None;
for (start, _) in text.match_indices(suffix) {
let end = extend_cwd_match_end_for_trailing_slash(text, start + suffix.len());
let start = extend_cwd_match_start_for_ellipsis(text, start);
let candidate = start..end;
if best
.as_ref()
.is_none_or(|current: &Range<usize>| candidate.len() > current.len())
{
best = Some(candidate);
}
}
best
}
/// Find the longest substring of `text` that looks like the current working
/// directory.
///
/// We generate the possible CWD representations, then for each representation
/// look for the longest suffix that exists in `text`. Once we have that suffix,
/// we widen the match only when `text` includes an immediately-adjacent ellipsis
/// prefix or trailing slash.
fn find_cwd_in_span(text: &str, cwd: &str, home: Option<&str>) -> Option<Range<usize>> {
let current_folder = current_folder_name(cwd)?;
let mut best = None;
for representation in cwd_representations(cwd, home) {
let max_start = representation.len().saturating_sub(current_folder.len());
let suffix_starts = representation
.char_indices()
.map(|(idx, _)| idx)
.chain(std::iter::once(representation.len()))
.take_while(|idx| *idx <= max_start);
for start in suffix_starts {
let suffix = &representation[start..];
if let Some(candidate) = best_range_for_suffix(text, suffix) {
if best
.as_ref()
.is_none_or(|current: &Range<usize>| candidate.len() > current.len())
{
best = Some(candidate);
}
break;
}
}
}
best
}
/// Split a static [`Span`] at the first (longest) detected CWD substring,
/// producing up to three segments: an optional `Static` prefix, a `Cwd`
/// segment for the matched path text, and an optional `Static` suffix.
///
/// If no CWD-like substring is found the original span is returned unchanged
/// as a single `Static` segment.
fn split_static_span_by_cwd(
span: Span<'static>,
cwd: &str,
home: Option<&str>,
) -> Vec<PromptSegment> {
let text = span.content.as_ref().to_owned();
let style = span.style;
let Some(cwd_range) = find_cwd_in_span(&text, cwd, home) else {
return vec![PromptSegment::Static(span)];
};
let mut result = Vec::new();
if cwd_range.start > 0 {
result.push(PromptSegment::Static(Span::styled(
text[..cwd_range.start].to_owned(),
style,
)));
}
result.push(PromptSegment::Cwd(split_cwd_text_into_spans(
&text[cwd_range.clone()],
style,
)));
if cwd_range.end < text.len() {
result.push(PromptSegment::Static(Span::styled(
text[cwd_range.end..].to_owned(),
style,
)));
}
result
}
/// Split a CWD text string into individual [`Span`]s, with each `/` separator
/// as its own span distinct from the path segments on either side.
///
/// The leftmost span is the tilde or root `/`; each subsequent alternating pair
/// is a `"/"` separator followed by a directory name.
///
/// Examples:
/// - `"~/foo/bar"` → `["~", "/", "foo", "/", "bar"]`
/// - `"/home/foo/bar"` → `["/", "home", "/", "foo", "/", "bar"]`
/// - `"~"` → `["~"]`
/// - `"qwe/try/ooh"` → `["qwe", "/", "try", "/", "ooh"]`
fn split_cwd_text_into_spans(text: &str, style: ratatui::style::Style) -> Vec<Span<'static>> {
if text.is_empty() {
return vec![];
}
let mut result: Vec<Span<'static>> = Vec::new();
if let Some(rest) = text.strip_prefix('~') {
// The tilde segment never has a leading slash.
if let Some(rel_slash) = rest.find('/') {
result.push(Span::styled("~".to_owned(), style));
split_into_spans(&rest[rel_slash..], style, &mut result);
} else {
// Bare "~" or "~something" with no slash — emit as a single segment.
result.push(Span::styled(text.to_owned(), style));
}
} else {
split_into_spans(text, style, &mut result);
}
result
}
/// Append spans from `path` to `result`, emitting each `/` separator and each
/// directory name as a separate span. Handles absolute paths (starting with
/// `/`) as well as relative paths.
fn split_into_spans(path: &str, style: ratatui::style::Style, result: &mut Vec<Span<'static>>) {
let mut remaining = path;
while !remaining.is_empty() {
if remaining.starts_with('/') {
result.push(Span::styled("/".to_owned(), style));
remaining = &remaining[1..];
} else if let Some(slash_pos) = remaining.find('/') {
result.push(Span::styled(remaining[..slash_pos].to_owned(), style));
remaining = &remaining[slash_pos..];
} else {
result.push(Span::styled(remaining.to_owned(), style));
break;
}
}
}
/// Expand `stdout` through bash prompt processing and return pre-tagged spans.
///
/// This is the common conversion used whenever a custom widget command
/// completes successfully: the raw stdout string is passed through
/// [`expand_prompt_through_bash`] and each resulting span is wrapped in a
/// [`TaggedSpan`] with [`Tag::Ps1Prompt`].
fn stdout_to_tagged_spans(stdout: String) -> Vec<TaggedSpan<'static>> {
stdout_to_tagged_spans_with_tag(stdout, Tag::Prompt)
}
fn stdout_to_tagged_spans_with_tag(stdout: String, tag: Tag) -> Vec<TaggedSpan<'static>> {
expand_prompt_through_bash(stdout)
.unwrap_or_default()
.into_iter()
.flat_map(|line| {
line.spans
.into_iter()
.map(|span| TaggedSpan::new(span, tag))
})
.collect()
}
/// Advance every [`PromptSegment::WidgetCustom`] segment whose child process
/// has exited from `Pending` to either `Done` or `Failed`.
///
/// This is the only step that needs mutable access to the prompt segments at