In zsh, is there a way to navigate through the history of directories that I have visited (those listed in dirs) when I am typing a command in the command line?

For example, say that I start typing cp -r in the terminal, I would like to then use M-n or M-p until I find a directory, from the list of directories that I have visited, that I want to follow cp -r in the command that I am typing. Eventually I would find /some/path/ for the cp source directory, and then type <SPC> and repeat the process to find /some/other/path for the destination directory for my cp command.

In case it helps, the code below helps me navigate my command history from the command line using C-n and C-p, which allows me to autocomplete my command with other commands that I previously typed.

up-line-or-history-beginning-search () {
  if [[ -n $PREBUFFER ]]; then
    zle up-line-or-history
    zle history-beginning-search-backward
down-line-or-history-beginning-search () {
  if [[ -n $PREBUFFER ]]; then
    zle down-line-or-history
    zle history-beginning-search-forward

zle -N up-line-or-history-beginning-search
zle -N down-line-or-history-beginning-search

bindkey '^P' up-line-or-history-beginning-search
bindkey '^N' down-line-or-history-beginning-search
  • cd -<TAB> if you have pushd enabled? – Ulrich Dangel Mar 1 '13 at 22:31
  • @UlrichDangel That is very close to what I want! There are two differences: 1) I think it only shows directories within my current session and 2) It doesn't let me iterate pass the last item in the list. Is there any alternative? – Amelio Vazquez-Reina Mar 1 '13 at 22:59
  • no, but you can increase the stacksize – Ulrich Dangel Mar 2 '13 at 8:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.