1# Please add "source /path/to/bash-autocomplete.sh" to your .bashrc to use this. 2_clang() 3{ 4 local cur prev words cword arg flags 5 _init_completion -n : || return 6 7 # 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" 25 fi 26 27 # expand ~ to $HOME 28 eval local path=${COMP_WORDS[0]} 29 flags=$( "$path" --autocomplete="$arg" 2>/dev/null ) 30 # 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 37 if [[ "$cur" == '=' ]]; then 38 COMPREPLY=( $( compgen -W "$flags" -- "") ) 39 elif [[ "$flags" == "" || "$arg" == "" ]]; then 40 _filedir 41 else 42 # 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 45 COMPREPLY=( $( compgen -W "$flags" -- "$cur" ) ) 46 fi 47} 48complete -F _clang clang 49