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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
use crossterm::event::{Event, KeyEvent};
use std::io;
use unicode_width::UnicodeWidthChar;
use super::command_completion::CommandCompletionContext;
use super::completion::{
self, CompletionContext, CompletionUI, extract_completion_word, is_command_position,
};
use super::display_width::display_width;
use super::edit_action::EditAction;
use super::fuzzy_search::FuzzySearchUI;
use super::highlight::{CheckerEnv, ColorSpan, HighlightScanner, HighlightStyle, apply_style};
use super::history::History;
use super::keymap::{BufferState, Keymap};
use super::kill_ring::KillRing;
use super::terminal::Terminal;
use super::undo::UndoManager;
/// A minimal line-editing buffer used by the interactive REPL.
///
/// The buffer stores characters as a `Vec<char>` so that cursor
/// movement and insertion work correctly with multi-byte UTF-8
/// characters.
pub struct LineEditor {
buf: Vec<char>,
pos: usize,
suggestion: Option<String>,
tab_count: u8,
keymap: Keymap,
kill_ring: KillRing,
undo: UndoManager,
yank_state: Option<YankState>,
last_action: EditAction,
last_was_insert: bool,
prev_total_rows: usize,
}
#[derive(Debug, Clone)]
struct YankState {
start: usize,
len: usize,
}
impl LineEditor {
/// Create an empty line editor.
pub fn new() -> Self {
Self {
buf: Vec::new(),
pos: 0,
suggestion: None,
tab_count: 0,
keymap: Keymap::new(),
kill_ring: KillRing::new(60),
undo: UndoManager::new(256),
yank_state: None,
last_action: EditAction::Noop,
last_was_insert: false,
prev_total_rows: 0,
}
}
/// Return the current buffer contents as a `String`.
pub fn buffer(&self) -> String {
self.buf.iter().collect()
}
/// Return the current cursor position (0-based character index).
#[allow(dead_code)] // public API for interactive mode enhancements
pub fn cursor(&self) -> usize {
self.pos
}
/// Return `true` if the buffer is empty.
pub fn is_empty(&self) -> bool {
self.buf.is_empty()
}
/// Clear the buffer and reset the cursor to 0.
pub fn clear(&mut self) {
self.buf.clear();
self.pos = 0;
self.suggestion = None;
self.tab_count = 0;
self.yank_state = None;
self.last_action = EditAction::Noop;
self.last_was_insert = false;
self.undo.clear();
self.prev_total_rows = 0;
}
/// Insert a character at the current cursor position and advance
/// the cursor by one.
pub fn insert_char(&mut self, ch: char) {
self.buf.insert(self.pos, ch);
self.pos += 1;
}
/// Delete the character immediately before the cursor (like the
/// Backspace key). Does nothing when the cursor is at position 0.
pub fn backspace(&mut self) {
if self.pos > 0 {
self.pos -= 1;
self.buf.remove(self.pos);
}
}
/// Delete the character at the current cursor position (like the
/// Delete key). Does nothing when the cursor is at the end of
/// the buffer.
pub fn delete(&mut self) {
if self.pos < self.buf.len() {
self.buf.remove(self.pos);
}
}
/// Move the cursor one position to the left. Does nothing when
/// the cursor is already at position 0.
pub fn move_cursor_left(&mut self) {
if self.pos > 0 {
self.pos -= 1;
}
}
/// Move the cursor one position to the right. Does nothing when
/// the cursor is already at the end of the buffer.
pub fn move_cursor_right(&mut self) {
if self.pos < self.buf.len() {
self.pos += 1;
}
}
/// Move the cursor to the beginning of the buffer (position 0).
pub fn move_to_start(&mut self) {
self.pos = 0;
}
/// Move the cursor to the end of the buffer.
pub fn move_to_end(&mut self) {
self.pos = self.buf.len();
}
/// Returns true if `ch` is a word character (alphanumeric or underscore).
fn is_word_char(ch: char) -> bool {
ch.is_alphanumeric() || ch == '_'
}
/// Move cursor backward to the start of the previous word.
pub fn move_backward_word(&mut self) {
while self.pos > 0 && !Self::is_word_char(self.buf[self.pos - 1]) {
self.pos -= 1;
}
while self.pos > 0 && Self::is_word_char(self.buf[self.pos - 1]) {
self.pos -= 1;
}
}
/// Move cursor forward to the end of the next word.
pub fn move_forward_word(&mut self) {
let len = self.buf.len();
while self.pos < len && !Self::is_word_char(self.buf[self.pos]) {
self.pos += 1;
}
while self.pos < len && Self::is_word_char(self.buf[self.pos]) {
self.pos += 1;
}
}
/// Kill from cursor to end of line. Returns the killed text.
pub fn kill_to_end(&mut self) -> String {
let killed: String = self.buf[self.pos..].iter().collect();
self.buf.truncate(self.pos);
killed
}
/// Kill from start of line to cursor. Returns the killed text.
pub fn kill_to_start(&mut self) -> String {
let killed: String = self.buf[..self.pos].iter().collect();
self.buf.drain(..self.pos);
self.pos = 0;
killed
}
/// Kill the word behind the cursor. Returns the killed text.
pub fn kill_backward_word(&mut self) -> String {
let old_pos = self.pos;
self.move_backward_word();
let killed: String = self.buf[self.pos..old_pos].iter().collect();
self.buf.drain(self.pos..old_pos);
killed
}
/// Kill from cursor to end of the next word. Returns the killed text.
pub fn kill_forward_word(&mut self) -> String {
let old_pos = self.pos;
let len = self.buf.len();
let mut end = self.pos;
while end < len && !Self::is_word_char(self.buf[end]) {
end += 1;
}
while end < len && Self::is_word_char(self.buf[end]) {
end += 1;
}
let killed: String = self.buf[old_pos..end].iter().collect();
self.buf.drain(old_pos..end);
killed
}
/// Transpose the two characters around the cursor (Ctrl+T).
pub fn transpose_chars(&mut self) {
if self.buf.len() < 2 {
return;
}
if self.pos == 0 {
return;
}
if self.pos == self.buf.len() {
self.buf.swap(self.pos - 2, self.pos - 1);
} else {
self.buf.swap(self.pos - 1, self.pos);
self.pos += 1;
}
}
/// Transpose the two words around the cursor (Alt+T).
pub fn transpose_words(&mut self) {
let len = self.buf.len();
if len == 0 {
return;
}
let mut p = self.pos;
if p == len || !Self::is_word_char(self.buf[p]) {
while p > 0 && !Self::is_word_char(self.buf[p - 1]) {
p -= 1;
}
}
if p == 0 {
return;
}
// Find end of word2
let w2e = if self.pos < len && Self::is_word_char(self.buf[self.pos]) {
let mut e = self.pos;
while e < len && Self::is_word_char(self.buf[e]) {
e += 1;
}
e
} else {
p
};
// Find start of word2
let mut w2s = w2e;
while w2s > 0 && Self::is_word_char(self.buf[w2s - 1]) {
w2s -= 1;
}
if w2s == 0 {
return;
}
// Find end of word1
let mut w1e = w2s;
while w1e > 0 && !Self::is_word_char(self.buf[w1e - 1]) {
w1e -= 1;
}
if w1e == 0 {
return;
}
// Find start of word1
let mut w1s = w1e;
while w1s > 0 && Self::is_word_char(self.buf[w1s - 1]) {
w1s -= 1;
}
let word1: Vec<char> = self.buf[w1s..w1e].to_vec();
let sep: Vec<char> = self.buf[w1e..w2s].to_vec();
let word2: Vec<char> = self.buf[w2s..w2e].to_vec();
let mut replacement = Vec::new();
replacement.extend_from_slice(&word2);
replacement.extend_from_slice(&sep);
replacement.extend_from_slice(&word1);
self.buf.splice(w1s..w2e, replacement);
self.pos = w1s + word2.len() + sep.len() + word1.len();
}
/// Convert the next word to uppercase (Alt+U).
pub fn upcase_word(&mut self) {
let len = self.buf.len();
while self.pos < len && !Self::is_word_char(self.buf[self.pos]) {
self.pos += 1;
}
while self.pos < len && Self::is_word_char(self.buf[self.pos]) {
self.buf[self.pos] = self.buf[self.pos]
.to_uppercase()
.next()
.unwrap_or(self.buf[self.pos]);
self.pos += 1;
}
}
/// Convert the next word to lowercase (Alt+L).
pub fn downcase_word(&mut self) {
let len = self.buf.len();
while self.pos < len && !Self::is_word_char(self.buf[self.pos]) {
self.pos += 1;
}
while self.pos < len && Self::is_word_char(self.buf[self.pos]) {
self.buf[self.pos] = self.buf[self.pos]
.to_lowercase()
.next()
.unwrap_or(self.buf[self.pos]);
self.pos += 1;
}
}
/// Capitalize the next word: first char uppercase, rest lowercase (Alt+C).
pub fn capitalize_word(&mut self) {
let len = self.buf.len();
while self.pos < len && !Self::is_word_char(self.buf[self.pos]) {
self.pos += 1;
}
let mut first = true;
while self.pos < len && Self::is_word_char(self.buf[self.pos]) {
if first {
self.buf[self.pos] = self.buf[self.pos]
.to_uppercase()
.next()
.unwrap_or(self.buf[self.pos]);
first = false;
} else {
self.buf[self.pos] = self.buf[self.pos]
.to_lowercase()
.next()
.unwrap_or(self.buf[self.pos]);
}
self.pos += 1;
}
}
/// Insert text at the current cursor position. Returns (start, len) for yank tracking.
pub fn insert_str(&mut self, text: &str) -> (usize, usize) {
let start = self.pos;
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
for (i, ch) in chars.into_iter().enumerate() {
self.buf.insert(self.pos + i, ch);
}
self.pos += len;
(start, len)
}
/// Remove `len` characters starting at `start`. Used by yank_pop to replace yanked text.
pub fn remove_range(&mut self, start: usize, len: usize) {
let end = (start + len).min(self.buf.len());
self.buf.drain(start..end);
if self.pos > start {
self.pos = start;
}
}
/// Return the current suggestion text, if any.
#[allow(dead_code)]
pub fn suggestion(&self) -> Option<&str> {
self.suggestion.as_deref()
}
/// Accept the full autosuggestion, appending it to the buffer.
fn accept_full_suggestion(&mut self) {
if let Some(suggestion) = self.suggestion.take() {
self.buf.extend(suggestion.chars());
self.pos = self.buf.len();
}
}
/// Accept the next word from the autosuggestion.
/// A "word" is defined as: any leading spaces + non-space characters up to the next space.
fn accept_word_suggestion(&mut self) {
if let Some(suggestion) = self.suggestion.take() {
let chars: Vec<char> = suggestion.chars().collect();
let mut i = 0;
// Skip leading spaces
while i < chars.len() && chars[i] == ' ' {
i += 1;
}
// Take non-space characters
while i < chars.len() && chars[i] != ' ' {
i += 1;
}
// Append the accepted portion to the buffer
self.buf.extend(&chars[..i]);
self.pos = self.buf.len();
// Keep remaining suggestion, if any
if i < chars.len() {
self.suggestion = Some(chars[i..].iter().collect());
}
}
}
/// Update the autosuggestion based on the current buffer state.
/// Only suggests when the cursor is at the end of a non-empty buffer.
fn update_suggestion(&mut self, history: &History) {
if self.pos == self.buf.len() && !self.buf.is_empty() {
self.suggestion = history.suggest(&self.buffer());
} else {
self.suggestion = None;
}
}
}
impl std::fmt::Display for LineEditor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.buffer())
}
}
// ---------------------------------------------------------------------------
// Terminal I/O support (crossterm)
// ---------------------------------------------------------------------------
/// Result of processing a single key event.
enum KeyAction {
Continue,
Submit,
Eof,
Interrupt,
FuzzySearch,
TabComplete,
ClearScreen,
}
impl LineEditor {
/// Read a line of input from the terminal, handling cursor movement and
/// editing keys. Returns `Ok(Some(line))` on Enter, `Ok(None)` on
/// Ctrl-D with an empty buffer (EOF), or `Ok(Some(""))` on Ctrl-C.
#[allow(dead_code)] // Used by tests; production code uses read_line_with_completion
pub fn read_line<T: Terminal>(
&mut self,
prompt: &str,
upper_lines: &[String],
history: &mut History,
term: &mut T,
) -> io::Result<Option<String>> {
self.clear();
term.enable_raw_mode()?;
let result = self.read_line_loop(prompt, upper_lines, history, term);
let _ = term.disable_raw_mode();
result
}
fn read_line_loop<T: Terminal>(
&mut self,
prompt: &str,
upper_lines: &[String],
history: &mut History,
term: &mut T,
) -> io::Result<Option<String>> {
let prompt_width = display_width(prompt);
loop {
term.flush()?;
match term.read_event()? {
Event::Key(key_event) => {
match self.handle_key(key_event, history) {
KeyAction::Submit => {
history.reset_cursor();
if self.prev_total_rows > 0 {
let buf_pos_width: usize = self.buf[..self.pos]
.iter()
.map(|c| UnicodeWidthChar::width(*c).unwrap_or(0))
.sum();
let (tw, _) = term.size().unwrap_or((80, 24));
let tw = tw as usize;
let cursor_row = if tw > 0 {
(prompt_width + buf_pos_width) / tw
} else {
0
};
if self.prev_total_rows > cursor_row {
term.move_down((self.prev_total_rows - cursor_row) as u16)?;
}
}
term.move_to_column(0)?;
term.write_str("\r\n")?;
term.flush()?;
return Ok(Some(self.buffer()));
}
KeyAction::Eof => {
return Ok(None);
}
KeyAction::Interrupt => {
history.reset_cursor();
if self.prev_total_rows > 0 {
let buf_pos_width: usize = self.buf[..self.pos]
.iter()
.map(|c| UnicodeWidthChar::width(*c).unwrap_or(0))
.sum();
let (tw, _) = term.size().unwrap_or((80, 24));
let tw = tw as usize;
let cursor_row = if tw > 0 {
(prompt_width + buf_pos_width) / tw
} else {
0
};
if self.prev_total_rows > cursor_row {
term.move_down((self.prev_total_rows - cursor_row) as u16)?;
}
}
term.move_to_column(0)?;
term.write_str("\r\n")?;
term.flush()?;
self.clear();
return Ok(Some(String::new()));
}
KeyAction::FuzzySearch => {
self.suggestion = None;
term.disable_raw_mode()?;
if let Ok(Some(line)) = FuzzySearchUI::run(history, term) {
self.buf = line.chars().collect();
self.pos = self.buf.len();
}
term.enable_raw_mode()?;
term.move_to_column(0)?;
term.clear_current_line()?;
for line in upper_lines {
term.write_str(line)?;
term.write_str("\r\n")?;
}
term.write_str(prompt)?;
}
KeyAction::ClearScreen => {
term.clear_all()?;
for line in upper_lines {
term.write_str(line)?;
term.write_str("\r\n")?;
}
term.write_str(prompt)?;
}
KeyAction::TabComplete | KeyAction::Continue => {}
}
self.update_suggestion(history);
let (tw, _) = term.size().unwrap_or((80, 24));
self.redraw(term, prompt, prompt_width, &[], tw)?;
}
Event::Resize(_cols, _rows) => {
let (tw, _) = term.size().unwrap_or((80, 24));
self.update_suggestion(history);
self.redraw(term, prompt, prompt_width, &[], tw)?;
}
_ => {}
}
}
}
/// Redraw the current buffer on screen, positioning the cursor correctly.
/// Handles input that wraps past the terminal width.
fn redraw<T: Terminal>(
&mut self,
term: &mut T,
prompt: &str,
prompt_width: usize,
spans: &[ColorSpan],
term_width: u16,
) -> io::Result<()> {
let tw = term_width as usize;
let col = |n: usize| -> u16 { n.min(u16::MAX as usize) as u16 };
// Move cursor up to the prompt's last_line row (start of content)
if self.prev_total_rows > 0 {
term.move_up(self.prev_total_rows as u16)?;
}
term.move_to_column(0)?;
// Clear all rows from previous render
for i in 0..=self.prev_total_rows {
if i > 0 {
term.move_down(1)?;
}
term.clear_current_line()?;
}
// Move back up to start
if self.prev_total_rows > 0 {
term.move_up(self.prev_total_rows as u16)?;
}
// Repaint the prompt
term.move_to_column(0)?;
term.write_str(prompt)?;
// Write the buffer with or without highlighting
if spans.is_empty() {
term.write_str(&self.buffer())?;
} else {
let mut current_style = HighlightStyle::Default;
for (i, ch) in self.buf.iter().enumerate() {
let new_style = spans
.iter()
.find(|sp| sp.start <= i && i < sp.end)
.map(|sp| sp.style)
.unwrap_or(HighlightStyle::Default);
if new_style != current_style {
if current_style != HighlightStyle::Default {
term.reset_style()?;
}
apply_style(term, new_style)?;
current_style = new_style;
}
term.write_char(*ch)?;
}
if current_style != HighlightStyle::Default {
term.reset_style()?;
}
}
// Draw suggestion
let suggestion_width: usize;
if let Some(ref suggestion) = self.suggestion
&& self.pos == self.buf.len()
{
term.set_dim(true)?;
term.write_str(suggestion)?;
term.set_dim(false)?;
suggestion_width = suggestion
.chars()
.map(|c| UnicodeWidthChar::width(c).unwrap_or(0))
.sum();
} else {
suggestion_width = 0;
}
// Calculate total display width and rows
let buf_total_width: usize = self
.buf
.iter()
.map(|c| UnicodeWidthChar::width(*c).unwrap_or(0))
.sum();
let content_width = prompt_width + buf_total_width + suggestion_width;
let total_rows = if tw > 0 && content_width > 0 {
(content_width.saturating_sub(1)) / tw
} else {
0
};
self.prev_total_rows = total_rows;
// Position cursor at self.pos
let buf_pos_width: usize = self.buf[..self.pos]
.iter()
.map(|c| UnicodeWidthChar::width(*c).unwrap_or(0))
.sum();
let cursor_total = prompt_width + buf_pos_width;
let cursor_row = if tw > 0 { cursor_total / tw } else { 0 };
let cursor_col = if tw > 0 {
cursor_total % tw
} else {
cursor_total
};
// Move from end-of-content row to cursor row
let end_row = total_rows;
if end_row > cursor_row {
term.move_up((end_row - cursor_row) as u16)?;
}
term.move_to_column(col(cursor_col))?;
term.flush()?;
Ok(())
}
/// Map a single key event to a [`KeyAction`], mutating the buffer as needed.
fn handle_key(&mut self, key: KeyEvent, history: &mut History) -> KeyAction {
let state = BufferState {
is_empty: self.is_empty(),
at_end: self.pos == self.buf.len(),
has_suggestion: self.suggestion.is_some(),
last_action: self.last_action,
};
let (action, count) = self.keymap.resolve(key, &state);
if !matches!(action, EditAction::TabComplete) {
self.tab_count = 0;
}
// Undo snapshot management
// - Insert group boundary: when transitioning from insert to non-insert, save once
// - Destructive ops: always save pre-op state (once)
// - Insert start: save when first insert after non-insert
if self.last_was_insert && !matches!(action, EditAction::InsertChar(_)) {
// Finalize the insert group — save current state as group boundary
self.undo.save(&self.buf, self.pos);
}
match action {
EditAction::InsertChar(_) => {
if !self.last_was_insert {
self.undo.save(&self.buf, self.pos);
}
}
EditAction::KillToEnd
| EditAction::KillToStart
| EditAction::KillBackwardWord
| EditAction::KillForwardWord
| EditAction::DeleteBackward
| EditAction::DeleteForward
| EditAction::Yank
| EditAction::YankPop
| EditAction::TransposeChars
| EditAction::TransposeWords
| EditAction::UpcaseWord
| EditAction::DowncaseWord
| EditAction::CapitalizeWord => {
if !self.last_was_insert {
// Not transitioning from insert — save pre-op state directly
self.undo.save(&self.buf, self.pos);
}
// If last_was_insert, boundary save above already captured the state
}
_ => {}
}
// Determine if consecutive kill for append
let is_consecutive_kill = action.is_kill() && self.last_action.is_kill();
// Execute action
let key_action = self.execute_action(action, count, history, is_consecutive_kill);
// Update tracking state
self.last_was_insert = matches!(action, EditAction::InsertChar(ch) if ch != ' ');
if !matches!(action, EditAction::Yank | EditAction::YankPop) {
self.yank_state = None;
}
self.last_action = action;
key_action
}
fn execute_action(
&mut self,
action: EditAction,
count: u32,
history: &mut History,
consecutive_kill: bool,
) -> KeyAction {
match action {
EditAction::InsertChar(ch) => {
for _ in 0..count {
self.insert_char(ch);
}
KeyAction::Continue
}
EditAction::MoveBackward => {
for _ in 0..count {
self.move_cursor_left();
}
KeyAction::Continue
}
EditAction::MoveForward => {
for _ in 0..count {
self.move_cursor_right();
}
KeyAction::Continue
}
EditAction::MoveToStart => {
self.move_to_start();
KeyAction::Continue
}
EditAction::MoveToEnd => {
self.move_to_end();
KeyAction::Continue
}
EditAction::MoveBackwardWord => {
for _ in 0..count {
self.move_backward_word();
}
KeyAction::Continue
}
EditAction::MoveForwardWord => {
for _ in 0..count {
self.move_forward_word();
}
KeyAction::Continue
}
EditAction::DeleteBackward => {
for _ in 0..count {
self.backspace();
}
KeyAction::Continue
}
EditAction::DeleteForward => {
for _ in 0..count {
self.delete();
}
KeyAction::Continue
}
EditAction::KillToEnd => {
let killed = self.kill_to_end();
self.kill_ring.kill(&killed, consecutive_kill);
KeyAction::Continue
}
EditAction::KillToStart => {
let killed = self.kill_to_start();
self.kill_ring.prepend(&killed, consecutive_kill);
KeyAction::Continue
}
EditAction::KillBackwardWord => {
for _ in 0..count {
let killed = self.kill_backward_word();
self.kill_ring.prepend(&killed, consecutive_kill);
}
KeyAction::Continue
}
EditAction::KillForwardWord => {
for _ in 0..count {
let killed = self.kill_forward_word();
self.kill_ring.kill(&killed, consecutive_kill);
}
KeyAction::Continue
}
EditAction::Yank => {
if let Some(text) = self.kill_ring.yank().map(|s| s.to_string()) {
let (start, len) = self.insert_str(&text);
self.yank_state = Some(YankState { start, len });
}
KeyAction::Continue
}
EditAction::YankPop => {
if let Some(ys) = self.yank_state.clone() {
self.remove_range(ys.start, ys.len);
if let Some(text) = self.kill_ring.yank_pop().map(|s| s.to_string()) {
let (start, len) = self.insert_str(&text);
self.yank_state = Some(YankState { start, len });
}
}
KeyAction::Continue
}
EditAction::TransposeChars => {
for _ in 0..count {
self.transpose_chars();
}
KeyAction::Continue
}
EditAction::TransposeWords => {
for _ in 0..count {
self.transpose_words();
}
KeyAction::Continue
}
EditAction::UpcaseWord => {
for _ in 0..count {
self.upcase_word();
}
KeyAction::Continue
}
EditAction::DowncaseWord => {
for _ in 0..count {
self.downcase_word();
}
KeyAction::Continue
}
EditAction::CapitalizeWord => {
for _ in 0..count {
self.capitalize_word();
}
KeyAction::Continue
}
EditAction::Undo => {
for _ in 0..count {
if let Some((buf, pos)) = self.undo.undo() {
self.buf = buf;
self.pos = pos;
}
}
KeyAction::Continue
}
EditAction::ClearScreen => KeyAction::ClearScreen,
EditAction::Cancel => KeyAction::Continue,
EditAction::AcceptSuggestion => {
self.accept_full_suggestion();
KeyAction::Continue
}
EditAction::AcceptWordSuggestion => {
self.accept_word_suggestion();
KeyAction::Continue
}
EditAction::SetNumericArg(_) => KeyAction::Continue,
EditAction::Submit => KeyAction::Submit,
EditAction::Eof => KeyAction::Eof,
EditAction::Interrupt => KeyAction::Interrupt,
EditAction::FuzzySearch => KeyAction::FuzzySearch,
EditAction::TabComplete => {
self.tab_count += 1;
KeyAction::TabComplete
}
EditAction::HistoryPrev => {
for _ in 0..count {
if let Some(line) = history.navigate_up(&self.buffer()) {
self.buf = line.chars().collect();
self.pos = self.buf.len();
}
}
self.suggestion = None;
KeyAction::Continue
}
EditAction::HistoryNext => {
for _ in 0..count {
if let Some(line) = history.navigate_down() {
self.buf = line.chars().collect();
self.pos = self.buf.len();
}
}
self.suggestion = None;
KeyAction::Continue
}
EditAction::Noop => KeyAction::Continue,
}
}
// ── Tab completion support ─────────────────────────────────────────
/// Read a line of input with Tab completion support.
///
/// Behaves identically to [`read_line`] but also handles Tab key events
/// by invoking the completion engine.
#[allow(clippy::too_many_arguments)]
pub fn read_line_with_completion<T: Terminal>(
&mut self,
prompt: &str,
upper_lines: &[String],
history: &mut History,
term: &mut T,
ctx: &CompletionContext,
cmd_ctx: &mut CommandCompletionContext<'_>,
scanner: &mut HighlightScanner,
checker_env: &CheckerEnv<'_>,
accumulated: &str,
) -> io::Result<Option<String>> {
self.clear();
term.enable_raw_mode()?;
let result = self.read_line_loop_with_completion(
prompt,
upper_lines,
history,
term,
ctx,
cmd_ctx,
scanner,
checker_env,
accumulated,
);
let _ = term.disable_raw_mode();
result
}
#[allow(clippy::too_many_arguments)]
fn read_line_loop_with_completion<T: Terminal>(
&mut self,
prompt: &str,
upper_lines: &[String],
history: &mut History,
term: &mut T,
ctx: &CompletionContext,
cmd_ctx: &mut CommandCompletionContext<'_>,
scanner: &mut HighlightScanner,
checker_env: &CheckerEnv<'_>,
accumulated: &str,
) -> io::Result<Option<String>> {
let prompt_width = display_width(prompt);
loop {
term.flush()?;
match term.read_event()? {
Event::Key(key_event) => {
match self.handle_key(key_event, history) {
KeyAction::Submit => {
history.reset_cursor();
term.reset_style()?;
if self.prev_total_rows > 0 {
let buf_pos_width: usize = self.buf[..self.pos]
.iter()
.map(|c| UnicodeWidthChar::width(*c).unwrap_or(0))
.sum();
let (tw, _) = term.size().unwrap_or((80, 24));
let tw = tw as usize;
let cursor_row = if tw > 0 {
(prompt_width + buf_pos_width) / tw
} else {
0
};
if self.prev_total_rows > cursor_row {
term.move_down((self.prev_total_rows - cursor_row) as u16)?;
}
}
term.move_to_column(0)?;
term.write_str("\r\n")?;
term.flush()?;
return Ok(Some(self.buffer()));
}
KeyAction::Eof => {
return Ok(None);
}
KeyAction::Interrupt => {
history.reset_cursor();
term.reset_style()?;
if self.prev_total_rows > 0 {
let buf_pos_width: usize = self.buf[..self.pos]
.iter()
.map(|c| UnicodeWidthChar::width(*c).unwrap_or(0))
.sum();
let (tw, _) = term.size().unwrap_or((80, 24));
let tw = tw as usize;
let cursor_row = if tw > 0 {
(prompt_width + buf_pos_width) / tw
} else {
0
};
if self.prev_total_rows > cursor_row {
term.move_down((self.prev_total_rows - cursor_row) as u16)?;
}
}
term.move_to_column(0)?;
term.write_str("\r\n")?;
term.flush()?;
self.clear();
return Ok(Some(String::new()));
}
KeyAction::FuzzySearch => {
self.suggestion = None;
term.reset_style()?;
term.disable_raw_mode()?;
if let Ok(Some(line)) = FuzzySearchUI::run(history, term) {
self.buf = line.chars().collect();
self.pos = self.buf.len();
}
term.enable_raw_mode()?;
term.move_to_column(0)?;
term.clear_current_line()?;
for line in upper_lines {
term.write_str(line)?;
term.write_str("\r\n")?;
}
term.write_str(prompt)?;
}
KeyAction::TabComplete => {
term.reset_style()?;
self.handle_tab_complete(term, prompt, upper_lines, ctx, cmd_ctx)?;
}
KeyAction::ClearScreen => {
term.clear_all()?;
for line in upper_lines {
term.write_str(line)?;
term.write_str("\r\n")?;
}
term.write_str(prompt)?;
}
KeyAction::Continue => {}
}
self.update_suggestion(history);
let spans = scanner.scan(accumulated, &self.buf, checker_env);
let (tw, _) = term.size().unwrap_or((80, 24));
self.redraw(term, prompt, prompt_width, &spans, tw)?;
}
Event::Resize(_cols, _rows) => {
let (tw, _) = term.size().unwrap_or((80, 24));
self.update_suggestion(history);
let spans = scanner.scan(accumulated, &self.buf, checker_env);
self.redraw(term, prompt, prompt_width, &spans, tw)?;
}
_ => {}
}
}
}
fn handle_tab_complete<T: Terminal>(
&mut self,
term: &mut T,
prompt: &str,
upper_lines: &[String],
ctx: &CompletionContext,
cmd_ctx: &mut CommandCompletionContext<'_>,
) -> io::Result<()> {
let (word_start, word) = {
let buf = self.buffer();
let (ws, w) = extract_completion_word(&buf, self.pos);
(ws, w.to_owned())
};
let is_cmd_pos = {
let buf = self.buffer();
is_command_position(&buf, word_start)
};
let (candidates, common_prefix, dir_prefix) = if is_cmd_pos && !word.contains('/') {
// Command name completion
let (cands, common) = cmd_ctx.completer.complete_common_prefix(
&word,
cmd_ctx.path,
cmd_ctx.builtins,
cmd_ctx.aliases,
);
(cands, common, String::new())
} else {
// Path completion (existing)
let result = completion::complete(&self.buffer(), self.pos, ctx);
(result.candidates, result.common_prefix, result.dir_prefix)
};
if candidates.is_empty() {
return Ok(());
}
if self.tab_count == 1 {
if candidates.len() == 1 {
// Single candidate: replace word
let candidate = &candidates[0];
let is_dir = candidate.ends_with('/');
let mut replacement = format!("{}{}", dir_prefix, candidate);
if !is_dir {
replacement.push(' ');
}
self.replace_word(word_start, &replacement);
} else {
// Multiple candidates: replace with common prefix if longer
let current_word_len = self.buffer()[word_start..self.pos].len();
let new_word = format!("{}{}", dir_prefix, common_prefix);
if new_word.len() > current_word_len {
self.replace_word(word_start, &new_word);
}
}
} else if self.tab_count >= 2 && candidates.len() >= 2 {
// Show interactive completion UI
self.suggestion = None;
term.disable_raw_mode()?;
let selected = CompletionUI::run(&candidates, term)?;
if let Some(sel) = selected {
let is_dir = sel.ends_with('/');
let mut replacement = format!("{}{}", dir_prefix, sel);
if !is_dir {
replacement.push(' ');
}
self.replace_word(word_start, &replacement);
}
term.enable_raw_mode()?;
term.move_to_column(0)?;
term.clear_current_line()?;
for line in upper_lines {
term.write_str(line)?;
term.write_str("\r\n")?;
}
term.write_str(prompt)?;
}
Ok(())
}
/// Replace the word starting at byte offset `word_start` with `replacement`.
fn replace_word(&mut self, word_start: usize, replacement: &str) {
// Convert byte offset to char index
let char_start = self.buffer()[..word_start].chars().count();
// Drain chars from char_start to current pos
let drain_end = self.pos;
self.buf.drain(char_start..drain_end);
// Insert replacement chars at char_start
let rep_chars: Vec<char> = replacement.chars().collect();
let rep_len = rep_chars.len();
for (i, ch) in rep_chars.into_iter().enumerate() {
self.buf.insert(char_start + i, ch);
}
self.pos = char_start + rep_len;
}
}