-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcomplete.cpp
1656 lines (1425 loc) · 65.3 KB
/
complete.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 related to tab-completion.
///
/// These functions are used for storing and retrieving tab-completion data, as well as for
/// performing tab-completion.
///
#include "config.h" // IWYU pragma: keep
#include <pthread.h>
#include <pwd.h>
#include <stddef.h>
#include <wchar.h>
#include <wctype.h>
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <set>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include "autoload.h"
#include "builtin.h"
#include "common.h"
#include "complete.h"
#include "env.h"
#include "exec.h"
#include "expand.h"
#include "fallback.h" // IWYU pragma: keep
#include "function.h"
#include "iothread.h"
#include "parse_constants.h"
#include "parse_util.h"
#include "parser.h"
#include "path.h"
#include "proc.h"
#include "tnode.h"
#include "util.h"
#include "wildcard.h"
#include "wutil.h" // IWYU pragma: keep
// Completion description strings, mostly for different types of files, such as sockets, block
// devices, etc.
//
// There are a few more completion description strings defined in expand.c. Maybe all completion
// description strings should be defined in the same file?
/// Description for ~USER completion.
#define COMPLETE_USER_DESC _(L"Home for %ls")
/// Description for short variables. The value is concatenated to this description.
#define COMPLETE_VAR_DESC_VAL _(L"Variable: %ls")
/// The special cased translation macro for completions. The empty string needs to be special cased,
/// since it can occur, and should not be translated. (Gettext returns the version information as
/// the response).
#ifdef HAVE_GETTEXT
static const wchar_t *C_(const wcstring &s) {
return s.empty() ? L"" : wgettext(s.c_str()).c_str();
}
#else
static const wcstring &C_(const wcstring &s) { return s; }
#endif
static void complete_load(const wcstring &name, bool reload);
/// Testing apparatus.
const wcstring_list_t *s_override_variable_names = NULL;
void complete_set_variable_names(const wcstring_list_t *names) {
s_override_variable_names = names;
}
static inline wcstring_list_t complete_get_variable_names() {
if (s_override_variable_names != NULL) {
return *s_override_variable_names;
}
return env_get_names(0);
}
/// Struct describing a completion option entry.
///
/// If option is empty, the comp field must not be empty and contains a list of arguments to the
/// command.
///
/// The type field determines how the option is to be interpreted: either empty (args_only) or
/// short, single-long ("old") or double-long ("GNU"). An invariant is that the option is empty if
/// and only if the type is args_only.
///
/// If option is non-empty, it specifies a switch for the command. If \c comp is also not empty, it
/// contains a list of non-switch arguments that may only follow directly after the specified
/// switch.
typedef struct complete_entry_opt {
// Text of the option (like 'foo').
wcstring option;
// Type of the option: args-oly, short, single_long, or double_long.
complete_option_type_t type;
// Arguments to the option.
wcstring comp;
// Description of the completion.
wcstring desc;
// Condition under which to use the option.
wcstring condition;
// Must be one of the values SHARED, NO_FILES, NO_COMMON, EXCLUSIVE, and determines how
// completions should be performed on the argument after the switch.
int result_mode;
// Completion flags.
complete_flags_t flags;
const wcstring localized_desc() const { return C_(desc); }
size_t expected_dash_count() const {
switch (this->type) {
case option_type_args_only:
return 0;
case option_type_short:
case option_type_single_long:
return 1;
case option_type_double_long:
return 2;
}
DIE("unreachable");
}
} complete_entry_opt_t;
/// Last value used in the order field of completion_entry_t.
static unsigned int kCompleteOrder = 0;
/// Struct describing a command completion.
typedef std::list<complete_entry_opt_t> option_list_t;
class completion_entry_t {
public:
/// List of all options.
option_list_t options;
public:
/// Command string.
const wcstring cmd;
/// True if command is a path.
const bool cmd_is_path;
/// Order for when this completion was created. This aids in outputting completions sorted by
/// time.
const unsigned int order;
/// Getters for option list.
const option_list_t &get_options() const;
/// Adds or removes an option.
void add_option(const complete_entry_opt_t &opt);
bool remove_option(const wcstring &option, complete_option_type_t type);
completion_entry_t(wcstring c, bool type)
: cmd(std::move(c)), cmd_is_path(type), order(++kCompleteOrder) {}
};
/// Set of all completion entries.
namespace std {
template <>
struct hash<completion_entry_t> {
size_t operator()(const completion_entry_t &c) const {
std::hash<wcstring> hasher;
return hasher((wcstring)c.cmd);
}
};
template <>
struct equal_to<completion_entry_t> {
bool operator()(const completion_entry_t &c1, const completion_entry_t &c2) const {
return c1.cmd == c2.cmd;
}
};
}
typedef std::unordered_set<completion_entry_t> completion_entry_set_t;
static completion_entry_set_t completion_set;
/// Comparison function to sort completions by their order field.
static bool compare_completions_by_order(const completion_entry_t *p1,
const completion_entry_t *p2) {
return p1->order < p2->order;
}
/// The lock that guards the list of completion entries.
static fish_mutex_t completion_lock;
void completion_entry_t::add_option(const complete_entry_opt_t &opt) {
ASSERT_IS_LOCKED(completion_lock);
options.push_front(opt);
}
const option_list_t &completion_entry_t::get_options() const {
ASSERT_IS_LOCKED(completion_lock);
return options;
}
/// Clear the COMPLETE_AUTO_SPACE flag, and set COMPLETE_NO_SPACE appropriately depending on the
/// suffix of the string.
static complete_flags_t resolve_auto_space(const wcstring &comp, complete_flags_t flags) {
complete_flags_t new_flags = flags;
if (flags & COMPLETE_AUTO_SPACE) {
new_flags &= ~COMPLETE_AUTO_SPACE;
size_t len = comp.size();
if (len > 0 && (wcschr(L"/=@:", comp.at(len - 1)) != 0)) new_flags |= COMPLETE_NO_SPACE;
}
return new_flags;
}
/// completion_t functions. Note that the constructor resolves flags!
completion_t::completion_t(wcstring comp, wcstring desc, string_fuzzy_match_t mat,
complete_flags_t flags_val)
: completion(std::move(comp)),
description(std::move(desc)),
match(std::move(mat)),
flags(resolve_auto_space(completion, flags_val)) {}
completion_t::completion_t(const completion_t &him) = default;
completion_t::completion_t(completion_t &&him) = default;
completion_t &completion_t::operator=(const completion_t &him) = default;
completion_t &completion_t::operator=(completion_t &&him) = default;
completion_t::~completion_t() = default;
bool completion_t::is_naturally_less_than(const completion_t &a, const completion_t &b) {
// For this to work, stable_sort must be used because results aren't interchangeable.
if (a.flags & b.flags & COMPLETE_DONT_SORT) {
// Both completions are from a source with the --keep-order flag.
return false;
}
return wcsfilecmp(a.completion.c_str(), b.completion.c_str()) < 0;
}
void completion_t::prepend_token_prefix(const wcstring &prefix) {
if (this->flags & COMPLETE_REPLACES_TOKEN) {
this->completion.insert(0, prefix);
}
}
static bool compare_completions_by_match_type(const completion_t &a, const completion_t &b) {
return a.match.type < b.match.type;
}
template <class Iterator, class HashFunction>
static Iterator unique_unsorted(Iterator begin, Iterator end, HashFunction hash) {
typedef typename std::iterator_traits<Iterator>::value_type T;
std::unordered_set<size_t> temp;
return std::remove_if(begin, end, [&](const T &val) { return !temp.insert(hash(val)).second; });
}
void completions_sort_and_prioritize(std::vector<completion_t> *comps) {
// Find the best match type.
fuzzy_match_type_t best_type = fuzzy_match_none;
for (size_t i = 0; i < comps->size(); i++) {
best_type = std::min(best_type, comps->at(i).match.type);
}
// If the best type is an exact match, reduce it to prefix match. Otherwise a tab completion
// will only show one match if it matches a file exactly. (see issue #959).
if (best_type == fuzzy_match_exact) {
best_type = fuzzy_match_prefix;
}
// Throw out completions whose match types are less suitable than the best.
comps->erase(std::remove_if(comps->begin(), comps->end(), [&] (const completion_t &comp) {
return comp.match.type > best_type;
}), comps->end());
// Sort, provided COMPLETION_DONT_SORT isn't set
stable_sort(comps->begin(), comps->end(), completion_t::is_naturally_less_than);
// Deduplicate both sorted and unsorted results
comps->erase(
unique_unsorted(comps->begin(), comps->end(),
[](const completion_t &c) { return std::hash<wcstring>{}(c.completion); }),
comps->end());
// Sort the remainder by match type. They're already sorted alphabetically.
stable_sort(comps->begin(), comps->end(), compare_completions_by_match_type);
}
/// Class representing an attempt to compute completions.
class completer_t {
const completion_request_flags_t flags;
const wcstring initial_cmd;
std::vector<completion_t> completions;
/// Table of completions conditions that have already been tested and the corresponding test
/// results.
typedef std::unordered_map<wcstring, bool> condition_cache_t;
condition_cache_t condition_cache;
enum complete_type_t { COMPLETE_DEFAULT, COMPLETE_AUTOSUGGEST };
complete_type_t type() const {
return flags & COMPLETION_REQUEST_AUTOSUGGESTION ? COMPLETE_AUTOSUGGEST : COMPLETE_DEFAULT;
}
bool wants_descriptions() const {
return static_cast<bool>(flags & COMPLETION_REQUEST_DESCRIPTIONS);
}
bool fuzzy() const { return static_cast<bool>(flags & COMPLETION_REQUEST_FUZZY_MATCH); }
fuzzy_match_type_t max_fuzzy_match_type() const {
// If we are doing fuzzy matching, request all types; if not request only prefix matching.
if (flags & COMPLETION_REQUEST_FUZZY_MATCH) return fuzzy_match_none;
return fuzzy_match_prefix_case_insensitive;
}
public:
completer_t(wcstring c, completion_request_flags_t f) : flags(f), initial_cmd(std::move(c)) {}
bool empty() const { return completions.empty(); }
const std::vector<completion_t> &get_completions() { return completions; }
bool try_complete_variable(const wcstring &str);
bool try_complete_user(const wcstring &str);
bool complete_param(const wcstring &cmd_orig, const wcstring &popt, const wcstring &str,
bool use_switches);
void complete_param_expand(const wcstring &str, bool do_file,
bool handle_as_special_cd = false);
void complete_cmd(const wcstring &str, bool use_function, bool use_builtin, bool use_command,
bool use_implicit_cd);
void complete_from_args(const wcstring &str, const wcstring &args, const wcstring &desc,
complete_flags_t flags);
void complete_cmd_desc(const wcstring &str);
bool complete_variable(const wcstring &str, size_t start_offset);
bool condition_test(const wcstring &condition);
void complete_strings(const wcstring &wc_escaped, const wchar_t *desc,
wcstring (*desc_func)(const wcstring &),
std::vector<completion_t> &possible_comp, complete_flags_t flags);
expand_flags_t expand_flags() const {
// Never do command substitution in autosuggestions. Sadly, we also can't yet do job
// expansion because it's not thread safe.
expand_flags_t result = 0;
if (this->type() == COMPLETE_AUTOSUGGEST) result |= EXPAND_SKIP_CMDSUBST;
// Allow fuzzy matching.
if (this->fuzzy()) result |= EXPAND_FUZZY_MATCH;
return result;
}
};
// Callback when an autoloaded completion is removed.
static void autoloaded_completion_removed(const wcstring &cmd) {
complete_remove_all(cmd, false /* not a path */);
}
// Autoloader for completions
static autoload_t completion_autoloader(L"fish_complete_path", autoloaded_completion_removed);
/// Create a new completion entry.
void append_completion(std::vector<completion_t> *completions, wcstring comp, wcstring desc,
complete_flags_t flags, string_fuzzy_match_t match) {
completions->emplace_back(std::move(comp), std::move(desc), match,
resolve_auto_space(comp, flags));
}
/// Test if the specified script returns zero. The result is cached, so that if multiple completions
/// use the same condition, it needs only be evaluated once. condition_cache_clear must be called
/// after a completion run to make sure that there are no stale completions.
bool completer_t::condition_test(const wcstring &condition) {
if (condition.empty()) {
// fwprintf( stderr, L"No condition specified\n" );
return 1;
}
if (this->type() == COMPLETE_AUTOSUGGEST) {
// Autosuggestion can't support conditions.
return 0;
}
ASSERT_IS_MAIN_THREAD();
bool test_res;
condition_cache_t::iterator cached_entry = condition_cache.find(condition);
if (cached_entry == condition_cache.end()) {
// Compute new value and reinsert it.
test_res = (0 == exec_subshell(condition, false /* don't apply exit status */));
condition_cache[condition] = test_res;
} else {
// Use the old value.
test_res = cached_entry->second;
}
return test_res;
}
/// Locate the specified entry. Create it if it doesn't exist. Must be called while locked.
static completion_entry_t &complete_get_exact_entry(const wcstring &cmd, bool cmd_is_path) {
ASSERT_IS_LOCKED(completion_lock);
auto ins = completion_set.emplace(completion_entry_t(cmd, cmd_is_path));
// NOTE SET_ELEMENTS_ARE_IMMUTABLE: Exposing mutable access here is only okay as long as callers
// do not change any field that matters to ordering - affecting order without telling std::set
// invalidates its internal state.
return const_cast<completion_entry_t &>(*ins.first);
}
void complete_add(const wchar_t *cmd, bool cmd_is_path, const wcstring &option,
complete_option_type_t option_type, int result_mode, const wchar_t *condition,
const wchar_t *comp, const wchar_t *desc, complete_flags_t flags) {
CHECK(cmd, );
// option should be empty iff the option type is arguments only.
assert(option.empty() == (option_type == option_type_args_only));
// Lock the lock that allows us to edit the completion entry list.
scoped_lock lock(completion_lock);
completion_entry_t &c = complete_get_exact_entry(cmd, cmd_is_path);
// Create our new option.
complete_entry_opt_t opt;
opt.option = option;
opt.type = option_type;
opt.result_mode = result_mode;
if (comp) opt.comp = comp;
if (condition) opt.condition = condition;
if (desc) opt.desc = desc;
opt.flags = flags;
c.add_option(opt);
}
/// Remove all completion options in the specified entry that match the specified short / long
/// option strings. Returns true if it is now empty and should be deleted, false if it's not empty.
/// Must be called while locked.
bool completion_entry_t::remove_option(const wcstring &option, complete_option_type_t type) {
ASSERT_IS_LOCKED(completion_lock);
option_list_t::iterator iter = this->options.begin();
while (iter != this->options.end()) {
if (iter->option == option && iter->type == type) {
iter = this->options.erase(iter);
} else {
// Just go to the next one.
++iter;
}
}
return this->options.empty();
}
void complete_remove(const wcstring &cmd, bool cmd_is_path, const wcstring &option,
complete_option_type_t type) {
scoped_lock lock(completion_lock);
completion_entry_t tmp_entry(cmd, cmd_is_path);
completion_entry_set_t::iterator iter = completion_set.find(tmp_entry);
if (iter != completion_set.end()) {
// const_cast: See SET_ELEMENTS_ARE_IMMUTABLE.
completion_entry_t &entry = const_cast<completion_entry_t &>(*iter);
bool delete_it = entry.remove_option(option, type);
if (delete_it) {
completion_set.erase(iter);
}
}
}
void complete_remove_all(const wcstring &cmd, bool cmd_is_path) {
scoped_lock lock(completion_lock);
completion_entry_t tmp_entry(cmd, cmd_is_path);
completion_set.erase(tmp_entry);
}
/// Find the full path and commandname from a command string 'str'.
static void parse_cmd_string(const wcstring &str, wcstring &path, wcstring &cmd) {
if (!path_get_path(str, &path)) {
/// Use the empty string as the 'path' for commands that can not be found.
path = L"";
}
// Make sure the path is not included in the command.
size_t last_slash = str.find_last_of(L'/');
if (last_slash != wcstring::npos) {
cmd = str.substr(last_slash + 1);
} else {
cmd = str;
}
}
/// Copy any strings in possible_comp which have the specified prefix to the
/// completer's completion array. The prefix may contain wildcards. The output
/// will consist of completion_t structs.
///
/// There are three ways to specify descriptions for each completion. Firstly,
/// if a description has already been added to the completion, it is _not_
/// replaced. Secondly, if the desc_func function is specified, use it to
/// determine a dynamic completion. Thirdly, if none of the above are available,
/// the desc string is used as a description.
///
/// @param wc_escaped
/// the prefix, possibly containing wildcards. The wildcard should not have
/// been unescaped, i.e. '*' should be used for any string, not the
/// ANY_STRING character.
/// @param desc
/// the default description, used for completions with no embedded
/// description. The description _may_ contain a COMPLETE_SEP character, if
/// not, one will be prefixed to it
/// @param desc_func
/// the function that generates a description for those completions witout an
/// embedded description
/// @param possible_comp
/// the list of possible completions to iterate over
/// @param flags
/// The flags
void completer_t::complete_strings(const wcstring &wc_escaped, const wchar_t *desc,
wcstring (*desc_func)(const wcstring &),
std::vector<completion_t> &possible_comp,
complete_flags_t flags) {
wcstring tmp = wc_escaped;
if (!expand_one(tmp, EXPAND_SKIP_CMDSUBST | EXPAND_SKIP_WILDCARDS | this->expand_flags(), NULL))
return;
const wcstring wc = parse_util_unescape_wildcards(tmp);
for (size_t i = 0; i < possible_comp.size(); i++) {
wcstring temp = possible_comp.at(i).completion;
const wchar_t *next_str = temp.empty() ? NULL : temp.c_str();
if (next_str) {
wildcard_complete(next_str, wc.c_str(), desc, desc_func, &this->completions,
this->expand_flags(), flags);
}
}
}
/// If command to complete is short enough, substitute the description with the whatis information
/// for the executable.
void completer_t::complete_cmd_desc(const wcstring &str) {
ASSERT_IS_MAIN_THREAD();
const wchar_t *cmd_start;
int skip;
const wchar_t *const cmd = str.c_str();
cmd_start = wcsrchr(cmd, L'/');
if (cmd_start)
cmd_start++;
else
cmd_start = cmd;
// Using apropos with a single-character search term produces far to many results - require at
// least two characters if we don't know the location of the whatis-database.
if (wcslen(cmd_start) < 2) return;
if (wildcard_has(cmd_start, 0)) {
return;
}
skip = 1;
for (size_t i = 0; i < this->completions.size(); i++) {
const completion_t &c = this->completions.at(i);
if (c.completion.empty() || (c.completion[c.completion.size() - 1] != L'/')) {
skip = 0;
break;
}
}
if (skip) {
return;
}
wcstring lookup_cmd(L"__fish_describe_command ");
lookup_cmd.append(escape_string(cmd_start, 1));
std::unordered_map<wcstring, wcstring> lookup;
// First locate a list of possible descriptions using a single call to apropos or a direct
// search if we know the location of the whatis database. This can take some time on slower
// systems with a large set of manuals, but it should be ok since apropos is only called once.
wcstring_list_t list;
if (exec_subshell(lookup_cmd, list, false /* don't apply exit status */) != -1) {
// Then discard anything that is not a possible completion and put the result into a
// hashtable with the completion as key and the description as value.
//
// Should be reasonably fast, since no memory allocations are needed.
for (size_t i = 0; i < list.size(); i++) {
const wcstring &elstr = list.at(i);
const wcstring fullkey(elstr, wcslen(cmd_start));
size_t tab_idx = fullkey.find(L'\t');
if (tab_idx == wcstring::npos) continue;
const wcstring key(fullkey, 0, tab_idx);
wcstring val(fullkey, tab_idx + 1);
// And once again I make sure the first character is uppercased because I like it that
// way, and I get to decide these things.
if (!val.empty()) val[0] = towupper(val[0]);
lookup[key] = val;
}
// Then do a lookup on every completion and if a match is found, change to the new
// description.
//
// This needs to do a reallocation for every description added, but there shouldn't be that
// many completions, so it should be ok.
for (size_t i = 0; i < this->completions.size(); i++) {
completion_t &completion = this->completions.at(i);
const wcstring &el = completion.completion;
if (el.empty()) continue;
auto new_desc_iter = lookup.find(el);
if (new_desc_iter != lookup.end()) completion.description = new_desc_iter->second;
}
}
}
/// Returns a description for the specified function, or an empty string if none.
static wcstring complete_function_desc(const wcstring &fn) {
wcstring result;
bool has_description = function_get_desc(fn, &result);
if (!has_description) {
function_get_definition(fn, &result);
}
return result;
}
/// Complete the specified command name. Search for executables in the path, executables defined
/// using an absolute path, functions, builtins and directories for implicit cd commands.
///
/// \param str_cmd the command string to find completions for
void completer_t::complete_cmd(const wcstring &str_cmd, bool use_function, bool use_builtin,
bool use_command, bool use_implicit_cd) {
if (str_cmd.empty()) return;
std::vector<completion_t> possible_comp;
if (use_command) {
expand_error_t result = expand_string(str_cmd, &this->completions,
EXPAND_SPECIAL_FOR_COMMAND | EXPAND_FOR_COMPLETIONS |
EXECUTABLES_ONLY | this->expand_flags(),
NULL);
if (result != EXPAND_ERROR && this->wants_descriptions()) {
this->complete_cmd_desc(str_cmd);
}
}
if (use_implicit_cd) {
// We don't really care if this succeeds or fails. If it succeeds this->completions will be
// updated with choices for the user.
expand_error_t ignore =
expand_string(str_cmd, &this->completions,
EXPAND_FOR_COMPLETIONS | DIRECTORIES_ONLY | this->expand_flags(), NULL);
UNUSED(ignore);
}
if (str_cmd.find(L'/') == wcstring::npos && str_cmd.at(0) != L'~') {
if (use_function) {
wcstring_list_t names = function_get_names(str_cmd.at(0) == L'_');
for (size_t i = 0; i < names.size(); i++) {
append_completion(&possible_comp, names.at(i));
}
this->complete_strings(str_cmd, 0, &complete_function_desc, possible_comp, 0);
}
possible_comp.clear();
if (use_builtin) {
builtin_get_names(&possible_comp);
this->complete_strings(str_cmd, 0, &builtin_get_desc, possible_comp, 0);
}
}
}
/// Evaluate the argument list (as supplied by complete -a) and insert any
/// return matching completions. Matching is done using @c
/// copy_strings_with_prefix, meaning the completion may contain wildcards.
/// Logically, this is not always the right thing to do, but I have yet to come
/// up with a case where this matters.
///
/// @param str
/// The string to complete.
/// @param args
/// The list of option arguments to be evaluated.
/// @param desc
/// Description of the completion
/// @param flags
/// The list into which the results will be inserted
///
void completer_t::complete_from_args(const wcstring &str, const wcstring &args,
const wcstring &desc, complete_flags_t flags) {
bool is_autosuggest = (this->type() == COMPLETE_AUTOSUGGEST);
// If type is COMPLETE_AUTOSUGGEST, it means we're on a background thread, so don't call
// proc_push_interactive.
if (!is_autosuggest) {
proc_push_interactive(0);
}
expand_flags_t eflags = 0;
if (is_autosuggest) {
eflags |= EXPAND_NO_DESCRIPTIONS | EXPAND_SKIP_CMDSUBST;
}
std::vector<completion_t> possible_comp;
parser_t::expand_argument_list(args, eflags, &possible_comp);
if (!is_autosuggest) {
proc_pop_interactive();
}
this->complete_strings(escape_string(str, ESCAPE_ALL), desc.c_str(), 0, possible_comp, flags);
}
static size_t leading_dash_count(const wchar_t *str) {
size_t cursor = 0;
while (str[cursor] == L'-') {
cursor++;
}
return cursor;
}
/// Match a parameter.
static bool param_match(const complete_entry_opt_t *e, const wchar_t *optstr) {
bool result = false;
if (e->type != option_type_args_only) {
size_t dashes = leading_dash_count(optstr);
result = (dashes == e->expected_dash_count() && e->option == &optstr[dashes]);
}
return result;
}
/// Test if a string is an option with an argument, like --color=auto or -I/usr/include.
static const wchar_t *param_match2(const complete_entry_opt_t *e, const wchar_t *optstr) {
// We may get a complete_entry_opt_t with no options if it's just arguments.
if (e->option.empty()) {
return NULL;
}
// Verify leading dashes.
size_t cursor = leading_dash_count(optstr);
if (cursor != e->expected_dash_count()) {
return NULL;
}
// Verify options match.
if (!string_prefixes_string(e->option, &optstr[cursor])) {
return NULL;
}
cursor += e->option.length();
// Short options are like -DNDEBUG. Long options are like --color=auto. So check for an equal
// sign for long options.
if (e->type != option_type_short) {
if (optstr[cursor] != L'=') {
return NULL;
}
cursor += 1;
}
return &optstr[cursor];
}
/// Tests whether a short option is a viable completion. arg_str will be like '-xzv', nextopt will
/// be a character like 'f' options will be the list of all options, used to validate the argument.
static bool short_ok(const wcstring &arg, const complete_entry_opt_t *entry,
const option_list_t &options) {
// Ensure it's a short option.
if (entry->type != option_type_short || entry->option.empty()) {
return false;
}
const wchar_t nextopt = entry->option.at(0);
// Empty strings are always 'OK'.
if (arg.empty()) {
return true;
}
// The argument must start with exactly one dash.
if (leading_dash_count(arg.c_str()) != 1) {
return false;
}
// Short option must not be already present.
if (arg.find(nextopt) != wcstring::npos) {
return false;
}
// Verify that all characters in our combined short option list are present as short options in
// the options list. If we get a short option that can't be combined (NO_COMMON), then we stop.
bool result = true;
for (size_t i = 1; i < arg.size(); i++) {
wchar_t arg_char = arg.at(i);
const complete_entry_opt_t *match = NULL;
for (option_list_t::const_iterator iter = options.begin(); iter != options.end(); ++iter) {
if (iter->type == option_type_short && iter->option.at(0) == arg_char) {
match = &*iter;
break;
}
}
if (match == NULL || (match->result_mode & NO_COMMON)) {
result = false;
break;
}
}
return result;
}
/// Load command-specific completions for the specified command.
static void complete_load(const wcstring &name, bool reload) {
// We have to load this as a function, since it may define a --wraps or signature.
// See issue #2466.
function_load(name);
completion_autoloader.load(name, reload);
}
/// complete_param: Given a command, find completions for the argument str of command cmd_orig with
/// previous option popt.
///
/// Examples in format (cmd, popt, str):
///
/// echo hello world <tab> -> ("echo", "world", "")
/// echo hello world<tab> -> ("echo", "hello", "world")
///
/// Insert results into comp_out. Return true to perform file completion, false to disable it.
bool completer_t::complete_param(const wcstring &scmd_orig, const wcstring &spopt,
const wcstring &sstr, bool use_switches) {
const wchar_t *const cmd_orig = scmd_orig.c_str();
const wchar_t *const popt = spopt.c_str();
const wchar_t *const str = sstr.c_str();
bool use_common = 1, use_files = 1;
wcstring cmd, path;
parse_cmd_string(cmd_orig, path, cmd);
env_vars_snapshot_t vars; //does not need to be populated for our needs
// this has to be called before complete_load
if (!function_exists_no_autoload(cmd.c_str(), vars) && !builtin_exists(cmd)
&& !path_get_path(cmd, nullptr)) {
//Do not load custom completions if the head does not exist
//This prevents errors caused during the execution of completion providers for
//tools that do not exist. Applies to both manual completions ("cm<TAB>", "cmd <TAB>")
//and automatic completions ("gi" autosuggestion provider -> git)
}
else if (this->type() == COMPLETE_DEFAULT) {
ASSERT_IS_MAIN_THREAD();
complete_load(cmd, true);
} else if (this->type() == COMPLETE_AUTOSUGGEST &&
!completion_autoloader.has_tried_loading(cmd)) {
// Load this command (on the main thread)
iothread_perform_on_main([&]() {
complete_load(cmd, false);
});
}
// Make a list of lists of all options that we care about.
std::vector<option_list_t> all_options;
{
scoped_lock lock(completion_lock);
for (completion_entry_set_t::const_iterator iter = completion_set.begin();
iter != completion_set.end(); ++iter) {
const completion_entry_t &i = *iter;
const wcstring &match = i.cmd_is_path ? path : cmd;
if (wildcard_match(match, i.cmd)) {
// Copy all of their options into our list.
all_options.push_back(i.get_options()); // Oof, this is a lot of copying
}
}
}
// Now release the lock and test each option that we captured above. We have to do this outside
// the lock because callouts (like the condition) may add or remove completions. See issue 2.
for (std::vector<option_list_t>::const_iterator iter = all_options.begin();
iter != all_options.end(); ++iter) {
const option_list_t &options = *iter;
use_common = 1;
if (use_switches) {
if (str[0] == L'-') {
// Check if we are entering a combined option and argument (like --color=auto or
// -I/usr/include).
for (option_list_t::const_iterator oiter = options.begin(); oiter != options.end();
++oiter) {
const complete_entry_opt_t *o = &*oiter;
const wchar_t *arg = param_match2(o, str);
if (arg != NULL && this->condition_test(o->condition)) {
if (o->result_mode & NO_COMMON) use_common = false;
if (o->result_mode & NO_FILES) use_files = false;
complete_from_args(arg, o->comp, o->localized_desc(), o->flags);
}
}
} else if (popt[0] == L'-') {
// Set to true if we found a matching old-style switch.
// Here we are testing the previous argument,
// to see how we should complete the current argument
bool old_style_match = false;
// If we are using old style long options, check for them first.
for (option_list_t::const_iterator oiter = options.begin(); oiter != options.end();
++oiter) {
const complete_entry_opt_t *o = &*oiter;
if (o->type == option_type_single_long && param_match(o, popt) &&
this->condition_test(o->condition)) {
old_style_match = true;
if (o->result_mode & NO_COMMON) use_common = false;
if (o->result_mode & NO_FILES) use_files = false;
complete_from_args(str, o->comp, o->localized_desc(), o->flags);
}
}
// No old style option matched, or we are not using old style options. We check if
// any short (or gnu style options do.
if (!old_style_match) {
for (option_list_t::const_iterator oiter = options.begin();
oiter != options.end(); ++oiter) {
const complete_entry_opt_t *o = &*oiter;
// Gnu-style options with _optional_ arguments must be specified as a single
// token, so that it can be differed from a regular argument.
// Here we are testing the previous argument for a GNU-style match,
// to see how we should complete the current argument
if (o->type == option_type_double_long && !(o->result_mode & NO_COMMON))
continue;
if (param_match(o, popt) && this->condition_test(o->condition)) {
if (o->result_mode & NO_COMMON) use_common = false;
if (o->result_mode & NO_FILES) use_files = false;
complete_from_args(str, o->comp, o->localized_desc(), o->flags);
}
}
}
}
}
if (!use_common) {
continue;
}
// Now we try to complete an option itself
for (option_list_t::const_iterator oiter = options.begin(); oiter != options.end();
++oiter) {
const complete_entry_opt_t *o = &*oiter;
// If this entry is for the base command, check if any of the arguments match.
if (!this->condition_test(o->condition)) continue;
if (o->option.empty()) {
use_files = use_files && ((o->result_mode & NO_FILES) == 0);
complete_from_args(str, o->comp, o->localized_desc(), o->flags);
}
if (wcslen(str) == 0 || !use_switches) {
continue;
}
// Check if the short style option matches.
if (short_ok(str, o, options)) {
// It's a match.
const wcstring desc = o->localized_desc();
append_completion(&this->completions, o->option, desc, 0);
}
// Check if the long style option matches.
if (o->type != option_type_single_long && o->type != option_type_double_long) {
continue;
}
int match = 0, match_no_case = 0;
wcstring whole_opt(o->expected_dash_count(), L'-');
whole_opt.append(o->option);
match = string_prefixes_string(str, whole_opt);
if (!match) {
match_no_case = wcsncasecmp(str, whole_opt.c_str(), wcslen(str)) == 0;
}
if (!match && !match_no_case) {
continue;
}
int has_arg = 0; // does this switch have any known arguments
int req_arg = 0; // does this switch _require_ an argument
size_t offset = 0;
complete_flags_t flags = 0;
if (match) {
offset = wcslen(str);
} else {
flags = COMPLETE_REPLACES_TOKEN;
}
has_arg = !o->comp.empty();
req_arg = (o->result_mode & NO_COMMON);
if (o->type == option_type_double_long && (has_arg && !req_arg)) {
// Optional arguments to a switch can only be handled using the '=', so we add it as
// a completion. By default we avoid using '=' and instead rely on '--switch