blob: 4f9853accc8858004d3ec793b372dc5cd451b7a4 [file] [log] [blame]
Yuka Takahashic8068db2017-05-23 18:39:08 +00001# Please add "source /path/to/bash-autocomplete.sh" to your .bashrc to use this.
2_clang()
3{
Yuka Takahashi79d21c22017-06-28 15:59:55 +00004 local cur prev words cword arg flags
Yuka Takahashic8068db2017-05-23 18:39:08 +00005 _init_completion -n : || return
6
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00007 # bash always separates '=' as a token even if there's no space before/after '='.
8 # On the other hand, '=' is just a regular character for clang options that
9 # contain '='. For example, "-stdlib=" is defined as is, instead of "-stdlib" and "=".
10 # So, we need to partially undo bash tokenization here for integrity.
11 local w1="${COMP_WORDS[$cword - 1]}"
12 local w2="${COMP_WORDS[$cword - 2]}"
13 if [[ "$cur" == -* ]]; then
14 # -foo<tab>
15 arg="$cur"
16 elif [[ "$w1" == -* && "$cur" == '=' ]]; then
17 # -foo=<tab>
18 arg="$w1=,"
19 elif [[ "$w1" == -* ]]; then
20 # -foo <tab> or -foo bar<tab>
21 arg="$w1,$cur"
22 elif [[ "$w2" == -* && "$w1" == '=' ]]; then
23 # -foo=bar<tab>
24 arg="$w2=,$cur"
Yuka Takahashiba5d4af2017-06-20 16:31:31 +000025 fi
26
Yuka Takahashi558f3dd2017-07-01 16:30:02 +000027 # expand ~ to $HOME
28 eval local path=${COMP_WORDS[0]}
29 flags=$( "$path" --autocomplete="$arg" 2>/dev/null )
Yuka Takahashi79d21c22017-06-28 15:59:55 +000030 # If clang is old that it does not support --autocomplete,
31 # fall back to the filename completion.
32 if [[ "$?" != 0 ]]; then
33 _filedir
34 return
35 fi
36
Yuka Takahashia4a87802017-06-26 00:35:36 +000037 if [[ "$cur" == '=' ]]; then
Yuka Takahashiba5d4af2017-06-20 16:31:31 +000038 COMPREPLY=( $( compgen -W "$flags" -- "") )
Yuka Takahashia4a87802017-06-26 00:35:36 +000039 elif [[ "$flags" == "" || "$arg" == "" ]]; then
Yuka Takahashic8068db2017-05-23 18:39:08 +000040 _filedir
41 else
Yuka Takahashia4a87802017-06-26 00:35:36 +000042 # Bash automatically appends a space after '=' by default.
43 # Disable it so that it works nicely for options in the form of -foo=bar.
44 [[ "${flags: -1}" == '=' ]] && compopt -o nospace
Yuka Takahashic8068db2017-05-23 18:39:08 +000045 COMPREPLY=( $( compgen -W "$flags" -- "$cur" ) )
46 fi
Yuka Takahashib0360272017-05-23 18:52:27 +000047}
Yuka Takahashic8068db2017-05-23 18:39:08 +000048complete -F _clang clang