Yuka Takahashi | c8068db | 2017-05-23 18:39:08 +0000 | [diff] [blame] | 1 | # Please add "source /path/to/bash-autocomplete.sh" to your .bashrc to use this. |
| 2 | _clang() |
| 3 | { |
Yuka Takahashi | 79d21c2 | 2017-06-28 15:59:55 +0000 | [diff] [blame] | 4 | local cur prev words cword arg flags |
Yuka Takahashi | c8068db | 2017-05-23 18:39:08 +0000 | [diff] [blame] | 5 | _init_completion -n : || return |
| 6 | |
Yuka Takahashi | ba5d4af | 2017-06-20 16:31:31 +0000 | [diff] [blame] | 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" |
Yuka Takahashi | ba5d4af | 2017-06-20 16:31:31 +0000 | [diff] [blame] | 25 | fi |
| 26 | |
Yuka Takahashi | 558f3dd | 2017-07-01 16:30:02 +0000 | [diff] [blame^] | 27 | # expand ~ to $HOME |
| 28 | eval local path=${COMP_WORDS[0]} |
| 29 | flags=$( "$path" --autocomplete="$arg" 2>/dev/null ) |
Yuka Takahashi | 79d21c2 | 2017-06-28 15:59:55 +0000 | [diff] [blame] | 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 | |
Yuka Takahashi | a4a8780 | 2017-06-26 00:35:36 +0000 | [diff] [blame] | 37 | if [[ "$cur" == '=' ]]; then |
Yuka Takahashi | ba5d4af | 2017-06-20 16:31:31 +0000 | [diff] [blame] | 38 | COMPREPLY=( $( compgen -W "$flags" -- "") ) |
Yuka Takahashi | a4a8780 | 2017-06-26 00:35:36 +0000 | [diff] [blame] | 39 | elif [[ "$flags" == "" || "$arg" == "" ]]; then |
Yuka Takahashi | c8068db | 2017-05-23 18:39:08 +0000 | [diff] [blame] | 40 | _filedir |
| 41 | else |
Yuka Takahashi | a4a8780 | 2017-06-26 00:35:36 +0000 | [diff] [blame] | 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 |
Yuka Takahashi | c8068db | 2017-05-23 18:39:08 +0000 | [diff] [blame] | 45 | COMPREPLY=( $( compgen -W "$flags" -- "$cur" ) ) |
| 46 | fi |
Yuka Takahashi | b036027 | 2017-05-23 18:52:27 +0000 | [diff] [blame] | 47 | } |
Yuka Takahashi | c8068db | 2017-05-23 18:39:08 +0000 | [diff] [blame] | 48 | complete -F _clang clang |