cdr

Recent Directories (cdr) #

ZSH has a builtin tool to record recent directories that you’ve navigated to so that they persist across sessions.

Setup #

Add the following to your .zshrc file.

autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
add-zsh-hook chpwd chpwd_recent_dirs

Commands #

Once cdr is setup, you can run the following commands.

List
cdr -l
to list recent directories
Edit
cdr -e
to list recent directories
Navigate
cdr <index>
navigate to the directory specified by that index.

Configuration #

cdr can be further configured with the zstyles below.

recent-dirs-file #

Decide where to save the file. The default is: ${ZDOTDIR:-$HOME}/.chpwd-recent-dirs.

# Where to save the file.
zstyle ':chpwd:*' recent-dirs-file ${ZDOTDIR:-$HOME}/.chpwd-recent-dirs

This can also be an array, though only the first specified file is written to. This allows us to setup zsh where each zsh session writes to its own recent dirs file, but each session can reference another’s recent dirs.

zstyle ':chpwd:*' recent-dirs-file "${ZDOTDIR:-$HOME}/.chpwd-recent-dirs-${TTY##*/}" +

Keep in mind though, that the above setting will allow list up to a max amount of directories. So if the first file found hits the max, the other files won’t be loaded. This max can be changed with the following style:

recent-dirs-max #

How many directories to record.

zstyle ':chpwd:*' recent-dirs-max 10

recent-dirs-default / recent-dirs-insert #

If using history with zsh, seeing a command like cdr 3 or cdr <some index> probably doesn’t help very much. The following style with make it so that cdr <index> evaluates to cd <some directory>. This way your history is clean and readable.

# fall through to cd
zstyle ':chpwd:*' recent-dirs-default true
zstyle ':chpwd:*' recent-dirs-insert true

Completion #

Enable menu selection for cdr.

# Enable menu selection of `cdr`. Run `cdr` + TAB to enable a menu. Use keyboard to select, or type
# number. See: http://zsh.sourceforge.net/Doc/Release/User-Contributions.html#Recent-Directories
zstyle ':completion:*:*:cdr:*:*' menu selection

Dynamic Naming #

Enable dynamic naming. This allows you to reference a recent directory using ~[<index>] so for example: ~[2] would reference index 2 in the cdr file. Completion after ~[ also works!

add-zsh-hook -Uz zsh_directory_name zsh_directory_name_cdr