/bash_completion_lib/include/_get_cword

http://github.com/brinkman83/bashrc · #! · 38 lines · 34 code · 4 blank · 0 comment · 0 complexity · 6a0cc336e4d5464ad8915ebb69caa9ff MD5 · raw file

  1. # Get the word to complete
  2. # This is nicer than ${COMP_WORDS[$COMP_CWORD]}, since it handles cases
  3. # where the user is completing in the middle of a word.
  4. # (For example, if the line is "ls foobar",
  5. # and the cursor is here --------> ^
  6. # it will complete just "foo", not "foobar", which is what the user wants.)
  7. #
  8. # Accepts an optional parameter indicating which characters out of
  9. # $COMP_WORDBREAKS should NOT be considered word breaks. This is useful
  10. # for things like scp where we want to return host:path and not only path.
  11. _get_cword()
  12. {
  13. local i
  14. local WORDBREAKS=${COMP_WORDBREAKS}
  15. if [ -n $1 ]; then
  16. for (( i=0; i<${#1}; ++i )); do
  17. local char=${1:$i:1}
  18. WORDBREAKS=${WORDBREAKS//$char/}
  19. done
  20. fi
  21. local cur=${COMP_LINE:0:$COMP_POINT}
  22. local tmp="${cur}"
  23. local word_start=`expr "$tmp" : '.*['"${WORDBREAKS}"']'`
  24. while [ "$word_start" -ge 2 ]; do
  25. local char=${cur:$(( $word_start - 2 )):1}
  26. if [ "$char" != "\\" ]; then
  27. break
  28. fi
  29. tmp=${COMP_LINE:0:$(( $word_start - 2 ))}
  30. word_start=`expr "$tmp" : '.*['"${WORDBREAKS}"']'`
  31. done
  32. cur=${cur:$word_start}
  33. echo $cur
  34. } # _get_cword()