-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathengine.rs
1819 lines (1666 loc) · 68.3 KB
/
engine.rs
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
use std::path::PathBuf;
use itertools::Itertools;
use nu_ansi_term::{Color, Style};
use crate::{enums::ReedlineRawEvent, CursorConfig};
#[cfg(feature = "bashisms")]
use crate::{
history::SearchFilter,
menu_functions::{parse_selection_char, ParseAction},
};
#[cfg(feature = "external_printer")]
use {
crate::external_printer::ExternalPrinter,
crossbeam::channel::TryRecvError,
std::io::{Error, ErrorKind},
};
use {
crate::{
completion::{Completer, DefaultCompleter},
core_editor::Editor,
edit_mode::{EditMode, Emacs},
enums::{EventStatus, ReedlineEvent},
highlighter::SimpleMatchHighlighter,
hinter::Hinter,
history::{
FileBackedHistory, History, HistoryCursor, HistoryItem, HistoryItemId,
HistoryNavigationQuery, HistorySessionId, SearchDirection, SearchQuery,
},
painting::{Painter, PromptLines},
prompt::{PromptEditMode, PromptHistorySearchStatus},
result::{ReedlineError, ReedlineErrorVariants},
terminal_extensions::{bracketed_paste::BracketedPasteGuard, kitty::KittyProtocolGuard},
utils::text_manipulation,
EditCommand, ExampleHighlighter, Highlighter, LineBuffer, Menu, MenuEvent, Prompt,
PromptHistorySearch, ReedlineMenu, Signal, UndoBehavior, ValidationResult, Validator,
},
crossterm::{
cursor::{SetCursorStyle, Show},
event,
event::{Event, KeyCode, KeyEvent, KeyModifiers},
terminal, QueueableCommand,
},
std::{
fs::File, io, io::Result, io::Write, process::Command, time::Duration, time::SystemTime,
},
};
// The POLL_WAIT is used to specify for how long the POLL should wait for
// events, to accelerate the handling of paste or compound resize events. Having
// a POLL_WAIT of zero means that every single event is treated as soon as it
// arrives. This doesn't allow for the possibility of more than 1 event
// happening at the same time.
const POLL_WAIT: u64 = 10;
// Since a paste event is multiple Event::Key events happening at the same time, we specify
// how many events should be in the crossterm_events vector before it is considered
// a paste. 10 events in 10 milliseconds is conservative enough (unlikely somebody
// will type more than 10 characters in 10 milliseconds)
const EVENTS_THRESHOLD: usize = 10;
/// Determines if inputs should be used to extend the regular line buffer,
/// traverse the history in the standard prompt or edit the search string in the
/// reverse search
#[derive(Debug, PartialEq, Eq)]
enum InputMode {
/// Regular input by user typing or previous insertion.
/// Undo tracking is active
Regular,
/// Full reverse search mode with different prompt,
/// editing affects the search string,
/// suggestions are provided to be inserted in the line buffer
HistorySearch,
/// Hybrid mode indicating that history is walked through in the standard prompt
/// Either bash style up/down history or fish style prefix search,
/// Edits directly switch to [`InputMode::Regular`]
HistoryTraversal,
}
/// Line editor engine
///
/// ## Example usage
/// ```no_run
/// use reedline::{Reedline, Signal, DefaultPrompt};
/// let mut line_editor = Reedline::create();
/// let prompt = DefaultPrompt::default();
///
/// let out = line_editor.read_line(&prompt).unwrap();
/// match out {
/// Signal::Success(content) => {
/// // process content
/// }
/// _ => {
/// eprintln!("Entry aborted!");
///
/// }
/// }
/// ```
pub struct Reedline {
editor: Editor,
// History
history: Box<dyn History>,
history_cursor: HistoryCursor,
history_session_id: Option<HistorySessionId>,
// none if history doesn't support this
history_last_run_id: Option<HistoryItemId>,
history_exclusion_prefix: Option<String>,
history_excluded_item: Option<HistoryItem>,
history_cursor_on_excluded: bool,
input_mode: InputMode,
// Yielded to the host program after a `ReedlineEvent::ExecuteHostCommand`, thus redraw in-place
executing_host_command: bool,
// Validator
validator: Option<Box<dyn Validator>>,
// Stdout
painter: Painter,
transient_prompt: Option<Box<dyn Prompt>>,
// Edit Mode: Vi, Emacs
edit_mode: Box<dyn EditMode>,
// Provides the tab completions
completer: Box<dyn Completer>,
quick_completions: bool,
partial_completions: bool,
// Highlight the edit buffer
highlighter: Box<dyn Highlighter>,
// Style used for visual selection
visual_selection_style: Style,
// Showcase hints based on various strategies (history, language-completion, spellcheck, etc)
hinter: Option<Box<dyn Hinter>>,
hide_hints: bool,
// Use ansi coloring or not
use_ansi_coloring: bool,
// Engine Menus
menus: Vec<ReedlineMenu>,
// Text editor used to open the line buffer for editing
buffer_editor: Option<BufferEditor>,
// Use different cursors depending on the current edit mode
cursor_shapes: Option<CursorConfig>,
// Manage bracketed paste mode
bracketed_paste: BracketedPasteGuard,
// Manage optional kitty protocol
kitty_protocol: KittyProtocolGuard,
#[cfg(feature = "external_printer")]
external_printer: Option<ExternalPrinter<String>>,
}
struct BufferEditor {
command: Command,
temp_file: PathBuf,
}
impl Drop for Reedline {
fn drop(&mut self) {
if self.cursor_shapes.is_some() {
let _ignore = terminal::enable_raw_mode();
let mut stdout = std::io::stdout();
let _ignore = stdout.queue(SetCursorStyle::DefaultUserShape);
let _ignore = stdout.queue(Show);
let _ignore = stdout.flush();
}
// Ensures that the terminal is in a good state if we panic semigracefully
// Calling `disable_raw_mode()` twice is fine with Linux
let _ignore = terminal::disable_raw_mode();
}
}
impl Reedline {
const FILTERED_ITEM_ID: HistoryItemId = HistoryItemId(i64::MAX);
/// Create a new [`Reedline`] engine with a local [`History`] that is not synchronized to a file.
#[must_use]
pub fn create() -> Self {
let history = Box::<FileBackedHistory>::default();
let painter = Painter::new(std::io::BufWriter::new(std::io::stderr()));
let buffer_highlighter = Box::<ExampleHighlighter>::default();
let visual_selection_style = Style::new().on(Color::LightGray);
let completer = Box::<DefaultCompleter>::default();
let hinter = None;
let validator = None;
let edit_mode = Box::<Emacs>::default();
let hist_session_id = None;
Reedline {
editor: Editor::default(),
history,
history_cursor: HistoryCursor::new(
HistoryNavigationQuery::Normal(LineBuffer::default()),
hist_session_id,
),
history_session_id: hist_session_id,
history_last_run_id: None,
history_exclusion_prefix: None,
history_excluded_item: None,
history_cursor_on_excluded: false,
input_mode: InputMode::Regular,
executing_host_command: false,
painter,
transient_prompt: None,
edit_mode,
completer,
quick_completions: false,
partial_completions: false,
highlighter: buffer_highlighter,
visual_selection_style,
hinter,
hide_hints: false,
validator,
use_ansi_coloring: true,
menus: Vec::new(),
buffer_editor: None,
cursor_shapes: None,
bracketed_paste: BracketedPasteGuard::default(),
kitty_protocol: KittyProtocolGuard::default(),
#[cfg(feature = "external_printer")]
external_printer: None,
}
}
/// Get a new history session id based on the current time and the first commit datetime of reedline
pub fn create_history_session_id() -> Option<HistorySessionId> {
let nanos = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => n.as_nanos() as i64,
Err(_) => 0,
};
Some(HistorySessionId::new(nanos))
}
/// Toggle whether reedline enables bracketed paste to reed copied content
///
/// This currently alters the behavior for multiline pastes as pasting of regular text will
/// execute after every complete new line as determined by the [`Validator`]. With enabled
/// bracketed paste all lines will appear in the buffer and can then be submitted with a
/// separate enter.
///
/// At this point most terminals should support it or ignore the setting of the necessary
/// flags. For full compatibility, keep it disabled.
pub fn use_bracketed_paste(mut self, enable: bool) -> Self {
self.bracketed_paste.set(enable);
self
}
/// Toggle whether reedline uses the kitty keyboard enhancement protocol
///
/// This allows us to disambiguate more events than the traditional standard
/// Only available with a few terminal emulators.
/// You can check for that with [`crate::kitty_protocol_available`]
/// `Reedline` will perform this check internally
///
/// Read more: <https://sw.kovidgoyal.net/kitty/keyboard-protocol/>
pub fn use_kitty_keyboard_enhancement(mut self, enable: bool) -> Self {
self.kitty_protocol.set(enable);
self
}
/// Return the previously generated history session id
pub fn get_history_session_id(&self) -> Option<HistorySessionId> {
self.history_session_id
}
/// Set a new history session id
/// This should be used in situations where the user initially did not have a history_session_id
/// and then later realized they want to have one without restarting the application.
pub fn set_history_session_id(&mut self, session: Option<HistorySessionId>) -> Result<()> {
self.history_session_id = session;
Ok(())
}
/// A builder to include a [`Hinter`] in your instance of the Reedline engine
/// # Example
/// ```rust
/// //Cargo.toml
/// //[dependencies]
/// //nu-ansi-term = "*"
/// use {
/// nu_ansi_term::{Color, Style},
/// reedline::{DefaultHinter, Reedline},
/// };
///
/// let mut line_editor = Reedline::create().with_hinter(Box::new(
/// DefaultHinter::default()
/// .with_style(Style::new().italic().fg(Color::LightGray)),
/// ));
/// ```
#[must_use]
pub fn with_hinter(mut self, hinter: Box<dyn Hinter>) -> Self {
self.hinter = Some(hinter);
self
}
/// Remove current [`Hinter`]
#[must_use]
pub fn disable_hints(mut self) -> Self {
self.hinter = None;
self
}
/// A builder to configure the tab completion
/// # Example
/// ```rust
/// // Create a reedline object with tab completions support
///
/// use reedline::{DefaultCompleter, Reedline};
///
/// let commands = vec![
/// "test".into(),
/// "hello world".into(),
/// "hello world reedline".into(),
/// "this is the reedline crate".into(),
/// ];
/// let completer = Box::new(DefaultCompleter::new_with_wordlen(commands.clone(), 2));
///
/// let mut line_editor = Reedline::create().with_completer(completer);
/// ```
#[must_use]
pub fn with_completer(mut self, completer: Box<dyn Completer>) -> Self {
self.completer = completer;
self
}
/// Turn on quick completions. These completions will auto-select if the completer
/// ever narrows down to a single entry.
#[must_use]
pub fn with_quick_completions(mut self, quick_completions: bool) -> Self {
self.quick_completions = quick_completions;
self
}
/// Turn on partial completions. These completions will fill the buffer with the
/// smallest common string from all the options
#[must_use]
pub fn with_partial_completions(mut self, partial_completions: bool) -> Self {
self.partial_completions = partial_completions;
self
}
/// A builder which enables or disables the use of ansi coloring in the prompt
/// and in the command line syntax highlighting.
#[must_use]
pub fn with_ansi_colors(mut self, use_ansi_coloring: bool) -> Self {
self.use_ansi_coloring = use_ansi_coloring;
self
}
/// A builder that configures the highlighter for your instance of the Reedline engine
/// # Example
/// ```rust
/// // Create a reedline object with highlighter support
///
/// use reedline::{ExampleHighlighter, Reedline};
///
/// let commands = vec![
/// "test".into(),
/// "hello world".into(),
/// "hello world reedline".into(),
/// "this is the reedline crate".into(),
/// ];
/// let mut line_editor =
/// Reedline::create().with_highlighter(Box::new(ExampleHighlighter::new(commands)));
/// ```
#[must_use]
pub fn with_highlighter(mut self, highlighter: Box<dyn Highlighter>) -> Self {
self.highlighter = highlighter;
self
}
/// A builder that configures the style used for visual selection
#[must_use]
pub fn with_visual_selection_style(mut self, style: Style) -> Self {
self.visual_selection_style = style;
self
}
/// A builder which configures the history for your instance of the Reedline engine
/// # Example
/// ```rust,no_run
/// // Create a reedline object with history support, including history size limits
///
/// use reedline::{FileBackedHistory, Reedline};
///
/// let history = Box::new(
/// FileBackedHistory::with_file(5, "history.txt".into())
/// .expect("Error configuring history with file"),
/// );
/// let mut line_editor = Reedline::create()
/// .with_history(history);
/// ```
#[must_use]
pub fn with_history(mut self, history: Box<dyn History>) -> Self {
self.history = history;
self
}
/// A builder which configures history exclusion for your instance of the Reedline engine
/// # Example
/// ```rust,no_run
/// // Create a reedline instance with history that will *not* include commands starting with a space
///
/// use reedline::{FileBackedHistory, Reedline};
///
/// let history = Box::new(
/// FileBackedHistory::with_file(5, "history.txt".into())
/// .expect("Error configuring history with file"),
/// );
/// let mut line_editor = Reedline::create()
/// .with_history(history)
/// .with_history_exclusion_prefix(Some(" ".into()));
/// ```
#[must_use]
pub fn with_history_exclusion_prefix(mut self, ignore_prefix: Option<String>) -> Self {
self.history_exclusion_prefix = ignore_prefix;
self
}
/// A builder that configures the validator for your instance of the Reedline engine
/// # Example
/// ```rust
/// // Create a reedline object with validator support
///
/// use reedline::{DefaultValidator, Reedline};
///
/// let mut line_editor =
/// Reedline::create().with_validator(Box::new(DefaultValidator));
/// ```
#[must_use]
pub fn with_validator(mut self, validator: Box<dyn Validator>) -> Self {
self.validator = Some(validator);
self
}
/// A builder that configures the alternate text editor used to edit the line buffer
///
/// You are responsible for providing a file path that is unique to this reedline session
///
/// # Example
/// ```rust,no_run
/// // Create a reedline object with vim as editor
///
/// use reedline::Reedline;
/// use std::env::temp_dir;
/// use std::process::Command;
///
/// let temp_file = std::env::temp_dir().join("my-random-unique.file");
/// let mut command = Command::new("vim");
/// // you can provide additional flags:
/// command.arg("-p"); // open in a vim tab (just for demonstration)
/// // you don't have to pass the filename to the command
/// let mut line_editor =
/// Reedline::create().with_buffer_editor(command, temp_file);
/// ```
#[must_use]
pub fn with_buffer_editor(mut self, editor: Command, temp_file: PathBuf) -> Self {
let mut editor = editor;
if !editor.get_args().contains(&temp_file.as_os_str()) {
editor.arg(&temp_file);
}
self.buffer_editor = Some(BufferEditor {
command: editor,
temp_file,
});
self
}
/// Remove the current [`Validator`]
#[must_use]
pub fn disable_validator(mut self) -> Self {
self.validator = None;
self
}
/// Set a different prompt to be used after submitting each line
#[must_use]
pub fn with_transient_prompt(mut self, transient_prompt: Box<dyn Prompt>) -> Self {
self.transient_prompt = Some(transient_prompt);
self
}
/// A builder which configures the edit mode for your instance of the Reedline engine
#[must_use]
pub fn with_edit_mode(mut self, edit_mode: Box<dyn EditMode>) -> Self {
self.edit_mode = edit_mode;
self
}
/// A builder that appends a menu to the engine
#[must_use]
pub fn with_menu(mut self, menu: ReedlineMenu) -> Self {
self.menus.push(menu);
self
}
/// A builder that clears the list of menus added to the engine
#[must_use]
pub fn clear_menus(mut self) -> Self {
self.menus = Vec::new();
self
}
/// A builder that adds the history item id
#[must_use]
pub fn with_history_session_id(mut self, session: Option<HistorySessionId>) -> Self {
self.history_session_id = session;
self
}
/// A builder that enables reedline changing the cursor shape based on the current edit mode.
/// The current implementation sets the cursor shape when drawing the prompt.
/// Do not use this if the cursor shape is set elsewhere, e.g. in the terminal settings or by ansi escape sequences.
pub fn with_cursor_config(mut self, cursor_shapes: CursorConfig) -> Self {
self.cursor_shapes = Some(cursor_shapes);
self
}
/// Returns the corresponding expected prompt style for the given edit mode
pub fn prompt_edit_mode(&self) -> PromptEditMode {
self.edit_mode.edit_mode()
}
/// Output the complete [`History`] chronologically with numbering to the terminal
pub fn print_history(&mut self) -> Result<()> {
let history: Vec<_> = self
.history
.search(SearchQuery::everything(SearchDirection::Forward, None))
.expect("todo: error handling");
for (i, entry) in history.iter().enumerate() {
self.print_line(&format!("{}\t{}", i, entry.command_line))?;
}
Ok(())
}
/// Output the complete [`History`] for this session, chronologically with numbering to the terminal
pub fn print_history_session(&mut self) -> Result<()> {
let history: Vec<_> = self
.history
.search(SearchQuery::everything(
SearchDirection::Forward,
self.get_history_session_id(),
))
.expect("todo: error handling");
for (i, entry) in history.iter().enumerate() {
self.print_line(&format!("{}\t{}", i, entry.command_line))?;
}
Ok(())
}
/// Print the history session id
pub fn print_history_session_id(&mut self) -> Result<()> {
println!("History Session Id: {:?}", self.get_history_session_id());
Ok(())
}
/// Toggle between having a history that uses the history session id and one that does not
pub fn toggle_history_session_matching(
&mut self,
session: Option<HistorySessionId>,
) -> Result<()> {
self.history_session_id = match self.get_history_session_id() {
Some(_) => None,
None => session,
};
Ok(())
}
/// Read-only view of the history
pub fn history(&self) -> &dyn History {
&*self.history
}
/// Mutable view of the history
pub fn history_mut(&mut self) -> &mut dyn History {
&mut *self.history
}
/// Update the underlying [`History`] to/from disk
pub fn sync_history(&mut self) -> std::io::Result<()> {
// TODO: check for interactions in the non-submitting events
self.history.sync()
}
/// Check if any commands have been run.
///
/// When no commands have been run, calling [`Self::update_last_command_context`]
/// does not make sense and is guaranteed to fail with a "No command run" error.
pub fn has_last_command_context(&self) -> bool {
self.history_last_run_id.is_some()
}
/// update the last history item with more information
pub fn update_last_command_context(
&mut self,
f: &dyn Fn(HistoryItem) -> HistoryItem,
) -> crate::Result<()> {
match &self.history_last_run_id {
Some(Self::FILTERED_ITEM_ID) => {
self.history_excluded_item = Some(f(self.history_excluded_item.take().unwrap()));
Ok(())
}
Some(r) => self.history.update(*r, f),
None => Err(ReedlineError(ReedlineErrorVariants::OtherHistoryError(
"No command run",
))),
}
}
/// Wait for input and provide the user with a specified [`Prompt`].
///
/// Returns a [`std::io::Result`] in which the `Err` type is [`std::io::Result`]
/// and the `Ok` variant wraps a [`Signal`] which handles user inputs.
pub fn read_line(&mut self, prompt: &dyn Prompt) -> Result<Signal> {
terminal::enable_raw_mode()?;
self.bracketed_paste.enter();
self.kitty_protocol.enter();
let result = self.read_line_helper(prompt);
self.bracketed_paste.exit();
self.kitty_protocol.exit();
terminal::disable_raw_mode()?;
result
}
/// Returns the current insertion point of the input buffer.
pub fn current_insertion_point(&self) -> usize {
self.editor.insertion_point()
}
/// Returns the current contents of the input buffer.
pub fn current_buffer_contents(&self) -> &str {
self.editor.get_buffer()
}
/// Writes `msg` to the terminal with a following carriage return and newline
fn print_line(&mut self, msg: &str) -> Result<()> {
self.painter.paint_line(msg)
}
/// Clear the screen by printing enough whitespace to start the prompt or
/// other output back at the first line of the terminal.
pub fn clear_screen(&mut self) -> Result<()> {
self.painter.clear_screen()?;
Ok(())
}
/// Clear the screen and the scrollback buffer of the terminal
pub fn clear_scrollback(&mut self) -> Result<()> {
self.painter.clear_scrollback()?;
Ok(())
}
/// Helper implementing the logic for [`Reedline::read_line()`] to be wrapped
/// in a `raw_mode` context.
fn read_line_helper(&mut self, prompt: &dyn Prompt) -> Result<Signal> {
if self.executing_host_command {
self.executing_host_command = false;
} else {
self.painter.initialize_prompt_position()?;
self.hide_hints = false;
}
self.repaint(prompt)?;
let mut crossterm_events: Vec<ReedlineRawEvent> = vec![];
let mut reedline_events: Vec<ReedlineEvent> = vec![];
loop {
let mut paste_enter_state = false;
#[cfg(feature = "external_printer")]
if let Some(ref external_printer) = self.external_printer {
// get messages from printer as crlf separated "lines"
let messages = Self::external_messages(external_printer)?;
if !messages.is_empty() {
// print the message(s)
self.painter.print_external_message(
messages,
self.editor.line_buffer(),
prompt,
)?;
self.repaint(prompt)?;
}
}
let mut latest_resize = None;
loop {
match event::read()? {
Event::Resize(x, y) => {
latest_resize = Some((x, y));
}
enter @ Event::Key(KeyEvent {
code: KeyCode::Enter,
modifiers: KeyModifiers::NONE,
..
}) => {
let enter = ReedlineRawEvent::convert_from(enter);
if let Some(enter) = enter {
crossterm_events.push(enter);
// Break early to check if the input is complete and
// can be send to the hosting application. If
// multiple complete entries are submitted, events
// are still in the crossterm queue for us to
// process.
paste_enter_state = crossterm_events.len() > EVENTS_THRESHOLD;
break;
}
}
x => {
let raw_event = ReedlineRawEvent::convert_from(x);
if let Some(evt) = raw_event {
crossterm_events.push(evt);
}
}
}
// There could be multiple events queued up!
// pasting text, resizes, blocking this thread (e.g. during debugging)
// We should be able to handle all of them as quickly as possible without causing unnecessary output steps.
if !event::poll(Duration::from_millis(POLL_WAIT))? {
break;
}
}
if let Some((x, y)) = latest_resize {
reedline_events.push(ReedlineEvent::Resize(x, y));
}
// Accelerate pasted text by fusing `EditCommand`s
//
// (Text should only be `EditCommand::InsertChar`s)
let mut last_edit_commands = None;
for event in crossterm_events.drain(..) {
match (&mut last_edit_commands, self.edit_mode.parse_event(event)) {
(None, ReedlineEvent::Edit(ec)) => {
last_edit_commands = Some(ec);
}
(None, other_event) => {
reedline_events.push(other_event);
}
(Some(ref mut last_ecs), ReedlineEvent::Edit(ec)) => {
last_ecs.extend(ec);
}
(ref mut a @ Some(_), other_event) => {
reedline_events.push(ReedlineEvent::Edit(a.take().unwrap()));
reedline_events.push(other_event);
}
}
}
if let Some(ec) = last_edit_commands {
reedline_events.push(ReedlineEvent::Edit(ec));
}
for event in reedline_events.drain(..) {
match self.handle_event(prompt, event)? {
EventStatus::Exits(signal) => {
if !self.executing_host_command {
// Move the cursor below the input area, for external commands or new read_line call
self.painter.move_cursor_to_end()?;
}
return Ok(signal);
}
EventStatus::Handled => {
if !paste_enter_state {
self.repaint(prompt)?;
}
}
EventStatus::Inapplicable => {
// Nothing changed, no need to repaint
}
}
}
}
}
fn handle_event(&mut self, prompt: &dyn Prompt, event: ReedlineEvent) -> Result<EventStatus> {
if self.input_mode == InputMode::HistorySearch {
self.handle_history_search_event(event)
} else {
self.handle_editor_event(prompt, event)
}
}
fn handle_history_search_event(&mut self, event: ReedlineEvent) -> io::Result<EventStatus> {
match event {
ReedlineEvent::UntilFound(events) => {
for event in events {
match self.handle_history_search_event(event)? {
EventStatus::Inapplicable => {
// Try again with the next event handler
}
success => {
return Ok(success);
}
}
}
// Exhausting the event handlers is still considered handled
Ok(EventStatus::Handled)
}
ReedlineEvent::CtrlD => {
if self.editor.is_empty() {
self.input_mode = InputMode::Regular;
self.editor.reset_undo_stack();
Ok(EventStatus::Exits(Signal::CtrlD))
} else {
self.run_history_commands(&[EditCommand::Delete]);
Ok(EventStatus::Handled)
}
}
ReedlineEvent::CtrlC => {
self.input_mode = InputMode::Regular;
Ok(EventStatus::Exits(Signal::CtrlC))
}
ReedlineEvent::ClearScreen => {
self.painter.clear_screen()?;
Ok(EventStatus::Handled)
}
ReedlineEvent::ClearScrollback => {
self.painter.clear_scrollback()?;
Ok(EventStatus::Handled)
}
ReedlineEvent::Enter
| ReedlineEvent::HistoryHintComplete
| ReedlineEvent::Submit
| ReedlineEvent::SubmitOrNewline => {
if let Some(string) = self.history_cursor.string_at_cursor() {
self.editor
.set_buffer(string, UndoBehavior::CreateUndoPoint);
}
self.input_mode = InputMode::Regular;
Ok(EventStatus::Handled)
}
ReedlineEvent::ExecuteHostCommand(host_command) => {
// TODO: Decide if we need to do something special to have a nicer painter state on the next go
self.executing_host_command = true;
Ok(EventStatus::Exits(Signal::Success(host_command)))
}
ReedlineEvent::Edit(commands) => {
self.run_history_commands(&commands);
Ok(EventStatus::Handled)
}
ReedlineEvent::Mouse => Ok(EventStatus::Handled),
ReedlineEvent::Resize(width, height) => {
self.painter.handle_resize(width, height);
Ok(EventStatus::Inapplicable)
}
ReedlineEvent::Repaint => {
// A handled Event causes a repaint
Ok(EventStatus::Handled)
}
ReedlineEvent::PreviousHistory | ReedlineEvent::Up | ReedlineEvent::SearchHistory => {
self.history_cursor
.back(self.history.as_ref())
.expect("todo: error handling");
Ok(EventStatus::Handled)
}
ReedlineEvent::NextHistory | ReedlineEvent::Down => {
self.history_cursor
.forward(self.history.as_ref())
.expect("todo: error handling");
// Hacky way to ensure that we don't fall of into failed search going forward
if self.history_cursor.string_at_cursor().is_none() {
self.history_cursor
.back(self.history.as_ref())
.expect("todo: error handling");
}
Ok(EventStatus::Handled)
}
ReedlineEvent::Esc => {
self.input_mode = InputMode::Regular;
Ok(EventStatus::Handled)
}
// TODO: Check if events should be handled
ReedlineEvent::Right
| ReedlineEvent::Left
| ReedlineEvent::Multiple(_)
| ReedlineEvent::None
| ReedlineEvent::HistoryHintWordComplete
| ReedlineEvent::OpenEditor
| ReedlineEvent::Menu(_)
| ReedlineEvent::MenuNext
| ReedlineEvent::MenuPrevious
| ReedlineEvent::MenuUp
| ReedlineEvent::MenuDown
| ReedlineEvent::MenuLeft
| ReedlineEvent::MenuRight
| ReedlineEvent::MenuPageNext
| ReedlineEvent::MenuPagePrevious => Ok(EventStatus::Inapplicable),
}
}
fn handle_editor_event(
&mut self,
prompt: &dyn Prompt,
event: ReedlineEvent,
) -> io::Result<EventStatus> {
match event {
ReedlineEvent::Menu(name) => {
if self.active_menu().is_none() {
if let Some(menu) = self.menus.iter_mut().find(|menu| menu.name() == name) {
menu.menu_event(MenuEvent::Activate(self.quick_completions));
if self.quick_completions && menu.can_quick_complete() {
menu.update_values(
&mut self.editor,
self.completer.as_mut(),
self.history.as_ref(),
);
if menu.get_values().len() == 1 {
return self.handle_editor_event(prompt, ReedlineEvent::Enter);
}
}
if self.partial_completions
&& menu.can_partially_complete(
self.quick_completions,
&mut self.editor,
self.completer.as_mut(),
self.history.as_ref(),
)
{
return Ok(EventStatus::Handled);
}
return Ok(EventStatus::Handled);
}
}
Ok(EventStatus::Inapplicable)
}
ReedlineEvent::MenuNext => match self.active_menu() {
None => Ok(EventStatus::Inapplicable),
Some(menu) => {
if menu.get_values().len() == 1 && menu.can_quick_complete() {
self.handle_editor_event(prompt, ReedlineEvent::Enter)
} else {
menu.menu_event(MenuEvent::NextElement);
Ok(EventStatus::Handled)
}
}
},
ReedlineEvent::MenuPrevious => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::PreviousElement);
Ok(EventStatus::Handled)
})
}
ReedlineEvent::MenuUp => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::MoveUp);
Ok(EventStatus::Handled)
})
}
ReedlineEvent::MenuDown => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::MoveDown);
Ok(EventStatus::Handled)
})
}
ReedlineEvent::MenuLeft => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::MoveLeft);
Ok(EventStatus::Handled)
})
}
ReedlineEvent::MenuRight => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::MoveRight);
Ok(EventStatus::Handled)
})
}
ReedlineEvent::MenuPageNext => {
self.active_menu()
.map_or(Ok(EventStatus::Inapplicable), |menu| {
menu.menu_event(MenuEvent::NextPage);