-
Notifications
You must be signed in to change notification settings - Fork 65
/
completion.bash
executable file
·58 lines (41 loc) · 1.76 KB
/
completion.bash
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
#!/usr/bin/env bash
# Author: Brian Beffa <brbsix@gmail.com>
# Original source: https://brbsix.github.io/2015/11/29/accessing-tab-completion-programmatically-in-bash/
# License: LGPLv3 (http://www.gnu.org/licenses/lgpl-3.0.txt)
#
get_completions(){
local completion COMP_CWORD COMP_LINE COMP_POINT COMP_WORDS COMPREPLY=()
# load bash-completion if necessary
declare -F _completion_loader &>/dev/null || {
[[ -r "/usr/share/bash-completion/bash_completion" ]] && source "/usr/share/bash-completion/bash_completion"
# macOS via homebrew
[[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && source "/usr/local/etc/profile.d/bash_completion.sh"
# nixos
command -v nix && FILE="$(nix eval --raw '(import <nixpkgs> {}).bash-completion.outPath')/share/bash-completion/bash_completion" \
&& [[ -r $FILE ]] && source $FILE
}
COMP_LINE=$*
COMP_POINT=${#COMP_LINE}
eval set -- "$@"
COMP_WORDS=("$@")
# add '' to COMP_WORDS if the last character of the command line is a space
[[ ${COMP_LINE[@]: -1} = ' ' ]] && COMP_WORDS+=('')
# index of the last word
COMP_CWORD=$(( ${#COMP_WORDS[@]} - 1 ))
# determine completion function
completion=$(complete -p "$1" 2>/dev/null | awk '{print $(NF-1)}')
# run _completion_loader only if necessary
[[ -n $completion ]] || {
# load completion
_completion_loader "$1"
# detect completion
completion=$(complete -p "$1" 2>/dev/null | awk '{print $(NF-1)}')
}
# ensure completion was detected
[[ -n $completion ]] || return 1
# execute completion function
"$completion"
# print completions to stdout
printf '%s\n' "${COMPREPLY[@]}" | LC_ALL=C sort
}
get_completions "$@"