11

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.

gparyani
  • 1,845
  • 9
  • 30
  • 48
nifty
  • 345
  • 1
  • 4
  • 10

4 Answers4

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.

Matthew Scharley
  • 4,463
  • 3
  • 26
  • 21
  • This works great, thank you! A lot simpler than I would have thought. – nifty Jan 23 '12 at 09: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 03 '20 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.

Gilles 'SO- stop being evil'
  • 69,786
  • 21
  • 137
  • 178
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.

wjv
  • 1,081
  • 10
  • 14
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)