12

I have a directory where I put all my projects in, let's say it's ~/projects as an example. I've made a command called s which takes one argument, and moves me into that directory. E.g.: s foo moves me to ~/projects/foo.

What I'd like is to have a completion command of some sorts, which would act like cd so I could do keep hitting tab to go further into the ~/projects/... directories.

Basically, cd with a prefix which is always present.

I've looked into zstyle completion in man zshcompsys, but realized I just don't know enough about it to understand it properly.

4 Answers 4

14

Here's an example from my own .zshrc that I keep as a copy/paste snippet:

# Try using the below template to set up zsh functions that act
# as aliases to cd and allow you to get autocomplete nicely.

project() { cd /path/to/project/$1; }
compctl -W /path/to/project/ -/ project

Just edit the /path/to/project section in both lines above then you are good to go.

2
  • This works great, thank you! A lot simpler than I would have thought.
    – nifty
    Jan 23, 2012 at 9:54
  • For the 'oh-my-zsh` case insensitive completion, make sure to add -M 'm:{a-z}={A-Z}', i.e. compctl -M 'm:{a-z}={A-Z}' -W /path/to/project/ -/ project
    – Adracus
    Jan 3, 2020 at 12:33
3

A different way of achieving a similar effect is to define aliases for directories:

setopt auto_cd
alias -d s=~/projects

Type ~s/ Tab to change to a subdirectory of ~/projects; you can use ~s in a command argument, too.

1

You can add an entry directly to the named directory hash table:

hash -d s="${HOME}/projects"

Now you can simply use ~s to refer to your directory, and you can use Tab-completion in a cd command: cd ~s/Tab

If you have zsh's autocd option set, you can leave out the cd.

0

You can modify CDPATH:

export CDPATH="$CDPATH:$HOME/Repositories:$HOME/Repositories/jc/Projects"

Now you can access all subdirectories within the specified directories from every other directory as if they would be the subdirectories of the current directory:

➜  ~ /tmp
➜  /tmp pwd
/tmp
➜  /tmp MyAwesomeProject 
~/Repositories/jc/Projects/MyAwesomeProject
➜  MyAwesomeProject git:(master) pwd
/Users/rafael/Repositories/jc/Projects/MyAwesomeProject
➜  MyAwesomeProject git:(master)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .