bash-autocomplete.sh 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Please add "source /path/to/bash-autocomplete.sh" to your .bashrc to use this.
  2. _clang_filedir()
  3. {
  4. # _filedir function provided by recent versions of bash-completion package is
  5. # better than "compgen -f" because the former honors spaces in pathnames while
  6. # the latter doesn't. So we use compgen only when _filedir is not provided.
  7. _filedir 2> /dev/null || COMPREPLY=( $( compgen -f ) )
  8. }
  9. _clang()
  10. {
  11. local cur prev words cword arg flags w1 w2
  12. # If latest bash-completion is not supported just initialize COMPREPLY and
  13. # initialize variables by setting manually.
  14. _init_completion -n 2> /dev/null
  15. if [[ "$?" != 0 ]]; then
  16. COMPREPLY=()
  17. cword=$COMP_CWORD
  18. cur="${COMP_WORDS[$cword]}"
  19. fi
  20. w1="${COMP_WORDS[$cword - 1]}"
  21. if [[ $cword > 1 ]]; then
  22. w2="${COMP_WORDS[$cword - 2]}"
  23. fi
  24. # Pass all the current command-line flags to clang, so that clang can handle
  25. # these internally.
  26. # '=' is separated differently by bash, so we have to concat them without ','
  27. for i in `seq 1 $cword`; do
  28. if [[ $i == $cword || "${COMP_WORDS[$(($i+1))]}" == '=' ]]; then
  29. arg="$arg${COMP_WORDS[$i]}"
  30. else
  31. arg="$arg${COMP_WORDS[$i]},"
  32. fi
  33. done
  34. # expand ~ to $HOME
  35. eval local path=${COMP_WORDS[0]}
  36. # Use $'\t' so that bash expands the \t for older versions of sed.
  37. flags=$( "$path" --autocomplete="$arg" 2>/dev/null | sed -e $'s/\t.*//' )
  38. # If clang is old that it does not support --autocomplete,
  39. # fall back to the filename completion.
  40. if [[ "$?" != 0 ]]; then
  41. _clang_filedir
  42. return
  43. fi
  44. # When clang does not emit any possible autocompletion, or user pushed tab after " ",
  45. # just autocomplete files.
  46. if [[ "$flags" == "$(echo -e '\n')" ]]; then
  47. # If -foo=<tab> and there was no possible values, autocomplete files.
  48. [[ "$cur" == '=' || "$cur" == -*= ]] && cur=""
  49. _clang_filedir
  50. elif [[ "$cur" == '=' ]]; then
  51. COMPREPLY=( $( compgen -W "$flags" -- "") )
  52. else
  53. # Bash automatically appends a space after '=' by default.
  54. # Disable it so that it works nicely for options in the form of -foo=bar.
  55. [[ "${flags: -1}" == '=' ]] && compopt -o nospace 2> /dev/null
  56. COMPREPLY=( $( compgen -W "$flags" -- "$cur" ) )
  57. fi
  58. }
  59. complete -F _clang clang