In zsh
, the cd
command has a two-argument form: cd OLD NEW
changes to ${PWD/OLD/NEW}
. With the new-style completion system, zsh is capable of completing NEW
: the second argument is completed based on what OLD
can be substituted with to obtain an existing directory. But the first argument is only completed to existing directories.
How can I get zsh to offer completions that are possible values for OLD
, in addition to completing existing directories?
For example, if the current directory is /path/to/foo
and there are also directories /also/to/foo
and /path/to/foo/prime
, then cd p
Tab completes p
to prime
. If I intend to run cd path also
then I'd like zsh to also offer path
as a completion. How?
Using already-typed values of the second argument to limit the possibilities for the first argument would be a plus, but completing the first argument independently would be fine too.
Best Answer
I guess you could add the components of
$PWD
to thecd
completion list, though this appears to require fiddling with_cd
; that is, a customized version of_cd
must appear first in$fpath
.Then up at the top of
~/zcomp/_cd
add a functionand then just before the
_alternative
line add what that returns to the list of alternativesthough this will always add the
pwd
components tocd
completions:with additional logic you could only add the
$PWD
components when there is already a second argument present instead of always.However! This always messes up the
cd
completion and requires that we monkey patch the upstream_cd
completion. Another option would be to create a new name for the function provided by the two-argcd
, perhaps calledcdsub
, and only have the completion ofPWD
components appear for that. Add this to~/.zshrc
And then a gutted
_cd
completion for_cdsub
to be placed somewhere in$fpath
: