/
reader.cpp
3417 lines (2952 loc) · 132 KB
/
reader.cpp
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.
#include "config.h"
// IWYU pragma: no_include <type_traits>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include <wctype.h>
#include <algorithm>
#include <stack>
#ifdef HAVE_SIGINFO_H
#include <siginfo.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <assert.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <wchar.h>
#include <memory>
#include "color.h"
#include "common.h"
#include "complete.h"
#include "env.h"
#include "event.h"
#include "exec.h"
#include "expand.h"
#include "fallback.h" // IWYU pragma: keep
#include "function.h"
#include "highlight.h"
#include "history.h"
#include "input.h"
#include "input_common.h"
#include "intern.h"
#include "io.h"
#include "iothread.h"
#include "kill.h"
#include "output.h"
#include "pager.h"
#include "parse_constants.h"
#include "parse_tree.h"
#include "parse_util.h"
#include "parser.h"
#include "proc.h"
#include "reader.h"
#include "sanity.h"
#include "screen.h"
#include "signal.h"
#include "tokenizer.h"
#include "util.h"
#include "wutil.h" // IWYU pragma: keep
/// Maximum length of prefix string when printing completion list. Longer prefixes will be
/// ellipsized.
#define PREFIX_MAX_LEN 9
/// A simple prompt for reading shell commands that does not rely on fish specific commands, meaning
/// it will work even if fish is not installed. This is used by read_i.
#define DEFAULT_PROMPT L"echo -n \"$USER@\"(hostname|cut -d . -f 1)' '(__fish_pwd)'> '"
/// The name of the function that prints the fish prompt.
#define LEFT_PROMPT_FUNCTION_NAME L"fish_prompt"
/// The name of the function that prints the fish right prompt (RPROMPT).
#define RIGHT_PROMPT_FUNCTION_NAME L"fish_right_prompt"
/// The name of the function for getting the input mode indicator.
#define MODE_PROMPT_FUNCTION_NAME L"fish_mode_prompt"
/// The default title for the reader. This is used by reader_readline.
#define DEFAULT_TITLE L"echo $_ \" \"; __fish_pwd"
/// The maximum number of characters to read from the keyboard without repainting. Note that this
/// readahead will only occur if new characters are available for reading, fish will never block for
/// more input without repainting.
#define READAHEAD_MAX 256
/// A mode for calling the reader_kill function. In this mode, the new string is appended to the
/// current contents of the kill buffer.
#define KILL_APPEND 0
/// A mode for calling the reader_kill function. In this mode, the new string is prepended to the
/// current contents of the kill buffer.
#define KILL_PREPEND 1
/// History search mode. This value means that no search is currently performed.
#define NO_SEARCH 0
/// History search mode. This value means that we are performing a line history search.
#define LINE_SEARCH 1
/// History search mode. This value means that we are performing a token history search.
#define TOKEN_SEARCH 2
/// History search mode. This value means we are searching backwards.
#define SEARCH_BACKWARD 0
/// History search mode. This value means we are searching forwards.
#define SEARCH_FORWARD 1
/// Any time the contents of a buffer changes, we update the generation count. This allows for our
/// background highlighting thread to notice it and skip doing work that it would otherwise have to
/// do. This variable should really be of some kind of interlocked or atomic type that guarantees
/// we're not reading stale cache values. With C++11 we should use atomics, but until then volatile
/// should work as well, at least on x86.
static volatile unsigned int s_generation_count;
/// This pthreads generation count is set when an autosuggestion background thread starts up, so it
/// can easily check if the work it is doing is no longer useful.
static pthread_key_t generation_count_key;
static void set_command_line_and_position(editable_line_t *el, const wcstring &new_str, size_t pos);
void editable_line_t::insert_string(const wcstring &str, size_t start, size_t len) {
// Clamp the range to something valid.
size_t string_length = str.size();
start = mini(start, string_length); //!OCLINT(parameter reassignment)
len = mini(len, string_length - start); //!OCLINT(parameter reassignment)
this->text.insert(this->position, str, start, len);
this->position += len;
}
/// 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.
class reader_data_t {
public:
/// String containing the whole current commandline.
editable_line_t command_line;
/// String containing the autosuggestion.
wcstring autosuggestion;
/// Current pager.
pager_t pager;
/// Current page rendering.
page_rendering_t current_page_rendering;
/// Whether autosuggesting is allowed at all.
bool allow_autosuggestion;
/// When backspacing, we temporarily suppress autosuggestions.
bool suppress_autosuggestion;
/// Whether abbreviations are expanded.
bool expand_abbreviations;
/// The representation of the current screen contents.
screen_t screen;
/// The history.
history_t *history;
/// String containing the current search item.
wcstring search_buff;
/// History search.
history_search_t history_search;
/// Saved position used by token history search.
size_t token_history_pos;
/// Saved search string for token history search. Not handled by command_line_changed.
wcstring token_history_buff;
/// List for storing previous search results. Used to avoid duplicates.
wcstring_list_t search_prev;
/// The current position in search_prev.
size_t search_pos;
/// Indicates whether a selection is currently active.
bool sel_active;
/// The position of the cursor, when selection was initiated.
size_t sel_begin_pos;
/// The start position of the current selection, if one.
size_t sel_start_pos;
/// The stop position of the current selection, if one.
size_t sel_stop_pos;
/// Name of the current application.
wcstring app_name;
/// The prompt commands.
wcstring left_prompt;
wcstring right_prompt;
/// The output of the last evaluation of the prompt command.
wcstring left_prompt_buff;
/// The output of the last evaluation of the right prompt command.
wcstring right_prompt_buff;
/// Completion support.
wcstring cycle_command_line;
size_t cycle_cursor_pos;
/// Color is the syntax highlighting for buff. The format is that color[i] is the
/// classification (according to the enum in highlight.h) of buff[i].
std::vector<highlight_spec_t> colors;
/// An array defining the block level at each character.
std::vector<int> indents;
/// Function for tab completion.
complete_function_t complete_func;
/// Function for syntax highlighting.
highlight_function_t highlight_function;
/// Function for testing if the string can be returned.
parser_test_error_bits_t (*test_func)(const wchar_t *);
/// When this is true, the reader will exit.
bool end_loop;
/// If this is true, exit reader even if there are running jobs. This happens if we press e.g.
/// ^D twice.
bool prev_end_loop;
/// The current contents of the top item in the kill ring.
wcstring kill_item;
/// Pointer to previous reader_data.
reader_data_t *next;
/// This variable keeps state on if we are in search mode, and if yes, what mode.
int search_mode;
/// Keep track of whether any internal code has done something which is known to require a
/// repaint.
bool repaint_needed;
/// Whether a screen reset is needed after a repaint.
bool screen_reset_needed;
/// Whether the reader should exit on ^C.
bool exit_on_interrupt;
bool is_navigating_pager_contents() const { return this->pager.is_navigating_contents(); }
/// The line that is currently being edited. Typically the command line, but may be the search
/// field.
editable_line_t *active_edit_line() {
if (this->is_navigating_pager_contents() && this->pager.is_search_field_shown()) {
return &this->pager.search_field_line;
}
return &this->command_line;
}
/// Do what we need to do whenever our command line changes.
void command_line_changed(const editable_line_t *el);
/// Do what we need to do whenever our pager selection.
void pager_selection_changed();
/// Expand abbreviations at the current cursor position, minus backtrack_amt.
bool expand_abbreviation_as_necessary(size_t cursor_backtrack);
/// Constructor
reader_data_t()
: allow_autosuggestion(0),
suppress_autosuggestion(0),
expand_abbreviations(0),
history(0),
token_history_pos(0),
search_pos(0),
sel_active(0),
sel_begin_pos(0),
sel_start_pos(0),
sel_stop_pos(0),
cycle_cursor_pos(0),
complete_func(0),
highlight_function(0),
test_func(0),
end_loop(0),
prev_end_loop(0),
next(0),
search_mode(0),
repaint_needed(0),
screen_reset_needed(0),
exit_on_interrupt(0) {}
};
/// Sets the command line contents, without clearing the pager.
static void reader_set_buffer_maintaining_pager(const wcstring &b, size_t pos);
/// Clears the pager.
static void clear_pager();
/// The current interactive reading context.
static reader_data_t *data = 0;
/// This flag is set to true when fish is interactively reading from stdin. It changes how a ^C is
/// handled by the fish interrupt handler.
static int is_interactive_read;
/// Flag for ending non-interactive shell.
static int end_loop = 0;
/// The stack containing names of files that are being parsed.
static std::stack<const wchar_t *, std::vector<const wchar_t *> > current_filename;
/// This variable is set to true by the signal handler when ^C is pressed.
static volatile int interrupted = 0;
// Prototypes for a bunch of functions defined later on.
static bool is_backslashed(const wcstring &str, size_t pos);
static wchar_t unescaped_quote(const wcstring &str, size_t pos);
/// Mode on startup, which we restore on exit.
static struct termios terminal_mode_on_startup;
/// Mode we use to execute programs.
static struct termios terminal_mode_for_executing_programs;
static void reader_super_highlight_me_plenty(int highlight_pos_adjust = 0, bool no_io = false);
/// Variable to keep track of forced exits - see \c reader_exit_forced();
static int exit_forced;
/// Give up control of terminal.
static void term_donate() {
set_color(rgb_color_t::normal(), rgb_color_t::normal());
while (1) {
if (tcsetattr(0, TCSANOW, &terminal_mode_for_executing_programs)) {
if (errno != EINTR) {
debug(1, _(L"Could not set terminal mode for new job"));
wperror(L"tcsetattr");
break;
}
} else
break;
}
}
/// Update the cursor position.
static void update_buff_pos(editable_line_t *el, size_t buff_pos) {
el->position = buff_pos;
if (el == &data->command_line && data->sel_active) {
if (data->sel_begin_pos <= buff_pos) {
data->sel_start_pos = data->sel_begin_pos;
data->sel_stop_pos = buff_pos;
} else {
data->sel_start_pos = buff_pos;
data->sel_stop_pos = data->sel_begin_pos;
}
}
}
/// Grab control of terminal.
static void term_steal() {
while (1) {
if (tcsetattr(0, TCSANOW, &shell_modes)) {
if (errno != EINTR) {
debug(1, _(L"Could not set terminal mode for shell"));
wperror(L"tcsetattr");
break;
}
} else
break;
}
common_handle_winch(0);
}
int reader_exit_forced() { return exit_forced; }
/// Given a command line and an autosuggestion, return the string that gets shown to the user.
wcstring combine_command_and_autosuggestion(const wcstring &cmdline,
const wcstring &autosuggestion) {
// We want to compute the full line, containing the command line and the autosuggestion They may
// disagree on whether characters are uppercase or lowercase Here we do something funny: if the
// last token of the command line contains any uppercase characters, we use its case. Otherwise
// we use the case of the autosuggestion. This is an idea from issue #335.
wcstring full_line;
if (autosuggestion.size() <= cmdline.size() || cmdline.empty()) {
// No or useless autosuggestion, or no command line.
full_line = cmdline;
} else if (string_prefixes_string(cmdline, autosuggestion)) {
// No case disagreements, or no extra characters in the autosuggestion.
full_line = autosuggestion;
} else {
// We have an autosuggestion which is not a prefix of the command line, i.e. a case
// disagreement. Decide whose case we want to use.
const wchar_t *begin = NULL, *cmd = cmdline.c_str();
parse_util_token_extent(cmd, cmdline.size() - 1, &begin, NULL, NULL, NULL);
bool last_token_contains_uppercase = false;
if (begin) {
const wchar_t *end = begin + wcslen(begin);
last_token_contains_uppercase = (std::find_if(begin, end, iswupper) != end);
}
if (!last_token_contains_uppercase) {
// Use the autosuggestion's case.
full_line = autosuggestion;
} else {
// Use the command line case for its characters, then append the remaining characters in
// the autosuggestion. Note that we know that autosuggestion.size() > cmdline.size() due
// to the first test above.
full_line = cmdline;
full_line.append(autosuggestion, cmdline.size(),
autosuggestion.size() - cmdline.size());
}
}
return full_line;
}
/// Repaint the entire commandline. This means reset and clear the commandline, write the prompt,
/// perform syntax highlighting, write the commandline and move the cursor.
static void reader_repaint() {
editable_line_t *cmd_line = &data->command_line;
// Update the indentation.
data->indents = parse_util_compute_indents(cmd_line->text);
// Combine the command and autosuggestion into one string.
wcstring full_line = combine_command_and_autosuggestion(cmd_line->text, data->autosuggestion);
size_t len = full_line.size();
if (len < 1) len = 1;
std::vector<highlight_spec_t> colors = data->colors;
colors.resize(len, highlight_spec_autosuggestion);
if (data->sel_active) {
highlight_spec_t selection_color = highlight_make_background(highlight_spec_selection);
for (size_t i = data->sel_start_pos; i <= std::min(len - 1, data->sel_stop_pos); i++) {
colors[i] = selection_color;
}
}
std::vector<int> indents = data->indents;
indents.resize(len);
// Re-render our completions page if necessary. We set the term size to 1 less than the true
// term height. This means we will always show the (bottom) line of the prompt.
data->pager.set_term_size(maxi(1, common_get_width()), maxi(1, common_get_height() - 1));
data->pager.update_rendering(&data->current_page_rendering);
bool focused_on_pager = data->active_edit_line() == &data->pager.search_field_line;
size_t cursor_position = focused_on_pager ? data->pager.cursor_position() : cmd_line->position;
s_write(&data->screen, data->left_prompt_buff, data->right_prompt_buff, full_line,
cmd_line->size(), &colors[0], &indents[0], cursor_position,
data->current_page_rendering, focused_on_pager);
data->repaint_needed = false;
}
/// Internal helper function for handling killing parts of text.
static void reader_kill(editable_line_t *el, size_t begin_idx, size_t length, int mode, int newv) {
const wchar_t *begin = el->text.c_str() + begin_idx;
if (newv) {
data->kill_item = wcstring(begin, length);
kill_add(data->kill_item);
} else {
wcstring old = data->kill_item;
if (mode == KILL_APPEND) {
data->kill_item.append(begin, length);
} else {
data->kill_item = wcstring(begin, length);
data->kill_item.append(old);
}
kill_replace(old, data->kill_item);
}
if (el->position > begin_idx) {
// Move the buff position back by the number of characters we deleted, but don't go past
// buff_pos.
size_t backtrack = mini(el->position - begin_idx, length);
update_buff_pos(el, el->position - backtrack);
}
el->text.erase(begin_idx, length);
data->command_line_changed(el);
reader_super_highlight_me_plenty();
reader_repaint();
}
// This is called from a signal handler!
void reader_handle_sigint() {
if (!is_interactive_read) {
parser_t::skip_all_blocks();
}
interrupted = 1;
}
const wchar_t *reader_current_filename() {
ASSERT_IS_MAIN_THREAD();
return current_filename.empty() ? NULL : current_filename.top();
}
void reader_push_current_filename(const wchar_t *fn) {
ASSERT_IS_MAIN_THREAD();
current_filename.push(intern(fn));
}
void reader_pop_current_filename() {
ASSERT_IS_MAIN_THREAD();
current_filename.pop();
}
/// Make sure buffers are large enough to hold the current string length.
void reader_data_t::command_line_changed(const editable_line_t *el) {
ASSERT_IS_MAIN_THREAD();
if (el == &this->command_line) {
size_t len = this->command_line.size();
// When we grow colors, propagate the last color (if any), under the assumption that usually
// it will be correct. If it is, it avoids a repaint.
highlight_spec_t last_color = colors.empty() ? highlight_spec_t() : colors.back();
colors.resize(len, last_color);
indents.resize(len);
// Update the gen count.
s_generation_count++;
} else if (el == &this->pager.search_field_line) {
this->pager.refilter_completions();
this->pager_selection_changed();
}
}
void reader_data_t::pager_selection_changed() {
ASSERT_IS_MAIN_THREAD();
const completion_t *completion = this->pager.selected_completion(this->current_page_rendering);
// Update the cursor and command line.
size_t cursor_pos = this->cycle_cursor_pos;
wcstring new_cmd_line;
if (completion == NULL) {
new_cmd_line = this->cycle_command_line;
} else {
new_cmd_line =
completion_apply_to_command_line(completion->completion, completion->flags,
this->cycle_command_line, &cursor_pos, false);
}
reader_set_buffer_maintaining_pager(new_cmd_line, cursor_pos);
// Trigger repaint (see issue #765).
reader_repaint_needed();
}
/// Expand abbreviations at the given cursor position. Does NOT inspect 'data'.
bool reader_expand_abbreviation_in_command(const wcstring &cmdline, size_t cursor_pos,
wcstring *output) {
// See if we are at "command position". Get the surrounding command substitution, and get the
// extent of the first token.
const wchar_t *const buff = cmdline.c_str();
const wchar_t *cmdsub_begin = NULL, *cmdsub_end = NULL;
parse_util_cmdsubst_extent(buff, cursor_pos, &cmdsub_begin, &cmdsub_end);
assert(cmdsub_begin != NULL && cmdsub_begin >= buff);
assert(cmdsub_end != NULL && cmdsub_end >= cmdsub_begin);
// Determine the offset of this command substitution.
const size_t subcmd_offset = cmdsub_begin - buff;
const wcstring subcmd = wcstring(cmdsub_begin, cmdsub_end - cmdsub_begin);
const size_t subcmd_cursor_pos = cursor_pos - subcmd_offset;
// Parse this subcmd.
parse_node_tree_t parse_tree;
parse_tree_from_string(subcmd,
parse_flag_continue_after_error | parse_flag_accept_incomplete_tokens,
&parse_tree, NULL);
// Look for plain statements where the cursor is at the end of the command.
const parse_node_t *matching_cmd_node = NULL;
const size_t len = parse_tree.size();
for (size_t i = 0; i < len; i++) {
const parse_node_t &node = parse_tree.at(i);
// Only interested in plain statements with source.
if (node.type != symbol_plain_statement || !node.has_source()) continue;
// Skip decorated statements.
if (parse_tree.decoration_for_plain_statement(node) != parse_statement_decoration_none)
continue;
// Get the command node. Skip it if we can't or it has no source.
const parse_node_t *cmd_node = parse_tree.get_child(node, 0, parse_token_type_string);
if (cmd_node == NULL || !cmd_node->has_source()) continue;
// Now see if its source range contains our cursor, including at the end.
if (subcmd_cursor_pos >= cmd_node->source_start &&
subcmd_cursor_pos <= cmd_node->source_start + cmd_node->source_length) {
// Success!
matching_cmd_node = cmd_node;
break;
}
}
// Now if we found a command node, expand it.
bool result = false;
if (matching_cmd_node != NULL) {
assert(matching_cmd_node->type == parse_token_type_string);
const wcstring token = matching_cmd_node->get_source(subcmd);
wcstring abbreviation;
if (expand_abbreviation(token, &abbreviation)) {
// There was an abbreviation! Replace the token in the full command. Maintain the
// relative position of the cursor.
if (output != NULL) {
output->assign(cmdline);
output->replace(subcmd_offset + matching_cmd_node->source_start,
matching_cmd_node->source_length, abbreviation);
}
result = true;
}
}
return result;
}
/// Expand abbreviations at the current cursor position, minus the given cursor backtrack. This may
/// change the command line but does NOT repaint it. This is to allow the caller to coalesce
/// repaints.
bool reader_data_t::expand_abbreviation_as_necessary(size_t cursor_backtrack) {
bool result = false;
editable_line_t *el = data->active_edit_line();
if (this->expand_abbreviations && el == &data->command_line) {
// Try expanding abbreviations.
wcstring new_cmdline;
size_t cursor_pos = el->position - mini(el->position, cursor_backtrack);
if (reader_expand_abbreviation_in_command(el->text, cursor_pos, &new_cmdline)) {
// We expanded an abbreviation! The cursor moves by the difference in the command line
// lengths.
size_t new_buff_pos = el->position + new_cmdline.size() - el->text.size();
el->text.swap(new_cmdline);
update_buff_pos(el, new_buff_pos);
data->command_line_changed(el);
result = true;
}
}
return result;
}
void reader_reset_interrupted() { interrupted = 0; }
int reader_interrupted() {
int res = interrupted;
if (res) {
interrupted = 0;
}
return res;
}
int reader_reading_interrupted() {
int res = reader_interrupted();
if (res && data && data->exit_on_interrupt) {
reader_exit(1, 0);
parser_t::skip_all_blocks();
// We handled the interrupt ourselves, our caller doesn't need to handle it.
return 0;
}
return res;
}
bool reader_thread_job_is_stale() {
ASSERT_IS_BACKGROUND_THREAD();
return (void *)(uintptr_t)s_generation_count != pthread_getspecific(generation_count_key);
}
void reader_write_title(const wcstring &cmd, bool reset_cursor_position) {
const env_var_t term_str = env_get_string(L"TERM");
// This is a pretty lame heuristic for detecting terminals that do not support setting the
// title. If we recognise the terminal name as that of a virtual terminal, we assume it supports
// setting the title. If we recognise it as that of a console, we assume it does not support
// setting the title. Otherwise we check the ttyname and see if we believe it is a virtual
// terminal.
//
// One situation in which this breaks down is with screen, since screen supports setting the
// terminal title if the underlying terminal does so, but will print garbage on terminals that
// don't. Since we can't see the underlying terminal below screen there is no way to fix this.
if (term_str.missing()) return;
const wchar_t *term = term_str.c_str();
bool recognized = false;
recognized = recognized || contains(term, L"xterm", L"screen", L"nxterm", L"rxvt");
recognized = recognized || !wcsncmp(term, L"xterm-", wcslen(L"xterm-"));
recognized = recognized || !wcsncmp(term, L"screen-", wcslen(L"screen-"));
if (!recognized) {
char *n = ttyname(STDIN_FILENO);
if (contains(term, L"linux")) {
return;
}
if (contains(term, L"dumb")) return;
if (strstr(n, "tty") || strstr(n, "/vc/")) return;
}
wcstring fish_title_command = DEFAULT_TITLE;
if (function_exists(L"fish_title")) {
fish_title_command = L"fish_title";
if (!cmd.empty()) {
fish_title_command.append(L" ");
fish_title_command.append(parse_util_escape_string_with_quote(cmd, L'\0'));
}
}
wcstring_list_t lst;
proc_push_interactive(0);
if (exec_subshell(fish_title_command, lst, false /* do not apply exit status */) != -1) {
if (!lst.empty()) {
writestr(L"\x1b]0;");
for (size_t i = 0; i < lst.size(); i++) {
writestr(lst.at(i).c_str());
}
writestr(L"\7");
}
}
proc_pop_interactive();
set_color(rgb_color_t::reset(), rgb_color_t::reset());
if (reset_cursor_position && !lst.empty()) {
// Put the cursor back at the beginning of the line (issue #2453).
writestr(L"\r");
}
}
/// Reexecute the prompt command. The output is inserted into data->prompt_buff.
static void exec_prompt() {
// Clear existing prompts.
data->left_prompt_buff.clear();
data->right_prompt_buff.clear();
// Do not allow the exit status of the prompts to leak through.
const bool apply_exit_status = false;
// If we have any prompts, they must be run non-interactively.
if (data->left_prompt.size() || data->right_prompt.size()) {
proc_push_interactive(0);
// Prepend any mode indicator to the left prompt (issue #1988).
if (function_exists(MODE_PROMPT_FUNCTION_NAME)) {
wcstring_list_t mode_indicator_list;
exec_subshell(MODE_PROMPT_FUNCTION_NAME, mode_indicator_list, apply_exit_status);
// We do not support multiple lines in the mode indicator, so just concatenate all of
// them.
for (size_t i = 0; i < mode_indicator_list.size(); i++) {
data->left_prompt_buff += mode_indicator_list.at(i);
}
}
if (!data->left_prompt.empty()) {
wcstring_list_t prompt_list;
// Ignore return status.
exec_subshell(data->left_prompt, prompt_list, apply_exit_status);
for (size_t i = 0; i < prompt_list.size(); i++) {
if (i > 0) data->left_prompt_buff += L'\n';
data->left_prompt_buff += prompt_list.at(i);
}
}
if (!data->right_prompt.empty()) {
wcstring_list_t prompt_list;
// Status is ignored.
exec_subshell(data->right_prompt, prompt_list, apply_exit_status);
for (size_t i = 0; i < prompt_list.size(); i++) {
// Right prompt does not support multiple lines, so just concatenate all of them.
data->right_prompt_buff += prompt_list.at(i);
}
}
proc_pop_interactive();
}
// Write the screen title. Do not reset the cursor position: exec_prompt is called when there
// may still be output on the line from the previous command (#2499) and we need our PROMPT_SP
// hack to work.
reader_write_title(L"", false);
}
void reader_init() {
VOMIT_ON_FAILURE(pthread_key_create(&generation_count_key, NULL));
// Save the initial terminal mode.
tcgetattr(STDIN_FILENO, &terminal_mode_on_startup);
// Set the mode used for program execution, initialized to the current mode.
memcpy(&terminal_mode_for_executing_programs, &terminal_mode_on_startup,
sizeof terminal_mode_for_executing_programs);
terminal_mode_for_executing_programs.c_iflag &= ~IXON; // disable flow control
terminal_mode_for_executing_programs.c_iflag &= ~IXOFF; // disable flow control
// Set the mode used for the terminal, initialized to the current mode.
memcpy(&shell_modes, &terminal_mode_on_startup, sizeof shell_modes);
shell_modes.c_iflag &= ~ICRNL; // disable mapping CR (\cM) to NL (\cJ)
shell_modes.c_iflag &= ~INLCR; // disable mapping NL (\cJ) to CR (\cM)
shell_modes.c_iflag &= ~IXON; // disable flow control
shell_modes.c_iflag &= ~IXOFF; // disable flow control
shell_modes.c_lflag &= ~ICANON; // turn off canonical mode
shell_modes.c_lflag &= ~ECHO; // turn off echo mode
shell_modes.c_lflag &= ~IEXTEN; // turn off handling of discard and lnext characters
shell_modes.c_cc[VMIN] = 1;
shell_modes.c_cc[VTIME] = 0;
// We don't use term_steal because this can fail if fd 0 isn't associated with a tty and this
// function is run regardless of whether stdin is tied to a tty. This is harmless in that case.
// We do it unconditionally because disabling ICRNL mode (see above) needs to be done at the
// earliest possible moment. Doing it here means it will be done within approximately 1 ms of
// the start of the shell rather than 250 ms (or more) when reader_interactive_init is
// eventually called.
//
// TODO: Remove this condition when issue #2315 and #1041 are addressed.
if (is_interactive_session) {
tcsetattr(STDIN_FILENO, TCSANOW, &shell_modes);
}
}
void reader_destroy() { pthread_key_delete(generation_count_key); }
void restore_term_mode() {
// Restore the term mode if we own the terminal. It's important we do this before
// restore_foreground_process_group, otherwise we won't think we own the terminal.
if (getpid() == tcgetpgrp(STDIN_FILENO)) {
tcsetattr(STDIN_FILENO, TCSANOW, &terminal_mode_on_startup);
}
}
void reader_exit(int do_exit, int forced) {
if (data) data->end_loop = do_exit;
end_loop = do_exit;
if (forced) exit_forced = 1;
}
void reader_repaint_needed() {
if (data) {
data->repaint_needed = true;
}
}
void reader_repaint_if_needed() {
if (data == NULL) return;
bool needs_reset = data->screen_reset_needed;
bool needs_repaint = needs_reset || data->repaint_needed;
if (needs_reset) {
exec_prompt();
s_reset(&data->screen, screen_reset_current_line_and_prompt);
data->screen_reset_needed = false;
}
if (needs_repaint) {
reader_repaint(); // reader_repaint clears repaint_needed
}
}
static void reader_repaint_if_needed_one_arg(void *unused) {
UNUSED(unused);
reader_repaint_if_needed();
}
void reader_react_to_color_change() {
if (!data) return;
if (!data->repaint_needed || !data->screen_reset_needed) {
data->repaint_needed = true;
data->screen_reset_needed = true;
input_common_add_callback(reader_repaint_if_needed_one_arg, NULL);
}
}
/// Indicates if the given command char ends paging.
static bool command_ends_paging(wchar_t c, bool focused_on_search_field) {
switch (c) {
case R_HISTORY_SEARCH_BACKWARD:
case R_HISTORY_SEARCH_FORWARD:
case R_HISTORY_TOKEN_SEARCH_BACKWARD:
case R_HISTORY_TOKEN_SEARCH_FORWARD:
case R_ACCEPT_AUTOSUGGESTION:
case R_CANCEL: {
// These commands always end paging.
return true;
}
case R_COMPLETE:
case R_COMPLETE_AND_SEARCH:
case R_BACKWARD_CHAR:
case R_FORWARD_CHAR:
case R_UP_LINE:
case R_DOWN_LINE:
case R_NULL:
case R_REPAINT:
case R_SUPPRESS_AUTOSUGGESTION:
case R_BEGINNING_OF_HISTORY:
case R_END_OF_HISTORY:
default: {
// These commands never do.
return false;
}
case R_EXECUTE: {
// R_EXECUTE does end paging, but only executes if it was not paging. So it's handled
// specially.
return false;
}
case R_BEGINNING_OF_LINE:
case R_END_OF_LINE:
case R_FORWARD_WORD:
case R_BACKWARD_WORD:
case R_FORWARD_BIGWORD:
case R_BACKWARD_BIGWORD:
case R_DELETE_CHAR:
case R_BACKWARD_DELETE_CHAR:
case R_KILL_LINE:
case R_YANK:
case R_YANK_POP:
case R_BACKWARD_KILL_LINE:
case R_KILL_WHOLE_LINE:
case R_KILL_WORD:
case R_KILL_BIGWORD:
case R_BACKWARD_KILL_WORD:
case R_BACKWARD_KILL_PATH_COMPONENT:
case R_BACKWARD_KILL_BIGWORD:
case R_SELF_INSERT:
case R_TRANSPOSE_CHARS:
case R_TRANSPOSE_WORDS:
case R_UPCASE_WORD:
case R_DOWNCASE_WORD:
case R_CAPITALIZE_WORD:
case R_VI_ARG_DIGIT:
case R_VI_DELETE_TO:
case R_BEGINNING_OF_BUFFER:
case R_END_OF_BUFFER: {
// These commands operate on the search field if that's where the focus is.
return !focused_on_search_field;
}
}
}
/// Remove the previous character in the character buffer and on the screen using syntax
/// highlighting, etc.
static void remove_backward() {
editable_line_t *el = data->active_edit_line();
if (el->position <= 0) return;
// Fake composed character sequences by continuing to delete until we delete a character of
// width at least 1.
int width;
do {
update_buff_pos(el, el->position - 1);
width = fish_wcwidth(el->text.at(el->position));
el->text.erase(el->position, 1);
} while (width == 0 && el->position > 0);
data->command_line_changed(el);
data->suppress_autosuggestion = true;
reader_super_highlight_me_plenty();
reader_repaint_needed();
}
/// Insert the characters of the string into the command line buffer and print them to the screen
/// using syntax highlighting, etc. Optionally also expand abbreviations, after space characters.
/// Returns true if the string changed.
static bool insert_string(editable_line_t *el, const wcstring &str,
bool allow_expand_abbreviations = false) {
size_t len = str.size();
if (len == 0) return false;
// Start inserting. If we are expanding abbreviations, we have to do this after every space (see
// #1434), so look for spaces. We try to do this efficiently (rather than the simpler character
// at a time) to avoid expensive work in command_line_changed().
size_t cursor = 0;
while (cursor < len) {
// Determine the position of the next expansion-triggering char (possibly none), and the end
// of the range we wish to insert.
const wchar_t *expansion_triggering_chars = L" ;|&^><";
size_t char_triggering_expansion_pos =
allow_expand_abbreviations ? str.find_first_of(expansion_triggering_chars, cursor)
: wcstring::npos;
bool has_expansion_triggering_char = (char_triggering_expansion_pos != wcstring::npos);
size_t range_end =
(has_expansion_triggering_char ? char_triggering_expansion_pos + 1 : len);
// Insert from the cursor up to but not including the range end.
assert(range_end > cursor);
el->insert_string(str, cursor, range_end - cursor);
update_buff_pos(el, el->position);
data->command_line_changed(el);
// If we got an expansion trigger, then the last character we inserted was it (i.e. was a
// space). Expand abbreviations.
if (has_expansion_triggering_char && allow_expand_abbreviations) {
assert(range_end > 0);
assert(wcschr(expansion_triggering_chars, str.at(range_end - 1)));
data->expand_abbreviation_as_necessary(1);
}
cursor = range_end;
}
if (el == &data->command_line) {
data->suppress_autosuggestion = false;
// Syntax highlight. Note we must have that buff_pos > 0 because we just added something
// nonzero to its length.
assert(el->position > 0);
reader_super_highlight_me_plenty(-1);
}