Directory bookmarks with Zsh

Vincent Bernat

Sev­eral projects im­ple­ment di­rec­tory book­marks for your fa­vorite shell. But they all share a lim­i­ta­tion: they only en­hance the cd com­mand. You can­not use a book­mark in an ar­bi­trary command.

Up­date (2015-02)

My ini­tial im­ple­men­ta­tion with Zsh used dy­namic named di­rec­to­ries. Peo­ple on Twit­ter pointed out a sim­pler ap­proach. The ar­ti­cle has been up­dated to re­flect that. As a side note, you can also use shell variables.1

Static named directories#

Zsh comes with a lesser-known fea­ture called static named di­rec­to­ries. You de­clare them with the hash builtin and re­fer to them by prepending ~:

$ hash -d -- -lldpd=/home/bernat/code/deezer/lldpd
$ echo ~-lldpd/README.md
/home/bernat/code/deezer/lldpd/README.md
$ head -n1 ~-lldpd/README.md
lldpd: implementation of IEEE 802.1ab (LLDP)

Be­cause ~-lldpd is sub­sti­tuted dur­ing file­name ex­pan­sion, you can use it in any com­mand like a reg­u­lar di­rec­tory, as shown above. The - pre­fix avoids col­li­sions with home di­rectories.

Book­marks live in a ded­i­cated di­rec­tory, $MARKPATH. Each book­mark is a sym­bolic link to the tar­get di­rec­tory: for ex­am­ple, ~-lldpd ex­pands to $MARKPATH/​lldpd, which points to the ap­pro­pri­ate di­rec­tory. As­sum­ing you have pop­u­lated $MARKPATH with some links, here is how to reg­is­ter bookmarks:

for link ($MARKPATH/*(N@)) {
    hash -d -- -${link:t}=${link:A}
}

You also get com­ple­tion and prompt ex­pan­sion for free:

$ pwd
/home/bernat/code/deezer/lldpd/src/lib
$ echo ${(%):-%~}
~-lldpd/src/lib

The last step is to man­age book­marks with­out man­u­ally adding or re­mov­ing sym­bolic links. The fol­low­ing bookmark() func­tion dis­plays ex­ist­ing book­marks when called with­out ar­gu­ments, re­moves a book­mark when called with -d, or adds the cur­rent di­rec­tory as a book­mark otherwise.

bookmark() {
    if (( $# == 0 )); then
        # When no arguments are provided, just display existing
        # bookmarks
        for link in $MARKPATH/*(N@); do
            local markname="$fg[green]${link:t}$reset_color"
            local markpath="$fg[blue]${link:A}$reset_color"
            printf "%-30s -> %s\n" $markname $markpath
        done
    else
        # Otherwise, we may want to add a bookmark or delete an
        # existing one.
        local -a delete
        zparseopts -D d=delete
        if (( $+delete[1] )); then
            # With `-d`, we delete an existing bookmark
            command rm $MARKPATH/$1
        else
            # Otherwise, add a bookmark to the current
            # directory. The first argument is the bookmark
            # name. `.` is special and means the bookmark should
            # be named after the current directory.
            local name=$1
            [ $name == "." ] && name=${PWD:t}
            ln -s $PWD $MARKPATH/$name
        fi
    fi
}

Find the com­plete ver­sion on GitHub.

Dynamic named directories#

An­other, more com­plex, way to achieve the same re­sult is dy­namic named di­rec­to­ries. I ini­tially used this so­lu­tion but it is far more com­plex. This sec­tion ex­ists for his­tor­i­cal rea­sons only. You can find the com­plete im­ple­men­ta­tion in my Git repository.

Dur­ing file­name ex­pan­sion, Zsh passes a ~ fol­lowed by a string in square brack­ets to the zsh_​directory_​name() func­tion, which replies with a di­rec­tory name. This fea­ture can im­ple­ment di­rec­tory bookmarks:

$ cd ~[@lldpd]
$ pwd
/home/bernat/code/deezer/lldpd
$ echo ~[@lldpd]/README.md
/home/bernat/code/deezer/lldpd/README.md
$ head -n1 ~[@lldpd]/README.md
lldpd: implementation of IEEE 802.1ab (LLDP)

Like static named di­rec­to­ries, be­cause ~[@lldpd] is sub­sti­tuted dur­ing file­name ex­pan­sion, you can use it in any com­mand like a reg­u­lar di­rectory.

Basic implementation#

Book­marks still live in a ded­i­cated di­rec­tory, $MARKPATH, as sym­bolic links. Here is the core im­ple­mentation:

_bookmark_directory_name() {
    emulate -L zsh # ❶
    setopt extendedglob
    case $1 in
        n)
            [​[ $2 != (​#b)"@"(?*) ]] && return 1 # ❷
            typeset -ga reply
            reply=(${${:-$MARKPATH/$match[1]}:A}) # ❸
            return 0
            ;;
        *)
            return 1
            ;;
    esac
    return 0
}

add-zsh-hook zsh_directory_name _bookmark_directory_name

zsh_​directory_​name() ac­cepts hooks:2 in­stead of defin­ing it di­rectly, we de­fine an­other func­tion and reg­is­ter it as a hook with add-zsh-hook.

The hook han­dles dif­fer­ent sit­u­a­tions. The first is trans­form­ing a dy­namic name into a reg­u­lar di­rec­tory name. In this case, the first pa­ram­e­ter is n and the sec­ond is the dy­namic name.

In ❶, emulate re­stores the pris­tine be­hav­ior of Zsh and en­sures that op­tions set within the func­tion do not leak out­side. The func­tion can then be reused safely in an­other en­vi­ronment.

In ❷, we check that the dy­namic name starts with @ fol­lowed by at least one char­ac­ter. Oth­er­wise, we de­clare we don’t know how to han­dle it and an­other hook gets a chance to act. (#b) is a glob­bing flag that ac­ti­vates back­ref­er­ences for paren­the­sized groups. When a match is found, it is stored in the $match array.

In ❸, we build the re­ply. We could have re­turned $MARKPATH/$match[1], but to hide the sym­bolic link mech­a­nism, we use the A mod­i­fier to re­solve sym­bolic links. Zsh al­lows nested sub­sti­tu­tions, so you can ap­ply mod­i­fiers and flags on any­thing. ${:-$MARKPATH/$match[1]} is a com­mon trick to turn $MARKPATH/$match[1] into a pa­ram­e­ter sub­sti­tu­tion and ap­ply the A mod­i­fier on it.

Completion#

Zsh can also com­plete dy­namic di­rec­tory names. The com­ple­tion sys­tem calls the hook func­tion with c as the first argument.

_bookmark_directory_name() {
    # […]
    case $1 in
        c)
            # Completion
            local expl
            local -a dirs
            dirs=($MARKPATH/*(N@:t)) # ❶
            dirs=("@"${^dirs}) # ❷
            _wanted dynamic-dirs expl 'bookmarked directory' compadd -S\] -a dirs
            return
            ;;
        # […]
    esac
    # […]
}

First, in ❶, we build a list of pos­si­ble book­marks. In *(N@:t), N@ is a glob qual­i­fier: N re­turns noth­ing if there is no match (in­stead of an er­ror) while @ only re­turns sym­bolic links. t is a mod­i­fier that re­moves all lead­ing path­name com­po­nents. This is equiv­a­lent to basename or ${something##*/} in POSIX shells but plays nicely with glob ex­pressions.

