forked from fish-shell/fish-shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.cpp
4025 lines (3361 loc) · 121 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
/** \file reader.c
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"
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#include <time.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/poll.h>
#include <unistd.h>
#include <wctype.h>
#include <stack>
#include <pthread.h>
#if HAVE_NCURSES_H
#include <ncurses.h>
#else
#include <curses.h>
#endif
#if HAVE_TERM_H
#include <term.h>
#elif HAVE_NCURSES_TERM_H
#include <ncurses/term.h>
#endif
#ifdef HAVE_SIGINFO_H
#include <siginfo.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <signal.h>
#include <fcntl.h>
#include <dirent.h>
#include <wchar.h>
#include <assert.h>
#include "fallback.h"
#include "util.h"
#include "wutil.h"
#include "highlight.h"
#include "reader.h"
#include "proc.h"
#include "parser.h"
#include "complete.h"
#include "history.h"
#include "common.h"
#include "sanity.h"
#include "env.h"
#include "exec.h"
#include "expand.h"
#include "tokenizer.h"
#include "kill.h"
#include "input_common.h"
#include "input.h"
#include "function.h"
#include "output.h"
#include "signal.h"
#include "screen.h"
#include "iothread.h"
#include "intern.h"
#include "path.h"
#include "parse_util.h"
#include "parser_keywords.h"
/**
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 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;
/* A color is an int */
typedef int color_t;
static void set_command_line_and_position(const wcstring &new_str, size_t pos);
/**
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 */
wcstring command_line;
/** String containing the autosuggestion */
wcstring autosuggestion;
/** 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
*/
int 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;
/** Length of the command */
size_t command_length() const
{
return command_line.size();
}
/** Do what we need to do whenever our command line changes */
void command_line_changed(void);
/** Expand abbreviations at the current cursor position, minus backtrack_amt. */
bool expand_abbreviation_as_necessary(size_t cursor_backtrack);
/** The current position of the cursor in buff. */
size_t buff_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;
/**
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<color_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
*/
int (*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;
/** Constructor */
reader_data_t() :
allow_autosuggestion(0),
suppress_autosuggestion(0),
expand_abbreviations(0),
history(0),
token_history_pos(0),
search_pos(0),
buff_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)
{
}
};
/**
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;
/**
Store the pid of the parent process, so the exit function knows whether it should reset the terminal or not.
*/
static pid_t original_pid;
/**
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(size_t pos);
/**
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;
}
}
/**
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 https://github.com/fish-shell/fish-shell/issues/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()
{
// Update the indentation
parser_t::principal_parser().test(data->command_line.c_str(), &data->indents[0]);
// Combine the command and autosuggestion into one string
wcstring full_line = combine_command_and_autosuggestion(data->command_line, data->autosuggestion);
size_t len = full_line.size();
if (len < 1)
len = 1;
std::vector<color_t> colors = data->colors;
colors.resize(len, HIGHLIGHT_AUTOSUGGESTION);
std::vector<int> indents = data->indents;
indents.resize(len);
s_write(&data->screen,
data->left_prompt_buff,
data->right_prompt_buff,
full_line,
data->command_length(),
&colors[0],
&indents[0],
data->buff_pos);
data->repaint_needed = false;
}
static void reader_repaint_without_autosuggestion()
{
// Swap in an empty autosuggestion, repaint, then swap it out
wcstring saved_autosuggestion;
data->autosuggestion.swap(saved_autosuggestion);
reader_repaint();
data->autosuggestion.swap(saved_autosuggestion);
}
/** Internal helper function for handling killing parts of text. */
static void reader_kill(size_t begin_idx, size_t length, int mode, int newv)
{
const wchar_t *begin = data->command_line.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 (data->buff_pos > 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(data->buff_pos - begin_idx, length);
data->buff_pos -= backtrack;
}
data->command_line.erase(begin_idx, length);
data->command_line_changed();
reader_super_highlight_me_plenty(data->buff_pos);
reader_repaint();
}
/* This is called from a signal handler! */
void reader_handle_int(int sig)
{
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()
{
ASSERT_IS_MAIN_THREAD();
size_t len = command_length();
/* 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. */
color_t last_color = colors.empty() ? color_t() : colors.back();
colors.resize(len, last_color);
indents.resize(len);
/* Update the gen count */
s_generation_count++;
}
/* 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 wchar_t *subcmd_cstr = subcmd.c_str();
/* Get the token containing the cursor */
const wchar_t *subcmd_tok_begin = NULL, *subcmd_tok_end = NULL;
assert(cursor_pos >= subcmd_offset);
size_t subcmd_cursor_pos = cursor_pos - subcmd_offset;
parse_util_token_extent(subcmd_cstr, subcmd_cursor_pos, &subcmd_tok_begin, &subcmd_tok_end, NULL, NULL);
/* Compute the offset of the token before the cursor within the subcmd */
assert(subcmd_tok_begin >= subcmd_cstr);
assert(subcmd_tok_end >= subcmd_tok_begin);
const size_t subcmd_tok_begin_offset = subcmd_tok_begin - subcmd_cstr;
const size_t subcmd_tok_length = subcmd_tok_end - subcmd_tok_begin;
/* Now parse the subcmd, looking for commands */
bool had_cmd = false, previous_token_is_cmd = false;
tokenizer_t tok(subcmd_cstr, TOK_ACCEPT_UNFINISHED | TOK_SQUASH_ERRORS);
for (; tok_has_next(&tok); tok_next(&tok))
{
size_t tok_pos = static_cast<size_t>(tok_get_pos(&tok));
if (tok_pos > subcmd_tok_begin_offset)
{
/* We've passed the token we're interested in */
break;
}
int last_type = tok_last_type(&tok);
switch (last_type)
{
case TOK_STRING:
{
if (had_cmd)
{
/* Parameter to the command. */
}
else
{
const wcstring potential_cmd = tok_last(&tok);
if (parser_keywords_is_subcommand(potential_cmd))
{
if (potential_cmd == L"command" || potential_cmd == L"builtin")
{
/* 'command' and 'builtin' defeat abbreviation expansion. Skip this command. */
had_cmd = true;
}
else
{
/* Other subcommand. Pretend it doesn't exist so that we can expand the following command */
had_cmd = false;
}
}
else
{
/* It's a normal command */
had_cmd = true;
if (tok_pos == subcmd_tok_begin_offset)
{
/* This is the token we care about! */
previous_token_is_cmd = true;
}
}
}
break;
}
case TOK_REDIRECT_NOCLOB:
case TOK_REDIRECT_OUT:
case TOK_REDIRECT_IN:
case TOK_REDIRECT_APPEND:
case TOK_REDIRECT_FD:
{
if (!had_cmd)
{
break;
}
tok_next(&tok);
break;
}
case TOK_PIPE:
case TOK_BACKGROUND:
case TOK_END:
{
had_cmd = false;
break;
}
case TOK_COMMENT:
case TOK_ERROR:
default:
{
break;
}
}
}
bool result = false;
if (previous_token_is_cmd)
{
/* The token is a command. Try expanding it as an abbreviation. */
const wcstring token = wcstring(subcmd, subcmd_tok_begin_offset, subcmd_tok_length);
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)
{
size_t cmd_tok_begin_offset = subcmd_tok_begin_offset + subcmd_offset;
output->assign(cmdline);
output->replace(cmd_tok_begin_offset, subcmd_tok_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;
if (this->expand_abbreviations)
{
/* Try expanding abbreviations */
wcstring new_cmdline;
size_t cursor_pos = this->buff_pos - mini(this->buff_pos, cursor_backtrack);
if (reader_expand_abbreviation_in_command(this->command_line, cursor_pos, &new_cmdline))
{
/* We expanded an abbreviation! The cursor moves by the difference in the command line lengths. */
size_t new_buff_pos = this->buff_pos + new_cmdline.size() - this->command_line.size();
this->command_line.swap(new_cmdline);
data->buff_pos = new_buff_pos;
data->command_line_changed();
result = true;
}
}
return result;
}
/** Sorts and remove any duplicate completions in the list. */
static void sort_and_make_unique(std::vector<completion_t> &l)
{
sort(l.begin(), l.end(), completion_t::is_alphabetically_less_than);
l.erase(std::unique(l.begin(), l.end(), completion_t::is_alphabetically_equal_to), l.end());
}
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 wchar_t *title;
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 (strstr(n, "tty") || strstr(n, "/vc/"))
return;
}
title = function_exists(L"fish_title")?L"fish_title":DEFAULT_TITLE;
if (wcslen(title) ==0)
return;
wcstring_list_t lst;
proc_push_interactive(0);
if (exec_subshell(title, 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());
}
/**
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);
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 */
reader_write_title();
}
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_lflag &= ~ICANON; /* turn off canonical mode */
shell_modes.c_lflag &= ~ECHO; /* turn off echo mode */
shell_modes.c_iflag &= ~IXON; /* disable flow control */
shell_modes.c_iflag &= ~IXOFF; /* disable flow control */
shell_modes.c_cc[VMIN]=1;
shell_modes.c_cc[VTIME]=0;
#if defined(_POSIX_VDISABLE)
// PCA disable VDSUSP (typically control-Y), which is a funny job control
// function available only on OS X and BSD systems
// This lets us use control-Y for yank instead
#ifdef VDSUSP
shell_modes.c_cc[VDSUSP] = _POSIX_VDISABLE;
#endif
#endif
}
void reader_destroy()
{
tcsetattr(0, TCSANOW, &terminal_mode_on_startup);
pthread_key_delete(generation_count_key);
}