alias-finder.plugin.zsh 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. alias-finder() {
  2. local cmd=" " exact="" longer="" cheaper="" wordEnd="'{0,1}$" finder="" filter=""
  3. # build command and options
  4. for c in "$@"; do
  5. case $c in
  6. # TODO: Remove backward compatibility (other than zstyle form)
  7. # set options if exist
  8. -e|--exact) exact=true;;
  9. -l|--longer) longer=true;;
  10. -c|--cheaper) cheaper=true;;
  11. # concatenate cmd
  12. *) cmd="$cmd$c " ;;
  13. esac
  14. done
  15. zstyle -t ':omz:plugins:alias-finder' longer && longer=true
  16. zstyle -t ':omz:plugins:alias-finder' exact && exact=true
  17. zstyle -t ':omz:plugins:alias-finder' cheaper && cheaper=true
  18. # format cmd for grep
  19. ## - replace newlines with spaces
  20. ## - trim both ends
  21. ## - replace multiple spaces with one space
  22. ## - add escaping character to special characters
  23. cmd=$(echo -n "$cmd" | tr '\n' ' ' | xargs | tr -s '[:space:]' | sed 's/[].\|$(){}?+*^[]/\\&/g')
  24. if [[ $longer == true ]]; then
  25. wordEnd="" # remove wordEnd to find longer aliases
  26. fi
  27. # find with alias and grep, removing last word each time until no more words
  28. while [[ $cmd != "" ]]; do
  29. finder="'{0,1}$cmd$wordEnd"
  30. # make filter to find only shorter results than current cmd
  31. if [[ $cheaper == true ]]; then
  32. cmdLen=$(echo -n "$cmd" | wc -c)
  33. if [[ $cmdLen -le 1 ]]; then
  34. return
  35. fi
  36. filter="^'?.{1,$((cmdLen - 1))}'?=" # some aliases is surrounded by single quotes
  37. fi
  38. alias | grep -E "$filter" | grep -E "=$finder"
  39. if [[ $exact == true ]]; then
  40. break # because exact case is only one
  41. elif [[ $longer = true ]]; then
  42. break # because above grep command already found every longer aliases during first cycle
  43. fi
  44. cmd=$(sed -E 's/ {0,}[^ ]*$//' <<< "$cmd") # remove last word
  45. done
  46. }
  47. preexec_alias-finder() {
  48. # TODO: Remove backward compatibility (other than zstyle form)
  49. zstyle -t ':omz:plugins:alias-finder' autoload && alias-finder $1 || if [[ $ZSH_ALIAS_FINDER_AUTOMATIC = true ]]; then
  50. alias-finder $1
  51. fi
  52. }
  53. autoload -U add-zsh-hook
  54. add-zsh-hook preexec preexec_alias-finder