Created
August 3, 2021 21:52
-
-
Save philpennock/59f13306af8becea958824bd9e65f85f to your computer and use it in GitHub Desktop.
Be able to declare certain prefices to refer to certain sub-dir owning areas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# There's a great example in zshexpn(1) "Dynamic named directories" about | |
# shortening a path to be named by the perforce area it's in; I usually want | |
# this for git repos, and a whole bunch of them. In fact, it's a common | |
# pattern and one I don't want to repeat. | |
local label="${1:?need a label for this completion set}" | |
local short="${2:?need a short prefix for this completion set}" | |
local based="${3:?need a directory for this completion set}" | |
local elide_prefix="${4:-}" | |
local flags="${5:-}" | |
emulate -L zsh | |
setopt extended_glob | |
if [[ ! -d $based ]]; then | |
print -u2 "$0: no such directory ${(q)based}" | |
return 1 | |
fi | |
local opt | |
local want_resolve=0 # should resolve symlinks, so we can have aggregation dirs | |
while getopts ':r' opt "${(@Q)${(z)flags}}"; do | |
case $opt in | |
r) want_resolve=1 ;; | |
:) die "missing required option for -$OPTARG" ;; | |
\?) die "unknown option -$OPTARG" ;; | |
*) die "unhandled option -$arg; CODE BUG" ;; | |
esac | |
done | |
local funcname="zsh_directory_name_pds_$short" | |
eval "function $funcname { | |
emulate -L zsh | |
setopt extended_glob | |
local -a match mbegin mend | |
case \$1 in | |
d) # collapsing for prompt shortening | |
if [[ \$2 == (#b)($based/)(${elide_prefix}|)([^/]##)* ]]; then | |
typeset -ga reply | |
reply=(${short}:\$match[3] \$(( \${#match[1]} + \${#match[2]} + \${#match[3]} )) ) | |
return 0 | |
fi | |
return 1 | |
;; | |
n) # expand name out to dir | |
[[ \$2 == (#b)${short}:(?*) ]] || return 1 | |
local prefix short | |
typeset -ga reply | |
for prefix in '' '${elide_prefix}'; do | |
short=\"$based/\${prefix}\$match[1]\" | |
if [[ -d \"\$short\" ]]; then | |
if (( $want_resolve )); then short=\"\${short:A}\"; fi | |
reply=( \"\$short\" ) | |
return 0 | |
fi | |
done | |
return 1 | |
;; | |
c) # completion | |
local expl | |
local -a dirs | |
dirs=($based/*(-/:t)) | |
if [[ -n '${elide_prefix}' ]]; then | |
dirs=(\${dirs#${elide_prefix}}) | |
fi | |
dirs=(${short}:\${^dirs}) | |
_wanted dynamic-dirs expl 'Dynamic/$short repo' compadd -S\] -a dirs | |
;; | |
*) | |
return 1 | |
;; | |
esac | |
return 0 | |
}" | |
zsh_directory_name_functions+=( $funcname ) |
Author
philpennock
commented
Aug 3, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment