I have a project where I'm regularly switching out different versions of a library. I have a script set_lib
that takes the library version as input and then sets the relevant environment variables. Sometimes I want to source this script and build/run things manually. I know how to configure autocomplete for functions/scripts, but what about for sourcing scripts? That is
>source set_lib v<tab><tab>
ver1 ver2 ver3
Also, I would like to keep autocomplete working as normal with source
when not in conjunction with set_lib
.
EDIT: As suggested I tried the following
_comp_set_lib() {
if [ ${COMP_WORDS[1]} == 'set_lib' ]; then
COMPREPLY=( "set_lib ver1" "set_lib ver2" )
fi
}
complete -o bashdefault -F _comp_set_lib source
$COMP_CWORD
being the second position is giving me problems. The above doesn't work as expected and gives me
>source set_lib <tab>
source set_lib ver
CodePudding user response:
I think the most convenient approach is to define a function that wraps source set_lib ...
:
function set_lib() {
source set_lib "$@"
}
and then set up autocompletes for that function.
But if you prefer to have to type source set_lib
and not just set_lib
, then you can attach an autocompletion function to the source
builtin, and have it check whether "${COMP_WORDS[1]}"
(meaning the first argument to source
) equals set_lib
before deciding whether to return any custom matches. (When using the complete
builtin to set up the autocomplete, use the -o bashdefault
flag to tell it that if your function doesn't return any matches then you want Bash to fall back to its default logic for suggestions.)
CodePudding user response:
Usually you need to invoke compgen
for custom completion spec. See the following example:
_comp_set_lib()
{
local cur=$2
local versions=(v1 ver2 version3)
if [[ ${COMP_WORDS[1]} == set_lib ]]; then
COMPREPLY=( $( compgen -W "${versions[*]}" -- "$cur" ) )
return
fi
}
complete -o default -o bashdefault -F _comp_set_lib source