66 lines · bash
1# Please add "source /path/to/bash-autocomplete.sh" to your .bashrc to use this.2 3_clang_filedir()4{5 # _filedir function provided by recent versions of bash-completion package is6 # better than "compgen -f" because the former honors spaces in pathnames while7 # the latter doesn't. So we use compgen only when _filedir is not provided.8 _filedir 2> /dev/null || COMPREPLY=( $( compgen -f ) )9}10 11_clang()12{13 local cur prev words cword arg flags w1 w214 # If latest bash-completion is not supported just initialize COMPREPLY and15 # initialize variables by setting manually.16 _init_completion -n 2> /dev/null17 if [[ "$?" != 0 ]]; then18 COMPREPLY=()19 cword=$COMP_CWORD20 cur="${COMP_WORDS[$cword]}"21 fi22 23 w1="${COMP_WORDS[$cword - 1]}"24 if [[ $cword > 1 ]]; then25 w2="${COMP_WORDS[$cword - 2]}"26 fi27 28 # Pass all the current command-line flags to clang, so that clang can handle29 # these internally.30 # '=' is separated differently by bash, so we have to concat them without ','31 for i in `seq 1 $cword`; do32 if [[ $i == $cword || "${COMP_WORDS[$(($i+1))]}" == '=' ]]; then33 arg="$arg${COMP_WORDS[$i]}"34 else35 arg="$arg${COMP_WORDS[$i]},"36 fi37 done38 39 # expand ~ to $HOME40 eval local path=${COMP_WORDS[0]}41 # Use $'\t' so that bash expands the \t for older versions of sed.42 flags=$( "$path" --autocomplete="$arg" 2>/dev/null | sed -e $'s/\t.*//' )43 # If clang is old that it does not support --autocomplete,44 # fall back to the filename completion.45 if [[ "$?" != 0 ]]; then46 _clang_filedir47 return48 fi49 50 # When clang does not emit any possible autocompletion, or user pushed tab after " ",51 # just autocomplete files.52 if [[ "$flags" == "$(echo -e '\n')" ]]; then53 # If -foo=<tab> and there was no possible values, autocomplete files.54 [[ "$cur" == '=' || "$cur" == -*= ]] && cur=""55 _clang_filedir56 elif [[ "$cur" == '=' ]]; then57 COMPREPLY=( $( compgen -W "$flags" -- "") )58 else59 # Bash automatically appends a space after '=' by default.60 # Disable it so that it works nicely for options in the form of -foo=bar.61 [[ "${flags: -1}" == '=' ]] && compopt -o nospace 2> /dev/null62 COMPREPLY=( $( compgen -W "$flags" -- "$cur" ) )63 fi64}65complete -F _clang clang66