forked from scop/bash-completion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bash_completion
3346 lines (3079 loc) · 119 KB
/
bash_completion
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
# -*- shell-script -*-
#
# bash_completion - programmable completion functions for bash 4.2+
#
# Copyright © 2006-2008, Ian Macdonald <[email protected]>
# © 2009-2020, Bash Completion Maintainers
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# The latest version of this software can be obtained here:
#
# https://github.com/scop/bash-completion
BASH_COMPLETION_VERSINFO=(
2 # x-release-please-major
14 # x-release-please-minor
0 # x-release-please-patch
)
if [[ $- == *v* ]]; then
_comp__init_original_set_v="-v"
else
_comp__init_original_set_v="+v"
fi
if [[ ${BASH_COMPLETION_DEBUG-} ]]; then
set -v
else
set +v
fi
# Turn on extended globbing and programmable completion
shopt -s extglob progcomp
# Declare a compatibility function name
# @param $1 Version of bash-completion where the deprecation occurred
# @param $2 Old function name
# @param $3 New function name
# @since 2.12
_comp_deprecate_func()
{
if (($# != 3)); then
printf 'bash_completion: %s: usage: %s DEPRECATION_VERSION OLD_NAME NEW_NAME\n' "$FUNCNAME" "$FUNCNAME"
return 2
fi
if [[ $2 != [a-zA-Z_]*([a-zA-Z_0-9]) ]]; then
printf 'bash_completion: %s: %s\n' "$FUNCNAME" "\$2: invalid function name '$1'" >&2
return 2
elif [[ $3 != [a-zA-Z_]*([a-zA-Z_0-9]) ]]; then
printf 'bash_completion: %s: %s\n' "$FUNCNAME" "\$3: invalid function name '$2'" >&2
return 2
fi
eval -- "$2() { $3 \"\$@\"; }"
}
# Declare a compatibility variable name.
# For bash 4.3+, a real name alias is created, allowing value changes to
# "apply through" when the variables are set later. For bash versions earlier
# than that, the operation is once-only; the value of the new variable
# (if it's unset) is set to that of the old (if set) at call time.
#
# @param $1 Version of bash-completion where the deprecation occurred
# @param $2 Old variable name
# @param $3 New variable name
# @since 2.12
_comp_deprecate_var()
{
if (($# != 3)); then
printf 'bash_completion: %s: usage: %s DEPRECATION_VERSION OLD_NAME NEW_NAME\n' "$FUNCNAME" "$FUNCNAME"
return 2
fi
if [[ $2 != [a-zA-Z_]*([a-zA-Z_0-9]) ]]; then
printf 'bash_completion: %s: %s\n' "$FUNCNAME" "\$2: invalid variable name '$1'" >&2
return 2
elif [[ $3 != [a-zA-Z_]*([a-zA-Z_0-9]) ]]; then
printf 'bash_completion: %s: %s\n' "$FUNCNAME" "\$3: invalid variable name '$2'" >&2
return 2
fi
if ((BASH_VERSINFO[0] >= 5 || BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 3)); then
eval "declare -gn $2=$3"
elif [[ -v $2 && ! -v $3 ]]; then
printf -v "$3" %s "$2"
fi
}
# A lot of the following one-liners were taken directly from the
# completion examples provided with the bash 2.04 source distribution
# start of section containing compspecs that can be handled within bash
# user commands see only users
complete -u groups slay w sux
# bg completes with stopped jobs
complete -A stopped -P '"%' -S '"' bg
# other job commands
complete -j -P '"%' -S '"' fg jobs disown
# readonly and unset complete with shell variables
complete -v readonly unset
# shopt completes with shopt options
complete -A shopt shopt
# unalias completes with aliases
complete -a unalias
# type and which complete on commands
complete -c command type which
# builtin completes on builtins
complete -b builtin
# start of section containing completion functions called by other functions
# Check if we're running on the given userland
# @param $1 userland to check for
# @since 2.12
_comp_userland()
{
local userland=$(uname -s)
[[ $userland == @(Linux|GNU/*) ]] && userland=GNU
[[ $userland == "$1" ]]
}
# This function sets correct SysV init directories
#
# @since 2.12
_comp_sysvdirs()
{
sysvdirs=()
[[ -d /etc/rc.d/init.d ]] && sysvdirs+=(/etc/rc.d/init.d)
[[ -d /etc/init.d ]] && sysvdirs+=(/etc/init.d)
# Slackware uses /etc/rc.d
[[ -f /etc/slackware-version ]] && sysvdirs=(/etc/rc.d)
((${#sysvdirs[@]}))
}
# This function checks whether we have a given program on the system.
#
# @since 2.12
_comp_have_command()
{
# Completions for system administrator commands are installed as well in
# case completion is attempted via `sudo command ...'.
PATH=$PATH:/usr/sbin:/sbin:/usr/local/sbin type "$1" &>/dev/null
}
# This function checks whether a given readline variable
# is `on'.
#
# @since 2.12
_comp_readline_variable_on()
{
[[ $(bind -v) == *$1+([[:space:]])on* ]]
}
# This function shell-quotes the argument
# @param $1 String to be quoted
# @var[out] REPLY Resulting string
# @since 2.12
_comp_quote()
{
REPLY=\'${1//\'/\'\\\'\'}\'
}
# shellcheck disable=SC1003
_comp_dequote__initialize()
{
unset -f "$FUNCNAME"
local regex_param='\$([_a-zA-Z][_a-zA-Z0-9]*|[-*@#?$!0-9_])|\$\{[!#]?([_a-zA-Z][_a-zA-Z0-9]*(\[([0-9]+|[*@])\])?|[-*@#?$!0-9_])\}'
local regex_quoted='\\.|'\''[^'\'']*'\''|\$?"([^\"$`!]|'$regex_param'|\\.)*"|\$'\''([^\'\'']|\\.)*'\'''
_comp_dequote__regex_safe_word='^([^\'\''"$`;&|<>()!]|'$regex_quoted'|'$regex_param')*$'
}
_comp_dequote__initialize
# This function expands a word using `eval` in a safe way. This function can
# be typically used to get the expanded value of `${word[i]}` as
# `_comp_dequote "${word[i]}"`. When the word contains unquoted shell special
# characters, command substitutions, and other unsafe strings, the function
# call fails before applying `eval`. Otherwise, `eval` is applied to the
# string to generate the result.
#
# @param $1 String to be expanded. A safe word consists of the following
# sequence of substrings:
#
# - Shell non-special characters: [^\'"$`;&|<>()!].
# - Parameter expansions of the forms $PARAM, ${!PARAM},
# ${#PARAM}, ${NAME[INDEX]}, ${!NAME[INDEX]}, ${#NAME[INDEX]}
# where INDEX is an integer, `*` or `@`, NAME is a valid
# variable name [_a-zA-Z][_a-zA-Z0-9]*, and PARAM is NAME or a
# parameter [-*@#?$!0-9_].
# - Quotes \?, '...', "...", $'...', and $"...". In the double
# quotations, parameter expansions are allowed.
#
# @var[out] REPLY Array that contains the expanded results. Multiple words or
# no words may be generated through pathname expansions.
#
# Note: This function allows parameter expansions as safe strings, which might
# cause unexpected results:
#
# * This allows execution of arbitrary commands through extra expansions of
# array subscripts in name references. For example,
#
# declare -n v='dummy[$(echo xxx >/dev/tty)]'
# echo "$v" # This line executes the command 'echo xxx'.
# _comp_dequote '"$v"' # This line also executes it.
#
# * This may change the internal state of the variable that has side effects.
# For example, the state of the random number generator of RANDOM can change:
#
# RANDOM=1234 # Set seed
# echo "$RANDOM" # This produces 30658.
# RANDOM=1234 # Reset seed
# _comp_dequote '"$RANDOM"' # This line changes the internal state.
# echo "$RANDOM" # This fails to reproduce 30658.
#
# We allow these parameter expansions as a part of safe strings assuming the
# referential transparency of the simple parameter expansions and the sane
# setup of the variables by the user or other frameworks that the user loads.
# @since 2.12
_comp_dequote()
{
REPLY=() # fallback value for unsafe word and failglob
[[ $1 =~ $_comp_dequote__regex_safe_word ]] || return 1
eval "REPLY=($1)" 2>/dev/null # may produce failglob
}
# Unset the given variables across a scope boundary. Useful for unshadowing
# global scoped variables. Note that simply calling unset on a local variable
# will not unshadow the global variable. Rather, the result will be a local
# variable in an unset state.
# Usage: local IFS='|'; _comp_unlocal IFS
# @param $* Variable names to be unset
# @since 2.12
_comp_unlocal()
{
if ((BASH_VERSINFO[0] >= 5)) && shopt -q localvar_unset; then
shopt -u localvar_unset
unset -v "$@"
shopt -s localvar_unset
else
unset -v "$@"
fi
}
# Assign variables one scope above the caller
# Usage: local varname [varname ...] &&
# _comp_upvars [-v varname value] | [-aN varname [value ...]] ...
# Available OPTIONS:
# -aN Assign next N values to varname as array
# -v Assign single value to varname
# @return 1 if error occurs
# @see https://fvue.nl/wiki/Bash:_Passing_variables_by_reference
# @since 2.12
_comp_upvars()
{
if ! (($#)); then
echo "bash_completion: $FUNCNAME: usage: $FUNCNAME" \
"[-v varname value] | [-aN varname [value ...]] ..." >&2
return 2
fi
while (($#)); do
case $1 in
-a*)
# Error checking
[[ ${1#-a} ]] || {
echo "bash_completion: $FUNCNAME:" \
"\`$1': missing number specifier" >&2
return 1
}
printf %d "${1#-a}" &>/dev/null || {
echo bash_completion: \
"$FUNCNAME: \`$1': invalid number specifier" >&2
return 1
}
# Assign array of -aN elements
# shellcheck disable=SC2015,SC2140 # TODO
[[ $2 ]] && unset -v "$2" && eval "$2"=\(\"\$"{@:3:${1#-a}}"\"\) &&
shift $((${1#-a} + 2)) || {
echo bash_completion: \
"$FUNCNAME: \`$1${2+ }$2': missing argument(s)" \
>&2
return 1
}
;;
-v)
# Assign single value
# shellcheck disable=SC2015 # TODO
[[ $2 ]] && unset -v "$2" && eval "$2"=\"\$3\" &&
shift 3 || {
echo "bash_completion: $FUNCNAME: $1:" \
"missing argument(s)" >&2
return 1
}
;;
*)
echo "bash_completion: $FUNCNAME: $1: invalid option" >&2
return 1
;;
esac
done
}
# Get the list of filenames that match with the specified glob pattern.
# This function does the globbing in a controlled environment, avoiding
# interference from user's shell options/settings or environment variables.
# @param $1 array_name Array name
# The array name should not start with an underscore "_", which is internally
# used. The array name should not be "GLOBIGNORE".
# @param $2 pattern Pattern string to be evaluated.
# This pattern string will be evaluated using "eval", so brace expansions,
# parameter expansions, command substitutions, and other expansions will be
# processed. The user-provided strings should not be directly specified to
# this argument.
# @return 0 if at least one path is generated, 1 if no path is generated, or 2
# if the usage is incorrect.
# @since 2.12
_comp_expand_glob()
{
if (($# != 2)); then
printf 'bash-completion: %s: unexpected number of arguments\n' "$FUNCNAME" >&2
printf 'usage: %s ARRAY_NAME PATTERN\n' "$FUNCNAME" >&2
return 2
elif [[ $1 == @(GLOBIGNORE|_*|*[^_a-zA-Z0-9]*|[0-9]*|'') ]]; then
printf 'bash-completion: %s: invalid array name "%s"\n' "$FUNCNAME" "$1" >&2
return 2
fi
# Save and adjust the settings.
local _original_opts=$SHELLOPTS:$BASHOPTS
set +o noglob
shopt -s nullglob
shopt -u failglob dotglob
# Also the user's GLOBIGNORE may affect the result of pathname expansions.
local GLOBIGNORE=
eval -- "$1=()" # a fallback in case that the next line fails.
eval -- "$1=($2)"
# Restore the settings. Note: Changing GLOBIGNORE affects the state of
# "shopt -q dotglob", so we need to explicitly restore the original state
# of "shopt -q dotglob".
_comp_unlocal GLOBIGNORE
if [[ :$_original_opts: == *:dotglob:* ]]; then
shopt -s dotglob
else
shopt -u dotglob
fi
[[ :$_original_opts: == *:nullglob:* ]] || shopt -u nullglob
[[ :$_original_opts: == *:failglob:* ]] && shopt -s failglob
[[ :$_original_opts: == *:noglob:* ]] && set -o noglob
eval "((\${#$1[@]}))"
}
# Split a string and assign to an array. This function basically performs
# `IFS=<sep>; <array_name>=(<text>)` but properly handles saving/restoring the
# state of `IFS` and the shell option `noglob`. A naive splitting by
# `arr=(...)` suffers from unexpected IFS and pathname expansions, so one
# should prefer this function to such naive splitting.
# OPTIONS
# -a Append to the array
# -F sep Set a set of separator characters (used as IFS). The default
# separator is $' \t\n'
# -l The same as -F $'\n'
# @param $1 array_name The array name
# The array name should not start with an underscores "_", which is
# internally used. The array name should not be either "IFS" or
# "OPT{IND,ARG,ERR}".
# @param $2 text The string to split
# @return 2 when the usage is wrong, 0 when one or more completions are
# generated, or 1 when the execution succeeds but no candidates are
# generated.
# @since 2.12
_comp_split()
{
local _append="" IFS=$' \t\n'
local OPTIND=1 OPTARG="" OPTERR=0 _opt
while getopts ':alF:' _opt "$@"; do
case $_opt in
a) _append=set ;;
l) IFS=$'\n' ;;
F) IFS=$OPTARG ;;
*)
echo "bash_completion: $FUNCNAME: usage error" >&2
return 2
;;
esac
done
shift "$((OPTIND - 1))"
if (($# != 2)); then
printf '%s\n' "bash_completion: $FUNCNAME: unexpected number of arguments" >&2
printf '%s\n' "usage: $FUNCNAME [-al] [-F SEP] ARRAY_NAME TEXT" >&2
return 2
elif [[ $1 == @(*[^_a-zA-Z0-9]*|[0-9]*|''|_*|IFS|OPTIND|OPTARG|OPTERR) ]]; then
printf '%s\n' "bash_completion: $FUNCNAME: invalid array name '$1'" >&2
return 2
fi
local _original_opts=$SHELLOPTS
set -o noglob
local _old_size _new_size
if [[ $_append ]]; then
eval "$1+=()" # in case $1 is unset
eval "_old_size=\${#$1[@]}"
eval "$1+=(\$2)"
else
_old_size=0
eval "$1=(\$2)"
fi
eval "_new_size=\${#$1[@]}"
[[ :$_original_opts: == *:noglob:* ]] || set +o noglob
((_new_size > _old_size))
}
# Helper function for _comp_compgen
# @var[in] $?
# @var[in] _var
# @var[in] _append
# @return original $?
_comp_compgen__error_fallback()
{
local _status=$?
if [[ $_append ]]; then
# make sure existence of variable
eval -- "$_var+=()"
else
eval -- "$_var=()"
fi
return "$_status"
}
# Provide a common interface to generate completion candidates in COMPREPLY or
# in a specified array.
# OPTIONS
# -a Append to the array
# -v arr Store the results to the array ARR. The default is `COMPREPLY`.
# The array name should not start with an underscores "_", which is
# internally used. The array name should not be any of "cur", "IFS"
# or "OPT{IND,ARG,ERR}".
# -U var Unlocalize VAR before performing the assignments. This option can
# be specified multiple times to register multiple variables. This
# option is supposed to be used in implementing a generator (G1) when
# G1 defines a local variable name that does not start with `_`. In
# such a case, when the target variable specified to G1 by `-v VAR1`
# conflicts with the local variable, the assignment to the target
# variable fails to propagate outside G1. To avoid such a situation,
# G1 can call `_comp_compgen` with `-U VAR` to unlocalize `VAR`
# before accessing the target variable. For a builtin compgen call
# (i.e., _comp_compgen [options] -- options), VAR is unlocalized
# after calling the builtin `compgen` but before assigning results to
# the target array. For a generator call (i.e., _comp_compgen
# [options] G2 ...), VAR is unlocalized before calling the child
# generator function `_comp_compgen_G2`.
# -c cur Set a word used as a prefix to filter the completions. The default
# is ${cur-}.
# -R The same as -c ''. Use raw outputs without filtering.
# -C dir Evaluate compgen/generator in the specified directory.
# @var[in,opt] cur Used as the default value of a prefix to filter the
# completions.
#
# Usage #1: _comp_compgen [-alR|-F sep|-v arr|-c cur|-C dir] -- options...
# Call `compgen` with the specified arguments and store the results in the
# specified array. This function essentially performs arr=($(compgen args...))
# but properly handles shell options, IFS, etc. using _comp_split. This
# function is equivalent to `_comp_split [-a] -l arr "$(IFS=sep; compgen
# args... -- cur)"`, but this pattern is frequent in the codebase and is good
# to separate out as a function for the possible future implementation change.
# OPTIONS
# -F sep Set a set of separator characters (used as IFS in evaluating
# `compgen'). The default separator is $' \t\n'. Note that this is
# not the set of separators to delimit output of `compgen', but the
# separators in evaluating the expansions of `-W '...'`, etc. The
# delimiter of the output of `compgen` is always a newline.
# -l The same as -F $'\n'. Use lines as words in evaluating compgen.
# @param $1... options Arguments that are passed to compgen (if $1 starts with
# a hyphen `-`).
#
# Note: References to positional parameters $1, $2, ... (such as -W '$1')
# will not work as expected because these reference the arguments of
# `_comp_compgen' instead of those of the caller function. When there are
# needs to reference them, save the arguments to an array and reference the
# array instead.
#
# Note: The array option `-V arr` in bash >= 5.3 should be instead specified
# as `-v arr` as a part of the `_comp_compgen` options.
# @return True (0) if at least one completion is generated, False (1) if no
# completion is generated, or 2 with an incorrect usage.
#
# Usage #2: _comp_compgen [-aR|-v arr|-c cur|-C dir|-i cmd|-x cmd] name args...
# Call the generator `_comp_compgen_NAME ARGS...` with the specified options.
# This provides a common interface to call the functions `_comp_compgen_NAME`,
# which produce completion candidates, with custom options [-alR|-v arr|-c
# cur]. The option `-F sep` is not used with this usage.
# OPTIONS
# -x cmd Call exported generator `_comp_xfunc_CMD_compgen_NAME`
# -i cmd Call internal generator `_comp_cmd_CMD__compgen_NAME`
# @param $1... name args Calls the function _comp_compgen_NAME with the
# specified ARGS (if $1 does not start with a hyphen `-`). The options
# [-alR|-v arr|-c cur] are inherited by the child calls of `_comp_compgen`
# inside `_comp_compgen_NAME` unless the child call `_comp_compgen` receives
# overriding options.
# @var[in,opt,internal] _comp_compgen__append
# @var[in,opt,internal] _comp_compgen__var
# @var[in,opt,internal] _comp_compgen__cur
# These variables are internally used to pass the effect of the options
# [-alR|-v arr|-c cur] to the child calls of `_comp_compgen` in
# `_comp_compgen_NAME`.
# @return Exit status of the generator.
#
# @remarks When no options are supplied to _comp_compgen, `_comp_compgen NAME
# args` is equivalent to the direct call `_comp_compgen_NAME args`. As the
# direct call is slightly more efficient, the direct call is preferred over
# calling it through `_comp_compgen`.
#
# @remarks Design `_comp_compgen_NAME`: a function that produce completions can
# be defined with the name _comp_compgen_NAME. The function is supposed to
# generate completions by calling `_comp_compgen`. To reflect the options
# specified to the outer calls of `_comp_compgen`, the function should not
# directly modify `COMPREPLY`. To add words, one can call
#
# _comp_compgen -- -W '"${words[@]}"'
#
# To directly add words without filtering by `cur`, one can call
#
# _comp_compgen -R -- -W '"${words[@]}"'
#
# or use the utility `_comp_compgen_set`:
#
# _comp_compgen_set "${words[@]}"
#
# Other nested calls of _comp_compgen can also be used. The function is
# supposed to replace the existing content of the array by default to allow the
# caller control whether to replace or append by the option `-a`.
#
# @since 2.12
_comp_compgen()
{
local _append=
local _var=
local _cur=${_comp_compgen__cur-${cur-}}
local _dir=""
local _ifs=$' \t\n' _has_ifs=""
local _icmd="" _xcmd=""
local -a _upvars=()
local _old_nocasematch=""
if shopt -q nocasematch; then
_old_nocasematch=set
shopt -u nocasematch
fi
local OPTIND=1 OPTARG="" OPTERR=0 _opt
while getopts ':av:U:Rc:C:lF:i:x:' _opt "$@"; do
case $_opt in
a) _append=set ;;
v)
if [[ $OPTARG == @(*[^_a-zA-Z0-9]*|[0-9]*|''|_*|IFS|OPTIND|OPTARG|OPTERR|cur) ]]; then
printf 'bash_completion: %s: -v: invalid array name `%s'\''\n' "$FUNCNAME" "$OPTARG" >&2
return 2
fi
_var=$OPTARG
;;
U)
if [[ $OPTARG == @(*[^_a-zA-Z0-9]*|[0-9]*|'') ]]; then
printf 'bash_completion: %s: -U: invalid variable name `%s'\''\n' "$FUNCNAME" "$OPTARG" >&2
return 2
elif [[ $OPTARG == @(_*|IFS|OPTIND|OPTARG|OPTERR|cur) ]]; then
printf 'bash_completion: %s: -U: unnecessary to mark `%s'\'' as upvar\n' "$FUNCNAME" "$OPTARG" >&2
return 2
fi
_upvars+=("$OPTARG")
;;
c) _cur=$OPTARG ;;
R) _cur="" ;;
C)
if [[ ! $OPTARG ]]; then
printf 'bash_completion: %s: -C: invalid directory name `%s'\''\n' "$FUNCNAME" "$OPTARG" >&2
return 2
fi
_dir=$OPTARG
;;
l) _has_ifs=set _ifs=$'\n' ;;
F) _has_ifs=set _ifs=$OPTARG ;;
[ix])
if [[ ! $OPTARG ]]; then
printf 'bash_completion: %s: -%s: invalid command name `%s'\''\n' "$FUNCNAME" "$_opt" "$OPTARG" >&2
return 2
elif [[ $_icmd ]]; then
printf 'bash_completion: %s: -%s: `-i %s'\'' is already specified\n' "$FUNCNAME" "$_opt" "$_icmd" >&2
return 2
elif [[ $_xcmd ]]; then
printf 'bash_completion: %s: -%s: `-x %s'\'' is already specified\n' "$FUNCNAME" "$_opt" "$_xcmd" >&2
return 2
fi
;;&
i) _icmd=$OPTARG ;;
x) _xcmd=$OPTARG ;;
*)
printf 'bash_completion: %s: usage error\n' "$FUNCNAME" >&2
return 2
;;
esac
done
[[ $_old_nocasematch ]] && shopt -s nocasematch
shift "$((OPTIND - 1))"
if (($# == 0)); then
printf 'bash_completion: %s: unexpected number of arguments\n' "$FUNCNAME" >&2
printf 'usage: %s [-alR|-F SEP|-v ARR|-c CUR] -- ARGS...' "$FUNCNAME" >&2
return 2
fi
if [[ ! $_var ]]; then
# Inherit _append and _var only when -v var is unspecified.
_var=${_comp_compgen__var-COMPREPLY}
[[ $_append ]] || _append=${_comp_compgen__append-}
fi
if [[ $1 != -* ]]; then
# usage: _comp_compgen [options] NAME args
if [[ $_has_ifs ]]; then
printf 'bash_completion: %s: `-l'\'' and `-F sep'\'' are not supported for generators\n' "$FUNCNAME" >&2
return 2
fi
local -a _generator
if [[ $_icmd ]]; then
_generator=("_comp_cmd_${_icmd//[^a-zA-Z0-9_]/_}__compgen_$1")
elif [[ $_xcmd ]]; then
_generator=(_comp_xfunc "$_xcmd" "compgen_$1")
else
_generator=("_comp_compgen_$1")
fi
if ! declare -F -- "${_generator[0]}" &>/dev/null; then
printf 'bash_completion: %s: unrecognized generator `%s'\'' (function %s not found)\n' "$FUNCNAME" "$1" "${_generator[0]}" >&2
return 2
fi
((${#_upvars[@]})) && _comp_unlocal "${_upvars[@]}"
if [[ $_dir ]]; then
local _original_pwd=$PWD
local PWD=${PWD-} OLDPWD=${OLDPWD-}
# Note: We also redirect stdout because `cd` may output the target
# directory to stdout when CDPATH is set.
command cd -- "$_dir" &>/dev/null ||
{
_comp_compgen__error_fallback
return
}
fi
local _comp_compgen__append=$_append
local _comp_compgen__var=$_var
local _comp_compgen__cur=$_cur cur=$_cur
# Note: we use $1 as a part of a function name, and we use $2... as
# arguments to the function if any.
# shellcheck disable=SC2145
"${_generator[@]}" "${@:2}"
local _status=$?
# Go back to the original directory.
# Note: Failure of this line results in the change of the current
# directory visible to the user. We intentionally do not redirect
# stderr so that the error message appear in the terminal.
# shellcheck disable=SC2164
[[ $_dir ]] && command cd -- "$_original_pwd"
return "$_status"
fi
# usage: _comp_compgen [options] -- [compgen_options]
if [[ $_icmd || $_xcmd ]]; then
printf 'bash_completion: %s: generator name is unspecified for `%s'\''\n' "$FUNCNAME" "${_icmd:+-i $_icmd}${_xcmd:+x $_xcmd}" >&2
return 2
fi
# Note: $* in the below checks would be affected by uncontrolled IFS in
# bash >= 5.0, so we need to set IFS to the normal value. The behavior in
# bash < 5.0, where unquoted $* in conditional command did not honor IFS,
# was a bug.
# Note: Also, ${_cur:+-- "$_cur"} and ${_append:+-a} would be affected by
# uncontrolled IFS.
local IFS=$' \t\n'
# Note: extglob *\$?(\{)[0-9]* can be extremely slow when the string
# "${*:2:_nopt}" becomes longer, so we test \$[0-9] and \$\{[0-9]
# separately.
if [[ $* == *\$[0-9]* || $* == *\$\{[0-9]* ]]; then
printf 'bash_completion: %s: positional parameter $1, $2, ... do not work inside this function\n' "$FUNCNAME" >&2
return 2
fi
local _result
_result=$(
if [[ $_dir ]]; then
# Note: We also redirect stdout because `cd` may output the target
# directory to stdout when CDPATH is set.
command cd -- "$_dir" &>/dev/null || return
fi
IFS=$_ifs compgen "$@" ${_cur:+-- "$_cur"}
) || {
_comp_compgen__error_fallback
return
}
((${#_upvars[@]})) && _comp_unlocal "${_upvars[@]}"
_comp_split -l ${_append:+-a} "$_var" "$_result"
}
# usage: _comp_compgen_set [words...]
# Reset COMPREPLY with the specified WORDS. If no arguments are specified, the
# array is cleared.
#
# When an array name is specified by `-v VAR` in a caller _comp_compgen, the
# array is reset instead of COMPREPLY. When the `-a` flag is specified in a
# caller _comp_compgen, the words are appended to the existing elements of the
# array instead of replacing the existing elements. This function ignores
# ${cur-} or the prefix specified by `-v CUR`.
# @return 0 if at least one completion is generated, or 1 otherwise.
# @since 2.12
_comp_compgen_set()
{
local _append=${_comp_compgen__append-}
local _var=${_comp_compgen__var-COMPREPLY}
eval -- "$_var${_append:++}=(\"\$@\")"
(($#))
}
# Simply split the text and generate completions. This function should be used
# instead of `_comp_compgen -- -W "$(command)"`, which is vulnerable because
# option -W evaluates the shell expansions included in the option argument.
# Options:
# -F sep Specify the separators. The default is $' \t\n'
# -l The same as -F $'\n'
# -X arg The same as the compgen option -X.
# -S arg The same as the compgen option -S.
# -P arg The same as the compgen option -P.
# -o arg The same as the compgen option -o.
# @param $1 String to split
# @return 0 if at least one completion is generated, or 1 otherwise.
# @since 2.12
_comp_compgen_split()
{
local _ifs=$' \t\n'
local -a _compgen_options=()
local OPTIND=1 OPTARG="" OPTERR=0 _opt
while getopts ':lF:X:S:P:o:' _opt "$@"; do
case $_opt in
l) _ifs=$'\n' ;;
F) _ifs=$OPTARG ;;
[XSPo]) _compgen_options+=("-$_opt" "$OPTARG") ;;
*)
printf 'bash_completion: usage: %s [-l|-F sep] [--] str\n' "$FUNCNAME" >&2
return 2
;;
esac
done
shift "$((OPTIND - 1))"
if (($# != 1)); then
printf 'bash_completion: %s: unexpected number of arguments.\n' "$FUNCNAME" >&2
printf 'usage: %s [-l|-F sep] [--] str' "$FUNCNAME" >&2
return 2
fi
local input=$1 IFS=$' \t\n'
_comp_compgen -F "$_ifs" -U input -- ${_compgen_options[@]+"${_compgen_options[@]}"} -W '$input'
}
# Check if the argument looks like a path.
# @param $1 thing to check
# @return True (0) if it does, False (> 0) otherwise
# @since 2.12
_comp_looks_like_path()
{
[[ ${1-} == @(*/|[.~])* ]]
}
# Reassemble command line words, excluding specified characters from the
# list of word completion separators (COMP_WORDBREAKS).
# @param $1 chars Characters out of $COMP_WORDBREAKS which should
# NOT be considered word breaks. This is useful for things like scp where
# we want to return host:path and not only path, so we would pass the
# colon (:) as $1 here.
# @param $2 words Name of variable to return words to
# @param $3 cword Name of variable to return cword to
#
_comp__reassemble_words()
{
local exclude="" i j line ref
# Exclude word separator characters?
if [[ $1 ]]; then
# Yes, exclude word separator characters;
# Exclude only those characters, which were really included
exclude="[${1//[^$COMP_WORDBREAKS]/}]"
fi
# Default to cword unchanged
printf -v "$3" %s "$COMP_CWORD"
# Are characters excluded which were former included?
if [[ $exclude ]]; then
# Yes, list of word completion separators has shrunk;
line=$COMP_LINE
# Re-assemble words to complete
for ((i = 0, j = 0; i < ${#COMP_WORDS[@]}; i++, j++)); do
# Is current word not word 0 (the command itself) and is word not
# empty and is word made up of just word separator characters to
# be excluded and is current word not preceded by whitespace in
# original line?
while [[ $i -gt 0 && ${COMP_WORDS[i]} == +($exclude) ]]; do
# Is word separator not preceded by whitespace in original line
# and are we not going to append to word 0 (the command
# itself), then append to current word.
[[ $line != [[:blank:]]* ]] && ((j >= 2)) && ((j--))
# Append word separator to current or new word
ref="$2[$j]"
printf -v "$ref" %s "${!ref-}${COMP_WORDS[i]}"
# Indicate new cword
((i == COMP_CWORD)) && printf -v "$3" %s "$j"
# Remove optional whitespace + word separator from line copy
line=${line#*"${COMP_WORDS[i]}"}
# Indicate next word if available, else end *both* while and
# for loop
if ((i < ${#COMP_WORDS[@]} - 1)); then
((i++))
else
break 2
fi
# Start new word if word separator in original line is
# followed by whitespace.
[[ $line == [[:blank:]]* ]] && ((j++))
done
# Append word to current word
ref="$2[$j]"
printf -v "$ref" %s "${!ref-}${COMP_WORDS[i]}"
# Remove optional whitespace + word from line copy
line=${line#*"${COMP_WORDS[i]}"}
# Indicate new cword
((i == COMP_CWORD)) && printf -v "$3" %s "$j"
done
((i == COMP_CWORD)) && printf -v "$3" %s "$j"
else
# No, list of word completions separators hasn't changed;
for i in "${!COMP_WORDS[@]}"; do
printf -v "$2[i]" %s "${COMP_WORDS[i]}"
done
fi
}
# @param $1 exclude Characters out of $COMP_WORDBREAKS which should NOT be
# considered word breaks. This is useful for things like scp where
# we want to return host:path and not only path, so we would pass the
# colon (:) as $1 in this case.
# @param $2 words Name of variable to return words to
# @param $3 cword Name of variable to return cword to
# @param $4 cur Name of variable to return current word to complete to
# @see _comp__reassemble_words()
_comp__get_cword_at_cursor()
{
local cword words=()
_comp__reassemble_words "$1" words cword
local i cur="" index=$COMP_POINT lead=${COMP_LINE:0:COMP_POINT}
# Cursor not at position 0 and not led by just space(s)?
if [[ $index -gt 0 && ($lead && ${lead//[[:space:]]/}) ]]; then
cur=$COMP_LINE
for ((i = 0; i <= cword; ++i)); do
# Current word fits in $cur, and $cur doesn't match cword?
while [[ ${#cur} -ge ${#words[i]} &&
${cur:0:${#words[i]}} != "${words[i]-}" ]]; do
# Strip first character
cur=${cur:1}
# Decrease cursor position, staying >= 0
((index > 0)) && ((index--))
done
# Does found word match cword?
if ((i < cword)); then
# No, cword lies further;
local old_size=${#cur}
cur=${cur#"${words[i]}"}
local new_size=${#cur}
((index -= old_size - new_size))
fi
done
# Clear $cur if just space(s)
[[ $cur && ! ${cur//[[:space:]]/} ]] && cur=
# Zero $index if negative
((index < 0)) && index=0
fi
local IFS=$' \t\n'
local "$2" "$3" "$4" && _comp_upvars -a"${#words[@]}" "$2" ${words[@]+"${words[@]}"} \
-v "$3" "$cword" -v "$4" "${cur:0:index}"
}
# Get the word to complete and optional previous words.
# This is nicer than ${COMP_WORDS[COMP_CWORD]}, since it handles cases
# where the user is completing in the middle of a word.
# (For example, if the line is "ls foobar",
# and the cursor is here --------> ^
# Also one is able to cross over possible wordbreak characters.
# Usage: _comp_get_words [OPTIONS] [VARNAMES]
# Available VARNAMES:
# cur Return cur via $cur
# prev Return prev via $prev
# words Return words via $words
# cword Return cword via $cword
#
# Available OPTIONS:
# -n EXCLUDE Characters out of $COMP_WORDBREAKS which should NOT be
# considered word breaks. This is useful for things like scp
# where we want to return host:path and not only path, so we
# would pass the colon (:) as -n option in this case.
# -c VARNAME Return cur via $VARNAME
# -p VARNAME Return prev via $VARNAME
# -w VARNAME Return words via $VARNAME
# -i VARNAME Return cword via $VARNAME
#
# Example usage:
#
# $ _comp_get_words -n : cur prev
#
# @since 2.12
_comp_get_words()
{
local exclude="" flag i OPTIND=1
local cur cword words=()
local upargs=() upvars=() vcur="" vcword="" vprev="" vwords=""
while getopts "c:i:n:p:w:" flag "$@"; do
case $flag in
[cipw])
if [[ $OPTARG != [a-zA-Z_]*([a-zA-Z_0-9])?(\[*\]) ]]; then
echo "bash_completion: $FUNCNAME: -$flag: invalid variable name \`$OPTARG'" >&2
return 1
fi
;;&
c) vcur=$OPTARG ;;
i) vcword=$OPTARG ;;
n) exclude=$OPTARG ;;
p) vprev=$OPTARG ;;
w) vwords=$OPTARG ;;
*)
echo "bash_completion: $FUNCNAME: usage error" >&2
return 1
;;
esac
done
while [[ $# -ge $OPTIND ]]; do
case ${!OPTIND} in
cur) vcur=cur ;;
prev) vprev=prev ;;
cword) vcword=cword ;;
words) vwords=words ;;
*)
echo "bash_completion: $FUNCNAME: \`${!OPTIND}':" \
"unknown argument" >&2
return 1
;;
esac
((OPTIND += 1))
done
_comp__get_cword_at_cursor "${exclude-}" words cword cur
[[ $vcur ]] && {
upvars+=("$vcur")
upargs+=(-v "$vcur" "$cur")
}
[[ $vcword ]] && {
upvars+=("$vcword")
upargs+=(-v "$vcword" "$cword")
}
[[ $vprev ]] && {
local value=""
((cword >= 1)) && value=${words[cword - 1]}
upvars+=("$vprev")
upargs+=(-v "$vprev" "$value")
}
[[ $vwords ]] && {
# Note: bash < 4.4 has a bug that all the elements are connected with
# ${v+"$@"} when IFS does not contain whitespace.
local IFS=$' \t\n'
upvars+=("$vwords")