Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you convert this bash completion function to a zsh completion function?

Tags:

bash

zsh

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.

like image 832
Barry Jones Avatar asked Mar 10 '26 09:03

Barry Jones


1 Answers

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.

like image 182
kba Avatar answered Mar 12 '26 01:03

kba