-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
reader.rs
5631 lines (5094 loc) · 212 KB
/
reader.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
//! Functions for reading data from stdin and passing to the parser. If stdin is a keyboard, it
//! supplies a killring, history, syntax highlighting, tab-completion and various other interactive
//! features.
//!
//! Internally the interactive mode functions rely in the functions of the input library to read
//! individual characters of input.
//!
//! Token search is handled incrementally. Actual searches are only done on when searching backwards,
//! since the previous results are saved. The last search position is remembered and a new search
//! continues from the last search position. All search results are saved in the list 'search_prev'.
//! When the user searches forward, i.e. presses Alt-down, the list is consulted for previous search
//! result, and subsequent backwards searches are also handled by consulting the list up until the
//! end of the list is reached, at which point regular searching will commence.
use libc::{
c_char, c_int, ECHO, EINTR, EIO, EISDIR, ENOTTY, EPERM, ESRCH, ICANON, ICRNL, IEXTEN, INLCR,
IXOFF, IXON, ONLCR, OPOST, O_NONBLOCK, O_RDONLY, SIGINT, SIGTTIN, STDIN_FILENO, STDOUT_FILENO,
S_IFDIR, TCSANOW, VMIN, VQUIT, VSUSP, VTIME, _POSIX_VDISABLE,
};
use nix::fcntl::OFlag;
use nix::sys::stat::Mode;
use once_cell::sync::Lazy;
use std::cell::UnsafeCell;
use std::cmp;
use std::io::BufReader;
use std::io::Write;
use std::num::NonZeroUsize;
use std::ops::ControlFlow;
use std::ops::Range;
use std::os::fd::RawFd;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::Ordering;
use std::sync::atomic::{AtomicI32, AtomicU32, AtomicU64, AtomicU8};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use errno::{errno, Errno};
use crate::abbrs::abbrs_match;
use crate::ast::{self, Ast, Category, Traversal};
use crate::builtins::shared::STATUS_CMD_OK;
use crate::color::RgbColor;
use crate::common::{
escape, escape_string, exit_without_destructors, get_ellipsis_char, get_obfuscation_read_char,
redirect_tty_output, scoped_push_replacer, scoped_push_replacer_ctx, shell_modes, str2wcstring,
wcs2string, write_loop, EscapeFlags, EscapeStringStyle, ScopeGuard, ScopeGuarding,
PROGRAM_NAME, UTF8_BOM_WCHAR,
};
use crate::complete::{
complete, complete_load, sort_and_prioritize, CompleteFlags, Completion, CompletionList,
CompletionRequestOptions,
};
use crate::editable_line::{Edit, EditableLine};
use crate::env::{EnvMode, Environment, Statuses};
use crate::exec::exec_subshell;
use crate::expand::{expand_string, expand_tilde, ExpandFlags, ExpandResultCode};
use crate::fallback::fish_wcwidth;
use crate::fd_readable_set::poll_fd_readable;
use crate::fds::{make_fd_blocking, wopen_cloexec, AutoCloseFd};
use crate::flog::{FLOG, FLOGF};
#[allow(unused_imports)]
use crate::future::IsSomeAnd;
use crate::global_safety::RelaxedAtomicBool;
use crate::highlight::{
autosuggest_validate_from_history, highlight_shell, HighlightRole, HighlightSpec,
};
use crate::history::{
history_session_id, in_private_mode, History, HistorySearch, PersistenceMode, SearchDirection,
SearchType,
};
use crate::input::init_input;
use crate::input::Inputter;
use crate::input_common::IS_TMUX;
use crate::input_common::{
focus_events_enable_ifn, terminal_protocols_enable_scoped, CharEvent, CharInputStyle,
ReadlineCmd,
};
use crate::io::IoChain;
use crate::kill::{kill_add, kill_replace, kill_yank, kill_yank_rotate};
use crate::libc::MB_CUR_MAX;
use crate::nix::isatty;
use crate::operation_context::{get_bg_context, OperationContext};
use crate::output::Outputter;
use crate::pager::{PageRendering, Pager, SelectionMotion};
use crate::parse_constants::SourceRange;
use crate::parse_constants::{ParseTreeFlags, ParserTestErrorBits};
use crate::parse_tree::ParsedSource;
use crate::parse_util::MaybeParentheses;
use crate::parse_util::SPACES_PER_INDENT;
use crate::parse_util::{
parse_util_cmdsubst_extent, parse_util_compute_indents, parse_util_contains_wildcards,
parse_util_detect_errors, parse_util_detect_errors_in_ast, parse_util_escape_string_with_quote,
parse_util_escape_wildcards, parse_util_get_line_from_offset, parse_util_get_offset,
parse_util_get_offset_from_line, parse_util_lineno, parse_util_locate_cmdsubst_range,
parse_util_token_extent,
};
use crate::parser::{BlockType, EvalRes, Parser, ParserRef};
use crate::proc::{
have_proc_stat, hup_jobs, is_interactive_session, job_reap, jobs_requiring_warning_on_exit,
print_exit_warning_for_jobs, proc_update_jiffies,
};
use crate::reader_history_search::{smartcase_flags, ReaderHistorySearch, SearchMode};
use crate::screen::{screen_clear, screen_force_clear_to_end, Screen};
use crate::signal::{
signal_check_cancel, signal_clear_cancel, signal_reset_handlers, signal_set_handlers,
signal_set_handlers_once,
};
use crate::termsize::{termsize_invalidate_tty, termsize_last, termsize_update};
use crate::threads::{
assert_is_background_thread, assert_is_main_thread, iothread_service_main_with_timeout,
Debounce,
};
use crate::tokenizer::quote_end;
use crate::tokenizer::{
tok_command, MoveWordStateMachine, MoveWordStyle, TokenType, Tokenizer, TOK_ACCEPT_UNFINISHED,
TOK_SHOW_COMMENTS,
};
use crate::wchar::prelude::*;
use crate::wcstringutil::{
count_preceding_backslashes, join_strings, string_prefixes_string,
string_prefixes_string_case_insensitive, StringFuzzyMatch,
};
use crate::wildcard::wildcard_has;
use crate::wutil::{perror, write_to_fd};
use crate::{abbrs, event, function, history};
/// A description of where fish is in the process of exiting.
#[repr(u8)]
enum ExitState {
/// fish is not exiting.
None,
/// fish intends to exit, and is running handlers like 'fish_exit'.
RunningHandlers,
/// fish is finished running handlers and no more fish script may be run.
FinishedHandlers,
}
static EXIT_STATE: AtomicU8 = AtomicU8::new(ExitState::None as u8);
pub static SHELL_MODES: Lazy<Mutex<libc::termios>> =
Lazy::new(|| Mutex::new(unsafe { std::mem::zeroed() }));
/// Mode on startup, which we restore on exit.
pub static TERMINAL_MODE_ON_STARTUP: Lazy<Mutex<libc::termios>> =
Lazy::new(|| Mutex::new(unsafe { std::mem::zeroed() }));
/// Mode we use to execute programs.
static TTY_MODES_FOR_EXTERNAL_CMDS: Lazy<Mutex<libc::termios>> =
Lazy::new(|| Mutex::new(unsafe { std::mem::zeroed() }));
static RUN_COUNT: AtomicU64 = AtomicU64::new(0);
static STATUS_COUNT: AtomicU64 = AtomicU64::new(0);
/// This variable is set to a signal by the signal handler when ^C is pressed.
static INTERRUPTED: AtomicI32 = AtomicI32::new(0);
/// If set, SIGHUP has been received. This latches to true.
/// This is set from a signal handler.
static SIGHUP_RECEIVED: RelaxedAtomicBool = RelaxedAtomicBool::new(false);
/// A singleton snapshot of the reader state. This is factored out for thread-safety reasons:
/// it may be fetched on a background thread.
fn commandline_state_snapshot() -> MutexGuard<'static, CommandlineState> {
static STATE: Mutex<CommandlineState> = Mutex::new(CommandlineState::new());
STATE.lock().unwrap()
}
/// Any time the contents of a buffer changes, we update the generation count. This allows for our
/// background threads to notice it and skip doing work that they would otherwise have to do.
static GENERATION: AtomicU32 = AtomicU32::new(0);
/// Get the debouncer for autosuggestions and background highlighting.
fn debounce_autosuggestions() -> &'static Debounce {
const AUTOSUGGEST_TIMEOUT: Duration = Duration::from_millis(500);
static RES: once_cell::race::OnceBox<Debounce> = once_cell::race::OnceBox::new();
RES.get_or_init(|| Box::new(Debounce::new(AUTOSUGGEST_TIMEOUT)))
}
fn debounce_highlighting() -> &'static Debounce {
const HIGHLIGHT_TIMEOUT: Duration = Duration::from_millis(500);
static RES: once_cell::race::OnceBox<Debounce> = once_cell::race::OnceBox::new();
RES.get_or_init(|| Box::new(Debounce::new(HIGHLIGHT_TIMEOUT)))
}
fn debounce_history_pager() -> &'static Debounce {
const HISTORY_PAGER_TIMEOUT: Duration = Duration::from_millis(500);
static RES: once_cell::race::OnceBox<Debounce> = once_cell::race::OnceBox::new();
RES.get_or_init(|| Box::new(Debounce::new(HISTORY_PAGER_TIMEOUT)))
}
fn redirect_tty_after_sighup() {
// If we have received SIGHUP, redirect the tty to avoid a user script triggering SIGTTIN or
// SIGTTOU.
assert!(reader_received_sighup(), "SIGHUP not received");
static TTY_REDIRECTED: RelaxedAtomicBool = RelaxedAtomicBool::new(false);
if !TTY_REDIRECTED.swap(true) {
redirect_tty_output();
}
}
/// The stack of current interactive reading contexts.
fn reader_data_stack() -> &'static mut Vec<Pin<Box<ReaderData>>> {
struct ReaderDataStack(UnsafeCell<Vec<Pin<Box<ReaderData>>>>);
// Safety: only used on main thread.
unsafe impl Sync for ReaderDataStack {}
static mut READER_DATA_STACK: ReaderDataStack = ReaderDataStack(UnsafeCell::new(vec![]));
assert_is_main_thread();
unsafe { READER_DATA_STACK.0.get_mut() }
}
/// Access the top level reader data.
pub fn current_data() -> Option<&'static mut ReaderData> {
reader_data_stack()
.last_mut()
.map(|data| unsafe { Pin::get_unchecked_mut(Pin::as_mut(data)) })
}
pub use current_data as reader_current_data;
/// Add a new reader to the reader stack.
/// \return a shared pointer to it.
fn reader_push_ret(
parser: &Parser,
history_name: &wstr,
conf: ReaderConfig,
) -> &'static mut ReaderData {
assert_is_main_thread();
let hist = History::with_name(history_name);
hist.resolve_pending();
let data = ReaderData::new(parser.shared(), hist, conf);
reader_data_stack().push(data);
let data = current_data().unwrap();
data.command_line_changed(EditableLineTag::Commandline);
if reader_data_stack().len() == 1 {
reader_interactive_init(parser);
}
data
}
/// Push a new reader environment controlled by \p conf, using the given history name.
/// If \p history_name is empty, then save history in-memory only; do not write it to disk.
pub fn reader_push(parser: &Parser, history_name: &wstr, conf: ReaderConfig) {
// Public variant which discards the return value.
reader_push_ret(parser, history_name, conf);
}
/// Return to previous reader environment.
pub fn reader_pop() {
assert_is_main_thread();
reader_data_stack().pop().unwrap();
if let Some(new_reader) = current_data() {
new_reader
.screen
.reset_abandoning_line(usize::try_from(termsize_last().width).unwrap());
} else {
reader_interactive_destroy();
*commandline_state_snapshot() = CommandlineState::new();
}
}
/// Configuration that we provide to a reader.
#[derive(Default)]
pub struct ReaderConfig {
/// Left prompt command, typically fish_prompt.
pub left_prompt_cmd: WString,
/// Right prompt command, typically fish_right_prompt.
pub right_prompt_cmd: WString,
/// Name of the event to trigger once we're set up.
pub event: &'static wstr,
/// Whether tab completion is OK.
pub complete_ok: bool,
/// Whether to perform syntax highlighting.
pub highlight_ok: bool,
/// Whether to perform syntax checking before returning.
pub syntax_check_ok: bool,
/// Whether to allow autosuggestions.
pub autosuggest_ok: bool,
/// Whether to expand abbreviations.
pub expand_abbrev_ok: bool,
/// Whether to exit on interrupt (^C).
pub exit_on_interrupt: bool,
/// If set, do not show what is typed.
pub in_silent_mode: bool,
/// The fd for stdin, default to actual stdin.
pub inputfd: RawFd,
}
/// Snapshotted state from the reader.
#[derive(Clone, Default)]
pub struct CommandlineState {
/// command line text, or empty if not interactive
pub text: WString,
/// position of the cursor, may be as large as text.size()
pub cursor_pos: usize,
/// visual selection, or none if none
pub selection: Option<Range<usize>>,
/// current reader history, or null if not interactive
pub history: Option<Arc<History>>,
/// pager is visible
pub pager_mode: bool,
/// pager already shows everything if possible
pub pager_fully_disclosed: bool,
/// The search field, if shown.
pub search_field: Option<(WString, usize)>,
/// pager is visible and search is active
pub search_mode: bool,
/// if false, the reader has not yet been entered
pub initialized: bool,
}
impl CommandlineState {
const fn new() -> Self {
Self {
text: WString::new(),
cursor_pos: 0,
selection: None,
history: None,
pager_mode: false,
pager_fully_disclosed: false,
search_field: None,
search_mode: false,
initialized: false,
}
}
}
/// Strategy for determining how the selection behaves.
#[derive(Eq, PartialEq)]
pub enum CursorSelectionMode {
/// The character at/after the cursor is excluded.
/// This is most useful with a line cursor shape.
Exclusive,
/// The character at/after the cursor is included.
/// This is most useful with a block or underscore cursor shape.
Inclusive,
}
#[derive(Eq, PartialEq)]
pub enum CursorEndMode {
Exclusive,
Inclusive,
}
/// A mode for calling the reader_kill function.
enum Kill {
/// In this mode, the new string is appended to the current contents of the kill buffer.
Append,
/// In this mode, the new string is prepended to the current contents of the kill buffer.
Prepend,
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum JumpDirection {
Forward,
Backward,
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum JumpPrecision {
Till,
To,
}
/// readline_loop_state_t encapsulates the state used in a readline loop.
struct ReadlineLoopState {
/// The last command that was executed.
last_cmd: Option<ReadlineCmd>,
/// If the last command was a yank, the length of yanking that occurred.
yank_len: usize,
/// If the last "complete" readline command has inserted text into the command line.
complete_did_insert: bool,
/// List of completions.
comp: Vec<Completion>,
/// Whether the loop has finished, due to reaching the character limit or through executing a
/// command.
finished: bool,
/// Maximum number of characters to read.
nchars: Option<NonZeroUsize>,
}
impl ReadlineLoopState {
fn new() -> Self {
Self {
last_cmd: None,
yank_len: 0,
complete_did_insert: true,
comp: vec![],
finished: false,
nchars: None,
}
}
}
/// Data wrapping up the visual selection.
#[derive(Clone, Copy, Default, Eq, PartialEq)]
struct SelectionData {
/// The position of the cursor when selection was initiated.
begin: usize,
/// The start and stop position of the current selection.
start: usize,
stop: usize,
}
/// A value-type struct representing a layout that can be rendered.
/// The intent is that everything we send to the screen is encapsulated in this struct.
#[derive(Clone, Default)]
struct LayoutData {
/// Text of the command line.
text: WString,
/// The colors. This has the same length as 'text'.
colors: Vec<HighlightSpec>,
/// Position of the cursor in the command line.
position: usize,
/// Whether the cursor is focused on the pager or not.
focused_on_pager: bool,
/// Visual selection of the command line, or none if none.
selection: Option<SelectionData>,
/// String containing the autosuggestion.
autosuggestion: WString,
/// The matching range of the command line from a history search. If non-empty, then highlight
/// the range within the text.
history_search_range: Option<SourceRange>,
/// The result of evaluating the left, mode and right prompt commands.
/// That is, this the text of the prompts, not the commands to produce them.
left_prompt_buff: WString,
mode_prompt_buff: WString,
right_prompt_buff: WString,
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum EditableLineTag {
Commandline,
SearchField,
}
/// A struct describing the state of the interactive reader. These states can be stacked, in case
/// reader_readline() calls are nested. This happens when the 'read' builtin is used.
pub struct ReaderData {
/// We could put the entire thing in an Rc but Rc::get_unchecked_mut is not yet stable.
/// This is sufficient for our use.
canary: Rc<()>,
/// Configuration for the reader.
conf: ReaderConfig,
/// The parser being used.
parser_ref: ParserRef,
/// String containing the whole current commandline.
command_line: EditableLine,
/// Whether the most recent modification to the command line was done by either history search
/// or a pager selection change. When this is true and another transient change is made, the
/// old transient change will be removed from the undo history.
command_line_has_transient_edit: bool,
/// The most recent layout data sent to the screen.
rendered_layout: LayoutData,
/// The current autosuggestion.
autosuggestion: Autosuggestion,
/// Current pager.
pager: Pager,
/// The output of the pager.
current_page_rendering: PageRendering,
/// When backspacing, we temporarily suppress autosuggestions.
suppress_autosuggestion: bool,
/// HACK: A flag to reset the loop state from the outside.
reset_loop_state: bool,
/// Whether this is the first prompt.
first_prompt: bool,
/// The time when the last flash() completed
last_flash: Option<Instant>,
/// The representation of the current screen contents.
screen: Screen,
/// The source of input events.
inputter: Inputter,
/// The history.
history: Arc<History>,
/// The history search.
history_search: ReaderHistorySearch,
/// Whether the in-pager history search is active.
history_pager_active: bool,
/// The direction of the last successful history pager search.
history_pager_direction: SearchDirection,
/// The range in history covered by the history pager's current page.
history_pager_history_index_start: usize,
history_pager_history_index_end: usize,
/// The cursor selection mode.
cursor_selection_mode: CursorSelectionMode,
cursor_end_mode: CursorEndMode,
/// The selection data. If this is not none, then we have an active selection.
selection: Option<SelectionData>,
left_prompt_buff: WString,
mode_prompt_buff: WString,
/// The output of the last evaluation of the right prompt command.
right_prompt_buff: WString,
/// When navigating the pager, we modify the command line.
/// This is the saved command line before modification.
cycle_command_line: WString,
cycle_cursor_pos: usize,
/// If set, a key binding or the 'exit' command has asked us to exit our read loop.
exit_loop_requested: bool,
/// If this is true, exit reader even if there are running jobs. This happens if we press e.g.
/// ^D twice.
did_warn_for_bg_jobs: bool,
/// The current contents of the top item in the kill ring.
kill_item: WString,
/// A flag which may be set to force re-execing all prompts and re-rendering.
/// This may come about when a color like $fish_color... has changed.
force_exec_prompt_and_repaint: bool,
/// The target character of the last jump command.
last_jump_target: Option<char>,
last_jump_direction: JumpDirection,
last_jump_precision: JumpPrecision,
/// The text of the most recent asynchronous highlight and autosuggestion requests.
/// If these differs from the text of the command line, then we must kick off a new request.
in_flight_highlight_request: WString,
in_flight_autosuggest_request: WString,
rls: Option<ReadlineLoopState>,
}
/// Read commands from \c fd until encountering EOF.
/// The fd is not closed.
pub fn reader_read(parser: &Parser, fd: RawFd, io: &IoChain) -> c_int {
// If reader_read is called recursively through the '.' builtin, we need to preserve
// is_interactive. This, and signal handler setup is handled by
// proc_push_interactive/proc_pop_interactive.
let mut interactive = false;
// This block is a hack to work around https://sourceware.org/bugzilla/show_bug.cgi?id=20632.
// See also, commit 396bf12. Without the need for this workaround we would just write:
// int inter = ((fd == STDIN_FILENO) && isatty(STDIN_FILENO));
if fd == STDIN_FILENO {
let mut t: libc::termios = unsafe { std::mem::zeroed() };
if isatty(STDIN_FILENO) {
interactive = true;
} else if unsafe { libc::tcgetattr(STDIN_FILENO, &mut t) } == -1 && errno().0 == EIO {
redirect_tty_output();
interactive = true;
}
}
let _interactive_push = scoped_push_replacer(
|new_value| std::mem::replace(&mut parser.libdata_mut().pods.is_interactive, new_value),
interactive,
);
signal_set_handlers_once(interactive);
let res = if interactive {
read_i(parser)
} else {
read_ni(parser, fd, io)
};
// If the exit command was called in a script, only exit the script, not the program.
parser.libdata_mut().pods.exit_current_script = false;
res
}
/// Read interactively. Read input from stdin while providing editing facilities.
fn read_i(parser: &Parser) -> i32 {
assert_is_main_thread();
parser.assert_can_execute();
let mut conf = ReaderConfig::default();
conf.complete_ok = true;
conf.highlight_ok = true;
conf.syntax_check_ok = true;
conf.autosuggest_ok = check_autosuggestion_enabled(parser.vars());
conf.expand_abbrev_ok = true;
conf.event = L!("fish_prompt");
if parser.is_breakpoint() && function::exists(DEBUG_PROMPT_FUNCTION_NAME, parser) {
conf.left_prompt_cmd = DEBUG_PROMPT_FUNCTION_NAME.to_owned();
conf.right_prompt_cmd.clear();
} else {
conf.left_prompt_cmd = LEFT_PROMPT_FUNCTION_NAME.to_owned();
conf.right_prompt_cmd = RIGHT_PROMPT_FUNCTION_NAME.to_owned();
}
let data = reader_push_ret(parser, &history_session_id(parser.vars()), conf);
data.import_history_if_necessary();
while !check_exit_loop_maybe_warning(Some(data)) {
RUN_COUNT.fetch_add(1, Ordering::Relaxed);
let Some(command) = data.readline(None) else {
continue;
};
if command.is_empty() {
continue;
}
data.command_line.clear();
data.update_buff_pos(EditableLineTag::Commandline, None);
data.command_line_changed(EditableLineTag::Commandline);
data.screen.write_bytes(b"\x1b]133;C\x07");
event::fire_generic(parser, L!("fish_preexec").to_owned(), vec![command.clone()]);
let eval_res = reader_run_command(parser, &command);
signal_clear_cancel();
if !eval_res.no_status {
STATUS_COUNT.fetch_add(1, Ordering::Relaxed);
}
// If the command requested an exit, then process it now and clear it.
data.exit_loop_requested |= parser.libdata().pods.exit_current_script;
parser.libdata_mut().pods.exit_current_script = false;
let _ = write!(
Outputter::stdoutput().borrow_mut(),
"\x1b]133;D;{}\x07",
parser.get_last_status()
);
event::fire_generic(parser, L!("fish_postexec").to_owned(), vec![command]);
// Allow any pending history items to be returned in the history array.
data.history.resolve_pending();
let already_warned = data.did_warn_for_bg_jobs;
if check_exit_loop_maybe_warning(Some(data)) {
break;
}
if already_warned {
// We had previously warned the user and they ran another command.
// Reset the warning.
data.did_warn_for_bg_jobs = false;
}
}
reader_pop();
// If we got SIGHUP, ensure the tty is redirected.
if reader_received_sighup() {
// If we are the top-level reader, then we translate SIGHUP into exit_forced.
redirect_tty_after_sighup();
}
// If we are the last reader, then kill remaining jobs before exiting.
if reader_data_stack().is_empty() {
// Send the exit event and then commit to not executing any more fish script.
EXIT_STATE.store(ExitState::RunningHandlers as u8, Ordering::Relaxed);
event::fire_generic(parser, L!("fish_exit").to_owned(), vec![]);
EXIT_STATE.store(ExitState::FinishedHandlers as u8, Ordering::Relaxed);
hup_jobs(&parser.jobs());
}
0
}
/// Read non-interactively. Read input from stdin without displaying the prompt, using syntax
/// highlighting. This is used for reading scripts and init files.
/// The file is not closed.
fn read_ni(parser: &Parser, fd: RawFd, io: &IoChain) -> i32 {
let mut buf: libc::stat = unsafe { std::mem::zeroed() };
if unsafe { libc::fstat(fd, &mut buf) } == -1 {
let err = errno();
FLOG!(
error,
wgettext_fmt!("Unable to read input file: %s", err.to_string())
);
return 1;
}
/* FreeBSD allows read() on directories. Error explicitly in that case. */
// XXX: This can be triggered spuriously, so we'll not do that for stdin.
// This can be seen e.g. with node's "spawn" api.
if fd != STDIN_FILENO && (buf.st_mode & S_IFDIR) != 0 {
FLOG!(
error,
wgettext_fmt!("Unable to read input file: %s", Errno(EISDIR).to_string())
);
return 1;
}
// Read all data into a vec.
let mut fd_contents = Vec::with_capacity(usize::try_from(buf.st_size).unwrap());
loop {
let mut buff = [0_u8; 4096];
match nix::unistd::read(fd, &mut buff) {
Ok(0) => {
// EOF.
break;
}
Ok(amt) => {
fd_contents.extend_from_slice(&buff[..amt]);
}
Err(err) => {
if err == nix::Error::EINTR {
continue;
} else if (err == nix::Error::EAGAIN || err == nix::Error::EWOULDBLOCK)
&& make_fd_blocking(fd).is_ok()
{
// We succeeded in making the fd blocking, keep going.
continue;
} else {
// Fatal error.
FLOG!(
error,
wgettext_fmt!("Unable to read input file: %s", err.to_string())
);
return 1;
}
}
}
}
let mut s = str2wcstring(&fd_contents);
// Eagerly deallocate to save memory.
drop(fd_contents);
// Swallow a BOM (issue #1518).
if s.chars().next() == Some(UTF8_BOM_WCHAR) {
s.remove(0);
}
// Parse into an ast and detect errors.
let mut errors = vec![];
let ast = Ast::parse(&s, ParseTreeFlags::empty(), Some(&mut errors));
let mut errored = ast.errored();
if !errored {
errored = parse_util_detect_errors_in_ast(&ast, &s, Some(&mut errors)).is_err();
}
if errored {
let sb = parser.get_backtrace(&s, &errors);
eprintf!("%ls", sb);
return 1;
}
// Construct a parsed source ref.
// Be careful to transfer ownership, this could be a very large string.
let ps = Arc::new(ParsedSource::new(s, ast));
parser.eval_parsed_source(&ps, io, None, BlockType::top);
0
}
/// Initialize the reader.
pub fn reader_init() -> impl ScopeGuarding<Target = ()> {
// Save the initial terminal mode.
let mut terminal_mode_on_startup = TERMINAL_MODE_ON_STARTUP.lock().unwrap();
unsafe { libc::tcgetattr(STDIN_FILENO, &mut *terminal_mode_on_startup) };
// Set the mode used for program execution, initialized to the current mode.
let mut tty_modes_for_external_cmds = TTY_MODES_FOR_EXTERNAL_CMDS.lock().unwrap();
*tty_modes_for_external_cmds = *terminal_mode_on_startup;
term_fix_external_modes(&mut tty_modes_for_external_cmds);
// Disable flow control by default.
tty_modes_for_external_cmds.c_iflag &= !IXON;
tty_modes_for_external_cmds.c_iflag &= !IXOFF;
// Set the mode used for the terminal, initialized to the current mode.
*shell_modes() = *tty_modes_for_external_cmds;
term_fix_modes(&mut shell_modes());
drop(terminal_mode_on_startup);
drop(tty_modes_for_external_cmds);
// Set up our fixed terminal modes once,
// so we don't get flow control just because we inherited it.
let mut terminal_protocols = None;
if is_interactive_session() {
terminal_protocols = Some(terminal_protocols_enable_scoped());
if unsafe { libc::getpgrp() == libc::tcgetpgrp(STDIN_FILENO) } {
term_donate(/*quiet=*/ true);
}
}
ScopeGuard::new((), move |()| {
let _terminal_protocols = terminal_protocols;
restore_term_mode();
})
}
/// Restore the term mode if we own the terminal and are interactive (#8705).
/// It's important we do this before restore_foreground_process_group,
/// otherwise we won't think we own the terminal.
pub fn restore_term_mode() {
if !is_interactive_session() || unsafe { libc::getpgrp() != libc::tcgetpgrp(STDIN_FILENO) } {
return;
}
if unsafe {
libc::tcsetattr(
STDIN_FILENO,
TCSANOW,
&*TERMINAL_MODE_ON_STARTUP.lock().unwrap(),
) == -1
} && errno().0 == EIO
{
redirect_tty_output();
}
}
/// Change the history file for the current command reading context.
pub fn reader_change_history(name: &wstr) {
// We don't need to _change_ if we're not initialized yet.
let Some(data) = current_data() else {
return;
};
data.history.save();
data.history = History::with_name(name);
commandline_state_snapshot().history = Some(data.history.clone());
}
pub fn reader_change_cursor_selection_mode(selection_mode: CursorSelectionMode) {
// We don't need to _change_ if we're not initialized yet.
if let Some(data) = current_data() {
if data.cursor_selection_mode == selection_mode {
return;
}
let invalidates_selection = data.selection.is_some();
data.cursor_selection_mode = selection_mode;
if invalidates_selection {
data.update_buff_pos(EditableLineTag::Commandline, None);
}
}
}
pub fn reader_change_cursor_end_mode(end_mode: CursorEndMode) {
// We don't need to _change_ if we're not initialized yet.
if let Some(data) = current_data() {
if data.cursor_end_mode == end_mode {
return;
}
let invalidates_end = data.selection.is_some();
data.cursor_end_mode = end_mode;
if invalidates_end {
data.update_buff_pos(EditableLineTag::Commandline, None);
}
}
}
fn check_autosuggestion_enabled(vars: &dyn Environment) -> bool {
vars.get(L!("fish_autosuggestion_enabled"))
.map(|v| v.as_string())
.map(|v| v != L!("0"))
.unwrap_or(true)
}
/// Enable or disable autosuggestions based on the associated variable.
pub fn reader_set_autosuggestion_enabled(vars: &dyn Environment) {
// We don't need to _change_ if we're not initialized yet.
let Some(data) = current_data() else {
return;
};
let enable = check_autosuggestion_enabled(vars);
if data.conf.autosuggest_ok != enable {
data.conf.autosuggest_ok = enable;
data.force_exec_prompt_and_repaint = true;
data.inputter
.queue_char(CharEvent::from_readline(ReadlineCmd::Repaint));
}
}
/// Tell the reader that it needs to re-exec the prompt and repaint.
/// This may be called in response to e.g. a color variable change.
pub fn reader_schedule_prompt_repaint() {
assert_is_main_thread();
let Some(data) = current_data() else {
return;
};
if !data.force_exec_prompt_and_repaint {
data.force_exec_prompt_and_repaint = true;
data.inputter
.queue_char(CharEvent::from_readline(ReadlineCmd::Repaint));
}
}
pub fn reader_execute_readline_cmd(ch: CharEvent) {
if let Some(data) = current_data() {
let CharEvent::Readline(readline_cmd_evt) = &ch else {
panic!()
};
if matches!(
readline_cmd_evt.cmd,
ReadlineCmd::ClearScreenAndRepaint
| ReadlineCmd::RepaintMode
| ReadlineCmd::Repaint
| ReadlineCmd::ForceRepaint
) {
data.inputter.queue_char(ch);
return;
}
if data.rls.is_none() {
data.rls = Some(ReadlineLoopState::new());
}
data.save_screen_state();
data.handle_char_event(Some(ch));
}
}
/// Return the value of the interrupted flag, which is set by the sigint handler, and clear it if it
/// was set. If the current reader is interruptible, call \c reader_exit().
pub fn reader_reading_interrupted() -> i32 {
let res = reader_test_and_clear_interrupted();
if res == 0 {
return 0;
}
if let Some(data) = current_data() {
if data.conf.exit_on_interrupt {
data.exit_loop_requested = true;
// We handled the interrupt ourselves, our caller doesn't need to handle it.
return 0;
}
}
res
}
/// Read one line of input. Before calling this function, reader_push() must have been called in
/// order to set up a valid reader environment. If nchars > 0, return after reading that many
/// characters even if a full line has not yet been read. Note: the returned value may be longer
/// than nchars if a single keypress resulted in multiple characters being inserted into the
/// commandline.
pub fn reader_readline(nchars: usize) -> Option<WString> {
let nchars = NonZeroUsize::try_from(nchars).ok();
let data = current_data().unwrap();
data.readline(nchars)
}
/// Get the command line state. This may be fetched on a background thread.
pub fn commandline_get_state(sync: bool) -> CommandlineState {
if sync {
current_data().map(|data| data.update_commandline_state());
}
commandline_state_snapshot().clone()
}
/// Set the command line text and position. This may be called on a background thread; the reader
/// will pick it up when it is done executing.
pub fn commandline_set_buffer(text: WString, cursor_pos: Option<usize>) {
{
let mut state = commandline_state_snapshot();
state.cursor_pos = cmp::min(cursor_pos.unwrap_or(usize::MAX), text.len());
state.text = text;
}
current_data().map(|data| data.apply_commandline_state_changes());
}
pub fn commandline_set_search_field(text: WString, cursor_pos: Option<usize>) {
{
let mut state = commandline_state_snapshot();
assert!(state.search_field.is_some());
let new_pos = cmp::min(cursor_pos.unwrap_or(usize::MAX), text.len());
state.search_field = Some((text, new_pos));
}
current_data().map(|data| data.apply_commandline_state_changes());
}
/// Return the current interactive reads loop count. Useful for determining how many commands have
/// been executed between invocations of code.
pub fn reader_run_count() -> u64 {
RUN_COUNT.load(Ordering::Relaxed)
}
/// Returns the current "generation" of interactive status. Useful for determining whether the
/// previous command produced a status.
/// This is not incremented if the command being run produces no status,
/// (e.g. background job, or variable assignment).
pub fn reader_status_count() -> u64 {
STATUS_COUNT.load(Ordering::Relaxed)
}
// Name of the variable that tells how long it took, in milliseconds, for the previous
// interactive command to complete.