alias-finder.plugin.zsh 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. filter="^'{0,1}.{0,$((cmdLen - 1))}="
  34. fi
  35. alias | grep -E "$filter" | grep -E "=$finder"
  36. if [[ $exact == true ]]; then
  37. break # because exact case is only one
  38. elif [[ $longer = true ]]; then
  39. break # because above grep command already found every longer aliases during first cycle
  40. fi
  41. cmd=$(sed -E 's/ {0,}[^ ]*$//' <<< "$cmd") # remove last word
  42. done
  43. }
  44. preexec_alias-finder() {
  45. # TODO: Remove backward compatibility (other than zstyle form)
  46. zstyle -t ':omz:plugins:alias-finder' autoload && alias-finder $1 || if [[ $ZSH_ALIAS_FINDER_AUTOMATIC = true ]]; then
  47. alias-finder $1
  48. fi
  49. }
  50. autoload -U add-zsh-hook
  51. add-zsh-hook preexec preexec_alias-finder