-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathbd.zsh
107 lines (83 loc) · 2.5 KB
/
bd.zsh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# shellcheck shell=bash
bd () {
(($#<1)) && {
printf -- 'usage: %s <name-of-any-parent-directory>\n' "${0}"
printf -- ' %s <number-of-folders>\n' "${0}"
return 1
} >&2
local requestedDestination="${1}"
local -a parents=(${(ps:/:)"${PWD}"})
local numParents
local dest
local i
local parent
# prepend root to the parents array
parents=('/' "${parents[@]}")
# Remove the current directory since it isn't a parent
shift -p parents
# Get the number of parent directories
numParents="$(( ${#parents[@]}))"
# Build dest and 'cd' to it by looping over the parents array in reverse
dest='./'
for i in $(seq "${numParents}" -1 1); do
parent="${parents[${i}]}"
dest+='../'
if [[ "${requestedDestination}" == "${parent}" ]]; then
cd $dest
return $?
fi
done
# If the user provided an integer, go up as many times as asked
dest='./'
if [[ "${requestedDestination}" == <-> ]]; then
if [[ "${requestedDestination}" -gt "${numParents}" ]]; then
printf -- '%s: Error: Can not go up %s times (not enough parent directories)\n' "${0}" "${requestedDestination}"
return 1
fi
for i in {1.."${requestedDestination}"}; do
dest+='../'
done
cd "${dest}"
return $?
fi
# If the above methods fail
printf -- '%s: Error: No parent directory named "%s"\n' "${0}" "${requestedDestination}"
return 1
}
_bd () {
# Get parents (in reverse order)
local localMatcherList
local -a parents=(${(ps:/:)"${PWD}"})
local numParents
local i
local -a parentsReverse
zstyle -s ':completion:*' 'matcher-list' 'localMatcherList'
# prepend root to the parents array
parents=('/' "${parents[@]}")
# Remove the current directory since it isn't a parent
shift -p parents
# Get the number of parent directories
numParents="$(( ${#parents[@]}))"
parentsReverse=()
for i in $(seq "${numParents}" -1 1); do
parentsReverse+=("${parents[${i}]}")
done
local expl
_wanted -V directories expl 'parent directories' \
compadd -M "${localMatcherList}" "$@" -- "${parentsReverse[@]}"
}
compdef _bd bd
() {
local -a colors
local dir_color='1;31' # hard-coded default in zsh/complist
# check for defined zstyle
if zstyle -a ':completion:*' list-colors colors && [[ "$#colors" -ne 0 ]]; then
local zstyle_color="${colors[(r)di=*]#di=}"
if [[ -n "$zstyle_color" ]]; then
dir_color="$zstyle_color"
fi
else
return
fi
zstyle ':completion:*:*:bd:*:directories' list-colors "=*=${dir_color}"
}