Parent directory

alias-finder.plugin.zsh

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