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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
//! Prompt/minibuffer system for user input
use crate::input::commands::Suggestion;
use crate::primitives::grapheme;
use crate::primitives::word_navigation::{
find_word_end_bytes, find_word_start_bytes, is_word_char,
};
/// Type of prompt - determines what action to take when user confirms
#[derive(Debug, Clone, PartialEq)]
pub enum PromptType {
/// Open a file
OpenFile,
/// Switch to a different project folder (change working directory)
SwitchProject,
/// Save current buffer to a new file
SaveFileAs,
/// Search for text in buffer
Search,
/// Search for text in buffer (for replace operation - will prompt for replacement after)
ReplaceSearch,
/// Replace text in buffer
Replace { search: String },
/// Search for text in buffer (for query-replace - will prompt for replacement after)
QueryReplaceSearch,
/// Query replace text in buffer - prompt for replacement text
QueryReplace { search: String },
/// Query replace confirmation prompt (y/n/!/q for each match)
QueryReplaceConfirm,
/// Execute a command by name (M-x)
Command,
/// Quick Open - unified prompt with prefix-based provider routing
/// Supports file finding (default), commands (>), buffers (#), goto line (:)
QuickOpen,
/// Go to a specific line number
GotoLine,
/// Choose an ANSI background file
SetBackgroundFile,
/// Set background blend ratio (0-1)
SetBackgroundBlend,
/// Plugin-controlled prompt with custom type identifier
/// The string identifier is used to filter hooks in plugin code
Plugin { custom_type: String },
/// LSP Rename operation
/// Stores the original text, start/end positions in buffer, and overlay handle
LspRename {
original_text: String,
start_pos: usize,
end_pos: usize,
overlay_handle: crate::view::overlay::OverlayHandle,
},
/// Record a macro - prompts for register (0-9)
RecordMacro,
/// Play a macro - prompts for register (0-9)
PlayMacro,
/// Set a bookmark - prompts for register (0-9)
SetBookmark,
/// Jump to a bookmark - prompts for register (0-9)
JumpToBookmark,
/// Set compose width (empty clears to viewport)
SetComposeWidth,
/// Set tab size for current buffer
SetTabSize,
/// Set line ending format for current buffer
SetLineEnding,
/// Set language/syntax highlighting for current buffer
SetLanguage,
/// Stop a running LSP server (select from list)
StopLspServer,
/// Select a theme (select from list)
/// Stores the original theme name for restoration on cancel
SelectTheme { original_theme: String },
/// Select a keybinding map (select from list)
SelectKeybindingMap,
/// Select a cursor style (select from list)
SelectCursorStyle,
/// Select a UI locale/language (select from list)
SelectLocale,
/// Select a theme for copy with formatting
CopyWithFormattingTheme,
/// Confirm reverting a modified file
ConfirmRevert,
/// Confirm saving over a file that changed on disk
ConfirmSaveConflict,
/// Confirm saving with sudo after permission denied
ConfirmSudoSave {
info: crate::model::buffer::SudoSaveRequired,
},
/// Confirm overwriting an existing file during SaveAs
ConfirmOverwriteFile { path: std::path::PathBuf },
/// Confirm closing a modified buffer (save/discard/cancel)
/// Stores buffer_id to close after user confirms
ConfirmCloseBuffer {
buffer_id: crate::model::event::BufferId,
},
/// Confirm quitting with modified buffers
ConfirmQuitWithModified,
/// File Explorer rename operation
/// Stores the original path and name for the file/directory being renamed
FileExplorerRename {
original_path: std::path::PathBuf,
original_name: String,
/// True if this rename is for a newly created file (should switch focus to editor after)
/// False if renaming an existing file (should keep focus in file explorer)
is_new_file: bool,
},
/// Confirm deleting a file or directory in the file explorer
ConfirmDeleteFile {
path: std::path::PathBuf,
is_dir: bool,
},
/// Switch to a tab by name (from the current split's open buffers)
SwitchToTab,
/// Run shell command on buffer/selection
/// If replace is true, replace the input with the output
/// If replace is false, output goes to a new buffer
ShellCommand { replace: bool },
/// Async prompt from plugin (for editor.prompt() API)
/// The result is returned via callback resolution
AsyncPrompt,
}
/// Prompt state for the minibuffer
#[derive(Debug, Clone)]
pub struct Prompt {
/// The prompt message (e.g., "Find file: ")
pub message: String,
/// User's current input
pub input: String,
/// Cursor position in the input
pub cursor_pos: usize,
/// What to do when user confirms
pub prompt_type: PromptType,
/// Autocomplete suggestions (filtered)
pub suggestions: Vec<Suggestion>,
/// Original unfiltered suggestions (for prompts that filter client-side like SwitchToTab)
pub original_suggestions: Option<Vec<Suggestion>>,
/// Currently selected suggestion index
pub selected_suggestion: Option<usize>,
/// Selection anchor position (for Shift+Arrow selection)
/// When Some(pos), there's a selection from anchor to cursor_pos
pub selection_anchor: Option<usize>,
/// Tracks the input value when suggestions were last set by a plugin.
/// Used to skip Rust-side filtering when plugin has already filtered for this input.
pub suggestions_set_for_input: Option<String>,
}
impl Prompt {
/// Create a new prompt
pub fn new(message: String, prompt_type: PromptType) -> Self {
Self {
message,
input: String::new(),
cursor_pos: 0,
prompt_type,
suggestions: Vec::new(),
original_suggestions: None,
selected_suggestion: None,
selection_anchor: None,
suggestions_set_for_input: None,
}
}
/// Create a new prompt with suggestions
///
/// The suggestions are stored both as the current filtered list and as the original
/// unfiltered list (for prompts that filter client-side like SwitchToTab).
pub fn with_suggestions(
message: String,
prompt_type: PromptType,
suggestions: Vec<Suggestion>,
) -> Self {
let selected_suggestion = if suggestions.is_empty() {
None
} else {
Some(0)
};
Self {
message,
input: String::new(),
cursor_pos: 0,
prompt_type,
original_suggestions: Some(suggestions.clone()),
suggestions,
selected_suggestion,
selection_anchor: None,
suggestions_set_for_input: None,
}
}
/// Create a new prompt with initial text (selected so typing replaces it)
pub fn with_initial_text(
message: String,
prompt_type: PromptType,
initial_text: String,
) -> Self {
let cursor_pos = initial_text.len();
// Select all initial text so typing immediately replaces it
let selection_anchor = if initial_text.is_empty() {
None
} else {
Some(0)
};
Self {
message,
input: initial_text,
cursor_pos,
prompt_type,
suggestions: Vec::new(),
original_suggestions: None,
selected_suggestion: None,
selection_anchor,
suggestions_set_for_input: None,
}
}
/// Move cursor left (to previous grapheme cluster boundary)
///
/// Uses grapheme cluster boundaries for proper handling of combining characters
/// like Thai diacritics, emoji with modifiers, etc.
pub fn cursor_left(&mut self) {
if self.cursor_pos > 0 {
self.cursor_pos = grapheme::prev_grapheme_boundary(&self.input, self.cursor_pos);
}
}
/// Move cursor right (to next grapheme cluster boundary)
///
/// Uses grapheme cluster boundaries for proper handling of combining characters
/// like Thai diacritics, emoji with modifiers, etc.
pub fn cursor_right(&mut self) {
if self.cursor_pos < self.input.len() {
self.cursor_pos = grapheme::next_grapheme_boundary(&self.input, self.cursor_pos);
}
}
/// Insert a character at the cursor position
pub fn insert_char(&mut self, ch: char) {
self.input.insert(self.cursor_pos, ch);
self.cursor_pos += ch.len_utf8();
}
/// Delete one code point before cursor (backspace)
///
/// Deletes one Unicode code point at a time, allowing layer-by-layer deletion
/// of combining characters. For Thai text, this means you can delete just the
/// tone mark without removing the base consonant.
pub fn backspace(&mut self) {
if self.cursor_pos > 0 {
// Find the previous character (code point) boundary, not grapheme boundary
// This allows layer-by-layer deletion of combining marks
let prev_boundary = self.input[..self.cursor_pos]
.char_indices()
.next_back()
.map(|(i, _)| i)
.unwrap_or(0);
self.input.drain(prev_boundary..self.cursor_pos);
self.cursor_pos = prev_boundary;
}
}
/// Delete grapheme cluster at cursor (delete key)
///
/// Deletes the entire grapheme cluster, handling combining characters properly.
pub fn delete(&mut self) {
if self.cursor_pos < self.input.len() {
let next_boundary = grapheme::next_grapheme_boundary(&self.input, self.cursor_pos);
self.input.drain(self.cursor_pos..next_boundary);
}
}
/// Move to start of input
pub fn move_to_start(&mut self) {
self.cursor_pos = 0;
}
/// Move to end of input
pub fn move_to_end(&mut self) {
self.cursor_pos = self.input.len();
}
/// Set the input text and cursor position
///
/// Used for history navigation - replaces the entire input with a new value
/// and moves cursor to the end.
///
/// # Example
/// ```
/// # use fresh::prompt::{Prompt, PromptType};
/// let mut prompt = Prompt::new("Search: ".to_string(), PromptType::Search);
/// prompt.input = "current".to_string();
/// prompt.cursor_pos = 7;
///
/// prompt.set_input("from history".to_string());
/// assert_eq!(prompt.input, "from history");
/// assert_eq!(prompt.cursor_pos, 12); // At end
/// ```
pub fn set_input(&mut self, text: String) {
self.cursor_pos = text.len();
self.input = text;
self.clear_selection();
}
/// Select next suggestion
pub fn select_next_suggestion(&mut self) {
if !self.suggestions.is_empty() {
self.selected_suggestion = Some(match self.selected_suggestion {
Some(idx) if idx + 1 < self.suggestions.len() => idx + 1,
Some(_) => 0, // Wrap to start
None => 0,
});
}
}
/// Select previous suggestion
pub fn select_prev_suggestion(&mut self) {
if !self.suggestions.is_empty() {
self.selected_suggestion = Some(match self.selected_suggestion {
Some(0) => self.suggestions.len() - 1, // Wrap to end
Some(idx) => idx - 1,
None => 0,
});
}
}
/// Get the currently selected suggestion value
pub fn selected_value(&self) -> Option<String> {
self.selected_suggestion
.and_then(|idx| self.suggestions.get(idx))
.map(|s| s.get_value().to_string())
}
/// Get the final input (use selected suggestion if available, otherwise raw input)
pub fn get_final_input(&self) -> String {
self.selected_value().unwrap_or_else(|| self.input.clone())
}
/// Apply fuzzy filtering to suggestions based on current input
///
/// If `match_description` is true, also matches against suggestion descriptions.
/// Updates `suggestions` with filtered and sorted results.
pub fn filter_suggestions(&mut self, match_description: bool) {
use crate::input::fuzzy::{fuzzy_match, FuzzyMatch};
// Skip filtering if the plugin has already set suggestions for this exact input.
// This handles the race condition where run_hook("prompt_changed") is async:
// the plugin may have already responded with filtered results via setPromptSuggestions.
if let Some(ref set_for_input) = self.suggestions_set_for_input {
if set_for_input == &self.input {
return;
}
}
let Some(original) = &self.original_suggestions else {
return;
};
let input = &self.input;
let mut filtered: Vec<(crate::input::commands::Suggestion, i32)> = original
.iter()
.filter_map(|s| {
let text_result = fuzzy_match(input, &s.text);
let desc_result = if match_description {
s.description
.as_ref()
.map(|d| fuzzy_match(input, d))
.unwrap_or_else(FuzzyMatch::no_match)
} else {
FuzzyMatch::no_match()
};
if text_result.matched || desc_result.matched {
Some((s.clone(), text_result.score.max(desc_result.score)))
} else {
None
}
})
.collect();
filtered.sort_by(|a, b| b.1.cmp(&a.1));
self.suggestions = filtered.into_iter().map(|(s, _)| s).collect();
self.selected_suggestion = if self.suggestions.is_empty() {
None
} else {
Some(0)
};
}
// ========================================================================
// Advanced editing operations (word-based, clipboard)
// ========================================================================
//
// MOTIVATION:
// These methods provide advanced editing capabilities in prompts that
// users expect from normal text editing:
// - Word-based deletion (Ctrl+Backspace/Delete)
// - Copy/paste/cut operations
//
// This enables consistent editing experience across both buffer editing
// and prompt input (command palette, file picker, search, etc.).
/// Delete from cursor to end of word (Ctrl+Delete).
///
/// Deletes from the current cursor position to the end of the current word.
/// If the cursor is at a non-word character, skips to the next word and
/// deletes to its end.
///
/// # Example
/// ```
/// # use fresh::prompt::{Prompt, PromptType};
/// let mut prompt = Prompt::new("Find: ".to_string(), PromptType::OpenFile);
/// prompt.input = "hello world".to_string();
/// prompt.cursor_pos = 0; // At start of "hello"
/// prompt.delete_word_forward();
/// assert_eq!(prompt.input, " world");
/// assert_eq!(prompt.cursor_pos, 0);
/// ```
pub fn delete_word_forward(&mut self) {
let word_end = find_word_end_bytes(self.input.as_bytes(), self.cursor_pos);
if word_end > self.cursor_pos {
self.input.drain(self.cursor_pos..word_end);
// Cursor stays at same position
}
}
/// Delete from start of word to cursor (Ctrl+Backspace).
///
/// Deletes from the start of the current word to the cursor position.
/// If the cursor is after a non-word character, deletes the previous word.
///
/// # Example
/// ```
/// # use fresh::prompt::{Prompt, PromptType};
/// let mut prompt = Prompt::new("Find: ".to_string(), PromptType::OpenFile);
/// prompt.input = "hello world".to_string();
/// prompt.cursor_pos = 5; // After "hello"
/// prompt.delete_word_backward();
/// assert_eq!(prompt.input, " world");
/// assert_eq!(prompt.cursor_pos, 0);
/// ```
pub fn delete_word_backward(&mut self) {
let word_start = find_word_start_bytes(self.input.as_bytes(), self.cursor_pos);
if word_start < self.cursor_pos {
self.input.drain(word_start..self.cursor_pos);
self.cursor_pos = word_start;
}
}
/// Delete from cursor to end of line (Ctrl+K).
///
/// Deletes all text from the cursor position to the end of the input.
///
/// # Example
/// ```
/// # use fresh::prompt::{Prompt, PromptType};
/// let mut prompt = Prompt::new("Find: ".to_string(), PromptType::OpenFile);
/// prompt.input = "hello world".to_string();
/// prompt.cursor_pos = 5; // After "hello"
/// prompt.delete_to_end();
/// assert_eq!(prompt.input, "hello");
/// assert_eq!(prompt.cursor_pos, 5);
/// ```
pub fn delete_to_end(&mut self) {
if self.cursor_pos < self.input.len() {
self.input.truncate(self.cursor_pos);
}
}
/// Get the current input text (for copy operation).
///
/// Returns a copy of the entire input. In future, this could be extended
/// to support selection ranges for copying only selected text.
///
/// # Example
/// ```
/// # use fresh::prompt::{Prompt, PromptType};
/// let mut prompt = Prompt::new("Search: ".to_string(), PromptType::Search);
/// prompt.input = "test query".to_string();
/// assert_eq!(prompt.get_text(), "test query");
/// ```
pub fn get_text(&self) -> String {
self.input.clone()
}
/// Clear the input (used for cut operation).
///
/// Removes all text from the input and resets cursor to start.
///
/// # Example
/// ```
/// # use fresh::prompt::{Prompt, PromptType};
/// let mut prompt = Prompt::new("Find: ".to_string(), PromptType::OpenFile);
/// prompt.input = "some text".to_string();
/// prompt.cursor_pos = 9;
/// prompt.clear();
/// assert_eq!(prompt.input, "");
/// assert_eq!(prompt.cursor_pos, 0);
/// ```
pub fn clear(&mut self) {
self.input.clear();
self.cursor_pos = 0;
// Also clear selection when clearing input
self.selected_suggestion = None;
}
/// Insert text at cursor position (used for paste operation).
///
/// Inserts the given text at the current cursor position and moves
/// the cursor to the end of the inserted text.
///
/// # Example
/// ```
/// # use fresh::prompt::{Prompt, PromptType};
/// let mut prompt = Prompt::new("Command: ".to_string(), PromptType::Command);
/// prompt.input = "save".to_string();
/// prompt.cursor_pos = 4;
/// prompt.insert_str(" file");
/// assert_eq!(prompt.input, "save file");
/// assert_eq!(prompt.cursor_pos, 9);
/// ```
pub fn insert_str(&mut self, text: &str) {
// If there's a selection, delete it first
if self.has_selection() {
self.delete_selection();
}
self.input.insert_str(self.cursor_pos, text);
self.cursor_pos += text.len();
}
// ========================================================================
// Selection support
// ========================================================================
/// Check if there's an active selection
pub fn has_selection(&self) -> bool {
self.selection_anchor.is_some() && self.selection_anchor != Some(self.cursor_pos)
}
/// Get the selection range (start, end) where start <= end
pub fn selection_range(&self) -> Option<(usize, usize)> {
if let Some(anchor) = self.selection_anchor {
if anchor != self.cursor_pos {
let start = anchor.min(self.cursor_pos);
let end = anchor.max(self.cursor_pos);
return Some((start, end));
}
}
None
}
/// Get the selected text
pub fn selected_text(&self) -> Option<String> {
self.selection_range()
.map(|(start, end)| self.input[start..end].to_string())
}
/// Delete the current selection and return the deleted text
pub fn delete_selection(&mut self) -> Option<String> {
if let Some((start, end)) = self.selection_range() {
let deleted = self.input[start..end].to_string();
self.input.drain(start..end);
self.cursor_pos = start;
self.selection_anchor = None;
Some(deleted)
} else {
None
}
}
/// Clear selection without deleting text
pub fn clear_selection(&mut self) {
self.selection_anchor = None;
}
/// Move cursor left with selection (by grapheme cluster)
pub fn move_left_selecting(&mut self) {
// Set anchor if not already set
if self.selection_anchor.is_none() {
self.selection_anchor = Some(self.cursor_pos);
}
// Move cursor left by grapheme cluster
if self.cursor_pos > 0 {
self.cursor_pos = grapheme::prev_grapheme_boundary(&self.input, self.cursor_pos);
}
}
/// Move cursor right with selection (by grapheme cluster)
pub fn move_right_selecting(&mut self) {
// Set anchor if not already set
if self.selection_anchor.is_none() {
self.selection_anchor = Some(self.cursor_pos);
}
// Move cursor right by grapheme cluster
if self.cursor_pos < self.input.len() {
self.cursor_pos = grapheme::next_grapheme_boundary(&self.input, self.cursor_pos);
}
}
/// Move to start of input with selection
pub fn move_home_selecting(&mut self) {
if self.selection_anchor.is_none() {
self.selection_anchor = Some(self.cursor_pos);
}
self.cursor_pos = 0;
}
/// Move to end of input with selection
pub fn move_end_selecting(&mut self) {
if self.selection_anchor.is_none() {
self.selection_anchor = Some(self.cursor_pos);
}
self.cursor_pos = self.input.len();
}
/// Move to start of previous word with selection
/// Mimics Buffer's find_word_start_left behavior
pub fn move_word_left_selecting(&mut self) {
if self.selection_anchor.is_none() {
self.selection_anchor = Some(self.cursor_pos);
}
let bytes = self.input.as_bytes();
if self.cursor_pos == 0 {
return;
}
let mut new_pos = self.cursor_pos.saturating_sub(1);
// Skip non-word characters (spaces) backwards
while new_pos > 0 && !is_word_char(bytes[new_pos]) {
new_pos = new_pos.saturating_sub(1);
}
// Find start of word
while new_pos > 0 && is_word_char(bytes[new_pos.saturating_sub(1)]) {
new_pos = new_pos.saturating_sub(1);
}
self.cursor_pos = new_pos;
}
/// Move to end of next word with selection
/// For selection, we want to select whole words, so move to word END, not word START
pub fn move_word_right_selecting(&mut self) {
if self.selection_anchor.is_none() {
self.selection_anchor = Some(self.cursor_pos);
}
// Use find_word_end_bytes which moves to the END of words
let bytes = self.input.as_bytes();
let mut new_pos = find_word_end_bytes(bytes, self.cursor_pos);
// If we didn't move (already at word end), move forward to next word end
if new_pos == self.cursor_pos && new_pos < bytes.len() {
new_pos = (new_pos + 1).min(bytes.len());
new_pos = find_word_end_bytes(bytes, new_pos);
}
self.cursor_pos = new_pos;
}
/// Move to start of previous word (without selection)
/// Mimics Buffer's find_word_start_left behavior
pub fn move_word_left(&mut self) {
self.clear_selection();
let bytes = self.input.as_bytes();
if self.cursor_pos == 0 {
return;
}
let mut new_pos = self.cursor_pos.saturating_sub(1);
// Skip non-word characters (spaces) backwards
while new_pos > 0 && !is_word_char(bytes[new_pos]) {
new_pos = new_pos.saturating_sub(1);
}
// Find start of word
while new_pos > 0 && is_word_char(bytes[new_pos.saturating_sub(1)]) {
new_pos = new_pos.saturating_sub(1);
}
self.cursor_pos = new_pos;
}
/// Move to start of next word (without selection)
/// Mimics Buffer's find_word_start_right behavior
pub fn move_word_right(&mut self) {
self.clear_selection();
let bytes = self.input.as_bytes();
if self.cursor_pos >= bytes.len() {
return;
}
let mut new_pos = self.cursor_pos;
// Skip current word
while new_pos < bytes.len() && is_word_char(bytes[new_pos]) {
new_pos += 1;
}
// Skip non-word characters (spaces)
while new_pos < bytes.len() && !is_word_char(bytes[new_pos]) {
new_pos += 1;
}
self.cursor_pos = new_pos;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_delete_word_forward_basic() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello world test".to_string();
prompt.cursor_pos = 0;
prompt.delete_word_forward();
assert_eq!(prompt.input, " world test");
assert_eq!(prompt.cursor_pos, 0);
}
#[test]
fn test_delete_word_forward_middle() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello world test".to_string();
prompt.cursor_pos = 3; // Middle of "hello"
prompt.delete_word_forward();
assert_eq!(prompt.input, "hel world test");
assert_eq!(prompt.cursor_pos, 3);
}
#[test]
fn test_delete_word_forward_at_space() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello world".to_string();
prompt.cursor_pos = 5; // At space after "hello"
prompt.delete_word_forward();
assert_eq!(prompt.input, "hello");
assert_eq!(prompt.cursor_pos, 5);
}
#[test]
fn test_delete_word_backward_basic() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello world test".to_string();
prompt.cursor_pos = 5; // After "hello"
prompt.delete_word_backward();
assert_eq!(prompt.input, " world test");
assert_eq!(prompt.cursor_pos, 0);
}
#[test]
fn test_delete_word_backward_middle() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello world test".to_string();
prompt.cursor_pos = 8; // Middle of "world"
prompt.delete_word_backward();
assert_eq!(prompt.input, "hello rld test");
assert_eq!(prompt.cursor_pos, 6);
}
#[test]
fn test_delete_word_backward_at_end() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello world".to_string();
prompt.cursor_pos = 11; // At end
prompt.delete_word_backward();
assert_eq!(prompt.input, "hello ");
assert_eq!(prompt.cursor_pos, 6);
}
#[test]
fn test_delete_word_with_special_chars() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "save-file-as".to_string();
prompt.cursor_pos = 12; // At end
// Delete "as"
prompt.delete_word_backward();
assert_eq!(prompt.input, "save-file-");
assert_eq!(prompt.cursor_pos, 10);
// Delete "file"
prompt.delete_word_backward();
assert_eq!(prompt.input, "save-");
assert_eq!(prompt.cursor_pos, 5);
}
#[test]
fn test_get_text() {
let mut prompt = Prompt::new("Find: ".to_string(), PromptType::OpenFile);
prompt.input = "test content".to_string();
assert_eq!(prompt.get_text(), "test content");
}
#[test]
fn test_clear() {
let mut prompt = Prompt::new("Find: ".to_string(), PromptType::OpenFile);
prompt.input = "some text".to_string();
prompt.cursor_pos = 5;
prompt.selected_suggestion = Some(0);
prompt.clear();
assert_eq!(prompt.input, "");
assert_eq!(prompt.cursor_pos, 0);
assert_eq!(prompt.selected_suggestion, None);
}
#[test]
fn test_delete_forward_basic() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello".to_string();
prompt.cursor_pos = 1; // After 'h'
// Simulate delete key (remove 'e')
prompt.input.drain(prompt.cursor_pos..prompt.cursor_pos + 1);
assert_eq!(prompt.input, "hllo");
assert_eq!(prompt.cursor_pos, 1);
}
#[test]
fn test_delete_at_end() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello".to_string();
prompt.cursor_pos = 5; // At end
// Delete at end should do nothing
if prompt.cursor_pos < prompt.input.len() {
prompt.input.drain(prompt.cursor_pos..prompt.cursor_pos + 1);
}
assert_eq!(prompt.input, "hello");
assert_eq!(prompt.cursor_pos, 5);
}
#[test]
fn test_insert_str_at_start() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "world".to_string();
prompt.cursor_pos = 0;
prompt.insert_str("hello ");
assert_eq!(prompt.input, "hello world");
assert_eq!(prompt.cursor_pos, 6);
}
#[test]
fn test_insert_str_at_middle() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "helloworld".to_string();
prompt.cursor_pos = 5;
prompt.insert_str(" ");
assert_eq!(prompt.input, "hello world");
assert_eq!(prompt.cursor_pos, 6);
}
#[test]
fn test_insert_str_at_end() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello".to_string();
prompt.cursor_pos = 5;
prompt.insert_str(" world");
assert_eq!(prompt.input, "hello world");
assert_eq!(prompt.cursor_pos, 11);
}
#[test]
fn test_delete_word_forward_empty() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "".to_string();
prompt.cursor_pos = 0;
prompt.delete_word_forward();
assert_eq!(prompt.input, "");
assert_eq!(prompt.cursor_pos, 0);
}
#[test]
fn test_delete_word_backward_empty() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "".to_string();
prompt.cursor_pos = 0;
prompt.delete_word_backward();
assert_eq!(prompt.input, "");
assert_eq!(prompt.cursor_pos, 0);
}
#[test]
fn test_delete_word_forward_only_spaces() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = " ".to_string();
prompt.cursor_pos = 0;
prompt.delete_word_forward();
assert_eq!(prompt.input, "");
assert_eq!(prompt.cursor_pos, 0);
}
#[test]
fn test_multiple_word_deletions() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "one two three four".to_string();
prompt.cursor_pos = 18;
prompt.delete_word_backward(); // Delete "four"
assert_eq!(prompt.input, "one two three ");
prompt.delete_word_backward(); // Delete "three"
assert_eq!(prompt.input, "one two ");
prompt.delete_word_backward(); // Delete "two"
assert_eq!(prompt.input, "one ");
}
// Tests for selection functionality
#[test]
fn test_selection_with_shift_arrows() {
let mut prompt = Prompt::new("Command: ".to_string(), PromptType::Command);
prompt.input = "hello world".to_string();
prompt.cursor_pos = 5; // After "hello"
// No selection initially
assert!(!prompt.has_selection());
assert_eq!(prompt.selected_text(), None);
// Move right selecting - should select " "
prompt.move_right_selecting();
assert!(prompt.has_selection());
assert_eq!(prompt.selection_range(), Some((5, 6)));
assert_eq!(prompt.selected_text(), Some(" ".to_string()));
// Move right selecting again - should select " w"
prompt.move_right_selecting();
assert_eq!(prompt.selection_range(), Some((5, 7)));
assert_eq!(prompt.selected_text(), Some(" w".to_string()));
// Move left selecting - should shrink to " "
prompt.move_left_selecting();
assert_eq!(prompt.selection_range(), Some((5, 6)));
assert_eq!(prompt.selected_text(), Some(" ".to_string()));
}
#[test]
fn test_selection_backward() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "abcdef".to_string();
prompt.cursor_pos = 4; // After "abcd"
// Select backward
prompt.move_left_selecting();
prompt.move_left_selecting();
assert!(prompt.has_selection());
assert_eq!(prompt.selection_range(), Some((2, 4)));
assert_eq!(prompt.selected_text(), Some("cd".to_string()));
}
#[test]
fn test_selection_with_home_end() {
let mut prompt = Prompt::new("Prompt: ".to_string(), PromptType::Command);
prompt.input = "select this text".to_string();
prompt.cursor_pos = 7; // After "select "
// Select to end
prompt.move_end_selecting();
assert_eq!(prompt.selection_range(), Some((7, 16)));
assert_eq!(prompt.selected_text(), Some("this text".to_string()));
// Clear and select from current position to home
prompt.clear_selection();
prompt.move_home_selecting();
assert_eq!(prompt.selection_range(), Some((0, 16)));
assert_eq!(prompt.selected_text(), Some("select this text".to_string()));
}
#[test]
fn test_word_selection() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "one two three".to_string();
prompt.cursor_pos = 4; // After "one "
// Select word right
prompt.move_word_right_selecting();
assert_eq!(prompt.selection_range(), Some((4, 7)));
assert_eq!(prompt.selected_text(), Some("two".to_string()));
// Select another word
prompt.move_word_right_selecting();
assert_eq!(prompt.selection_range(), Some((4, 13)));
assert_eq!(prompt.selected_text(), Some("two three".to_string()));
}
#[test]
fn test_word_selection_backward() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "one two three".to_string();
prompt.cursor_pos = 13; // At end
// Select word left - moves to start of "three"
prompt.move_word_left_selecting();
assert_eq!(prompt.selection_range(), Some((8, 13)));
assert_eq!(prompt.selected_text(), Some("three".to_string()));
// Note: Currently, calling move_word_left_selecting again when already
// at a word boundary doesn't move further back. This matches the behavior
// of find_word_start_bytes which finds the start of the current word.
// For multi-word backward selection, move cursor backward first, then select.
}
#[test]
fn test_delete_selection() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello world".to_string();
prompt.cursor_pos = 5;
// Select " world"
prompt.move_end_selecting();
assert_eq!(prompt.selected_text(), Some(" world".to_string()));
// Delete selection
let deleted = prompt.delete_selection();
assert_eq!(deleted, Some(" world".to_string()));
assert_eq!(prompt.input, "hello");
assert_eq!(prompt.cursor_pos, 5);
assert!(!prompt.has_selection());
}
#[test]
fn test_insert_deletes_selection() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello world".to_string();
prompt.cursor_pos = 0;
// Select "hello"
for _ in 0..5 {
prompt.move_right_selecting();
}
assert_eq!(prompt.selected_text(), Some("hello".to_string()));
// Insert text - should delete selection first
prompt.insert_str("goodbye");
assert_eq!(prompt.input, "goodbye world");
assert_eq!(prompt.cursor_pos, 7);
assert!(!prompt.has_selection());
}
#[test]
fn test_clear_selection() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "test".to_string();
prompt.cursor_pos = 0;
// Create selection
prompt.move_end_selecting();
assert!(prompt.has_selection());
// Clear selection
prompt.clear_selection();
assert!(!prompt.has_selection());
assert_eq!(prompt.cursor_pos, 4); // Cursor should remain at end
assert_eq!(prompt.input, "test"); // Input unchanged
}
#[test]
fn test_selection_edge_cases() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "abc".to_string();
prompt.cursor_pos = 3;
// Select beyond end should stop at end (no movement, no selection)
prompt.move_right_selecting();
assert_eq!(prompt.cursor_pos, 3);
// Since cursor didn't move, anchor equals cursor, so no selection
assert_eq!(prompt.selection_range(), None);
assert_eq!(prompt.selected_text(), None);
// Delete non-existent selection should return None
assert_eq!(prompt.delete_selection(), None);
assert_eq!(prompt.input, "abc");
}
#[test]
fn test_selection_with_unicode() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "hello 世界 world".to_string();
prompt.cursor_pos = 6; // After "hello "
// Select the Chinese characters
for _ in 0..2 {
prompt.move_right_selecting();
}
let selected = prompt.selected_text().unwrap();
assert_eq!(selected, "世界");
// Delete should work correctly
prompt.delete_selection();
assert_eq!(prompt.input, "hello world");
}
// BUG REPRODUCTION TESTS
/// Test that Ctrl+Shift+Left continues past first word boundary (was bug #2)
#[test]
fn test_word_selection_continues_across_words() {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = "one two three".to_string();
prompt.cursor_pos = 13; // At end
// First Ctrl+Shift+Left - selects "three"
prompt.move_word_left_selecting();
assert_eq!(prompt.selection_range(), Some((8, 13)));
assert_eq!(prompt.selected_text(), Some("three".to_string()));
// Second Ctrl+Shift+Left - should extend to "two three"
// Now correctly moves back one more word when already at word boundary
prompt.move_word_left_selecting();
// Selection should extend to include "two three"
assert_eq!(prompt.selection_range(), Some((4, 13)));
assert_eq!(prompt.selected_text(), Some("two three".to_string()));
}
// Property-based tests for Prompt operations
#[cfg(test)]
mod property_tests {
use super::*;
use proptest::prelude::*;
proptest! {
/// Property: delete_word_backward should never increase input length
#[test]
fn prop_delete_word_backward_shrinks(
input in "[a-zA-Z0-9_ ]{0,50}",
cursor_pos in 0usize..50
) {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = input.clone();
prompt.cursor_pos = cursor_pos.min(input.len());
let original_len = prompt.input.len();
prompt.delete_word_backward();
prop_assert!(prompt.input.len() <= original_len);
}
/// Property: delete_word_forward should never increase input length
#[test]
fn prop_delete_word_forward_shrinks(
input in "[a-zA-Z0-9_ ]{0,50}",
cursor_pos in 0usize..50
) {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = input.clone();
prompt.cursor_pos = cursor_pos.min(input.len());
let original_len = prompt.input.len();
prompt.delete_word_forward();
prop_assert!(prompt.input.len() <= original_len);
}
/// Property: delete_word_backward should not move cursor past input start
#[test]
fn prop_delete_word_backward_cursor_valid(
input in "[a-zA-Z0-9_ ]{0,50}",
cursor_pos in 0usize..50
) {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = input.clone();
prompt.cursor_pos = cursor_pos.min(input.len());
prompt.delete_word_backward();
prop_assert!(prompt.cursor_pos <= prompt.input.len());
}
/// Property: delete_word_forward should keep cursor in valid range
#[test]
fn prop_delete_word_forward_cursor_valid(
input in "[a-zA-Z0-9_ ]{0,50}",
cursor_pos in 0usize..50
) {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = input.clone();
prompt.cursor_pos = cursor_pos.min(input.len());
prompt.delete_word_forward();
prop_assert!(prompt.cursor_pos <= prompt.input.len());
}
/// Property: insert_str should increase length by inserted text length
#[test]
fn prop_insert_str_length(
input in "[a-zA-Z0-9_ ]{0,30}",
insert in "[a-zA-Z0-9_ ]{0,20}",
cursor_pos in 0usize..30
) {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = input.clone();
prompt.cursor_pos = cursor_pos.min(input.len());
let original_len = prompt.input.len();
prompt.insert_str(&insert);
prop_assert_eq!(prompt.input.len(), original_len + insert.len());
}
/// Property: insert_str should move cursor by inserted text length
#[test]
fn prop_insert_str_cursor(
input in "[a-zA-Z0-9_ ]{0,30}",
insert in "[a-zA-Z0-9_ ]{0,20}",
cursor_pos in 0usize..30
) {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = input.clone();
let original_pos = cursor_pos.min(input.len());
prompt.cursor_pos = original_pos;
prompt.insert_str(&insert);
prop_assert_eq!(prompt.cursor_pos, original_pos + insert.len());
}
/// Property: clear should always result in empty string and zero cursor
#[test]
fn prop_clear_resets(input in "[a-zA-Z0-9_ ]{0,50}") {
let mut prompt = Prompt::new("Test: ".to_string(), PromptType::Search);
prompt.input = input;
prompt.cursor_pos = prompt.input.len();
prompt.clear();
prop_assert_eq!(prompt.input, "");
prop_assert_eq!(prompt.cursor_pos, 0);
}
}
}
}