In ❷, we just add @ be­fore each book­mark name. If we have b1, b2 and b3 as book­marks, ${^dirs} ex­pands to {b1,b2,b3} and there­fore "@"${^dirs} ex­pands to the (@b1 @b2 @b3) array.

The re­sult then feeds into the com­ple­tion system.

Prompt expansion#

Many peo­ple dis­play the cur­rent di­rec­tory name in their prompt. It would be nice to show the book­mark name in­stead of the full path when in­side a book­marked di­rec­tory. That’s also possible!

$ pwd
/home/bernat/code/deezer/lldpd/src/lib
$ echo ${(%):-%~}
~[@lldpd]/src/lib

The prompt ex­pan­sion sys­tem calls the hook func­tion with d as the first ar­gu­ment and the file­name to transform.

_bookmark_directory_name() {
    # […]
    case $1 in
        d)
            local link slink
            local -A links
            for link ($MARKPATH/*(N@)) {
                links[${​#link:A}$'\0'${link:A}]=${link:t} # ❶
            }
            for slink (${(@On)${(k)links}}) {
                link=${slink#*$'\0'} # ❷
                if [​[ $2 = (​#b)(${link})(|/*) ]]; then
                    typeset -ga reply
                    reply=("@"${links[$slink]} $(( ${​#match[1]} )) )
                    return 0
                fi
            }
            return 1
            ;;
        # […]
    esac
    # […]
}

Okay. This is black Zsh wiz­ardry. Feel free to skip the ex­pla­na­tion. It is com­plex be­cause we want to sub­sti­tute the most spe­cific book­mark, hence the need to sort book­marks by tar­get path length.

In ❶, we build the as­so­cia­tive ar­ray $links by it­er­at­ing over each sym­bolic link ($link) in $MARKPATH. The goal is to map a tar­get di­rec­tory to its book­mark name. But we need to it­er­ate from the long­est to the short­est key. To achieve that, we prepend each key with its length.

Re­mem­ber, ${link:A} is the ab­so­lute path with sym­bolic links re­solved. ${​#link:A} is the length of this path. We con­cate­nate the length with the di­rec­tory name, us­ing $'\0' as a sep­a­ra­tor be­cause it is the only safe char­ac­ter for this pur­pose. The re­sult maps to the book­mark name.

The sec­ond loop it­er­ates over the keys of $links (us­ing the k pa­ram­e­ter flag in ${(k)links}). These keys are turned into an ar­ray (@ pa­ram­e­ter flag) and sorted nu­mer­i­cally in de­scend­ing or­der (On pa­ram­e­ter flag). Since the keys are di­rec­tory names pre­fixed by their lengths, the first match is the longest one.

In ❷, we ex­tract the di­rec­tory name from the key by strip­ping the length and null char­ac­ter pre­fix. Then, we check if the ex­tracted di­rec­tory name matches the pro­vided file­name. Again, (#b) ac­ti­vates back­ref­er­ences. With ex­tended glob­bing, we can use the “or” op­erator, |.

When the file­name matches the di­rec­tory name ex­actly or is some­where deeper, we build the re­ply: an ar­ray whose first el­e­ment is the book­mark name and the sec­ond is the un­trans­lated part of the filename.

Easy typing#

Typ­ing ~[@ is cum­ber­some. For­tu­nately, the Zsh line ed­i­tor sup­ports cus­tom bind­ings. The fol­low­ing snip­pet sub­sti­tutes @@ (if typed with­out a pause) with ~[@:

vbe-insert-bookmark() {
    emulate -L zsh
    LBUFFER=${LBUFFER}"~[@"
}
zle -N vbe-insert-bookmark
bindkey '@@' vbe-insert-bookmark

Com­bined with the autocd op­tion and com­ple­tion, jump­ing to a book­marked di­rec­tory be­comes ef­fortless.