The Simplest Autojump Implementation for Zsh
This is the simplest autojump implementation for Zsh:
autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
add-zsh-hook chpwd chpwd_recent_dirs
zstyle ':chpwd:*' recent-dirs-default yes
zstyle ':completion:*' recent-dirs-insert always
alias j=cdr
As you can see, all it does is set up “cdr’, which is included with Zsh (see the “zshcontrib” manpage) and alias it to “j”, which is the command that would be installed by autojump.
Now, when you “cd” around, Zsh keeps the history and allows you to return to directories in that history with “j”. It’s integrated into Zsh’s completion system. Which, as we all know, can be made quite friendly and powerful.
The following well-known configuration option, for example, will give you a menu of completion items, for all commands including “j”:
zstyle ':completion:*' menu select
You can also set up completions to match substrings. That means that you can type “j” followed by a substring of the directory you want to go back to, press TAB, and have all directories containing that substring as the completion:
setopt complete_in_word
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|=*' 'l:|=* r:|=*'
Credit where credit is due: these useful lines are taken from oh-my-zsh:
https://github.com/ohmyzsh/ohmyzsh/blob/master/lib/completion.zsh
If you’re using FISH, it provides the “cdh” command, which is its counterpart to autojump and cdr.
There’s long been a cottage industry of CLI tools that keep a history of your cd’ing and let you jump quickly to directories in that history. That includes a number of recent projects in Rust. Nothing wrong with those, but if you’re using Zsh or FISH, then try what’s included first.
(I wrote this because I recently discovered “cdr”, I think it’s great, and I also think it’s not nearly well-known enough).