Reputation: 1430
How can you convert this bash completion function to a zsh completion function?
This bash function allows you to tab-complete the names of directories above your current working directory so you can more quickly and accurately navigate up the file hierarchy.
Example:
$ pwd
/Users/me/Animals/Mammals/Ungulates/Goats/Ibex
$ upto Animals
$ pwd
/Users/me/Animals
Code:
function upto {
if [[ -z $1 ]]; then
return
fi
local upto=$1
cd "${PWD/\/$upto\/*//$upto}"
}
_upto()
{
local cur=${COMP_WORDS[COMP_CWORD]}
local d=${PWD//\//\ }
COMPREPLY=( $( compgen -W "$d" -- "$cur" ) )
}
complete -F _upto upto
I'd like to have a similar one in zsh, but I don't fully understand the mechanics of how this one works, much less how to modify it for zsh.
Upvotes: 3
Views: 471
Reputation: 1177
Try this completion function
_upto() {
local parents;
parents=(${(s:/:)PWD});
compadd -V 'Parent Dirs' -- "${(Oa)parents[@]}";
}
Enable it with compdef _upto upto
.
Test it by creating a deply nested folder: f=/tmp/foo/bar/one/two/three;mkdir -p $f;cd $f
. Typing upto <Tab>
should give
three two one bar foo tmp
To reverse the directories (i.e. start proposals at root rather at ..
), remove the (Oa)
flag from the compadd
line.
Upvotes: 2