2

I discovered this little navigation trick the other day, which allows me to trigger menu completions by number when I enter 'cd -'

~ cd -
0 -- ~/home
1 -- ~/home/stuff
2 -- ~/downloads
3 -- ~/wallpaper

Shell scripting syntax still reads like a foreign language to me, but to get this functionality my directory stack history is piped into the function below.

DIRSTACKSIZE=9
DIRSTACKFILE=~/.zdirs

if [[ -f $DIRSTACKFILE ]] && [[ $#dirstack -eq 0 ]]; 
   then dirstack=( ${(f)"$(< $DIRSTACKFILE)"} )
   [[ -d $dirstack[1] ]] && cd $dirstack[1] && cd $OLDPWD
fi
  chpwd() {
  print -l $PWD ${(u)dirstack} >$DIRSTACKFILE

}

The magical part is being able to choose from the list by number, but I have come to learn that this is probably because the functionality for navigation by number is baked in to the 'cd -' command. Still, I'd like to use this everywhere.

Any tips writing a wrapper function (or something like that, I guess) for the completion menu that pipes in completions from the menu when it is triggered and displays them in a numbered list where those numbers select the corresponding element?

I've gotten started reading the manual and what not, but everything remains rather opaque. Thanks!

xoihiox
  • 101
  • 6

1 Answers1

1

First off, the code snippet you show has nothing to do with completion. Instead, what it does is to record the directory stack to a file in order to preserve it between zsh sessions. (Personally, I'm not even sure this is a good idea.)

A good place to start investigating zsh completions is the _complete_help ZLE widget. This is bound by default to ^Xh in zsh's viins (vi insert) keyboard map, but is unbound by default in the emacs keymap. If you want to use it in the emacs keymap (the default for many people), you have to bind it:

bindkey -M emacs "^Xh" _complete_help

Now you can type cd - (or cd +) and follow it by CTRL-Xh instead of TAB. You should see the following output:

tags in context :completion::complete:cd::
    directory-stack  (_directory_stack _cd)

(At this point I'll admit we're getting close to the limits of my knowledge of the zsh completion system.)

Now you can see the completer functions for the directory-stack tag in this particular context. The one you're probably interested in is _directory_stack, and you can see the content of that function with:

functions _directory_stack

…which is where those leading numbers are actually generated.

Arguably it's possible to write similar completion functions for other completion contexts, and apply the using zstyle. However, this is non-trivial completion magic, and beyond anything I have attempted

wjv
  • 2,288
  • 1
  • 18
  • 21