Change to Custom Directory Alias With Completions in Zsh
For quite some time, I've had a helper function on my Zsh config to quickly be able to cd to specific directories. It looked something like this: function cdc() { cd "$HOME/Code/$1" } So simply typing cdc or even cdc hacdias/hacdias.com would work perfectly. But there was a problem: I was seeing myself just typing cdc, pressing enter, and then "cding" to the right directory. This mostly happened because there was no autocomplete with this function. Yesterday I decided to investigate how to enable autocomplete for this function and it's actually pretty straightforward. To do so, you need to implement a definition function. It is standard to call it {name of alias}. Hence, in our case, it would be cdc. function cdc() { cd "$HOME/Code/$1" } function cdc() { ((CURRENT == 2)) && files -/ -W "$HOME/Code" } compdef cdc cdc On the completion definition function cdc we use ((CURRENT == 2)) to make sure we only give definitions for the directory part of the command. files is a builtin for auto completing paths. Now, if you restart your shell, you can just type cdc and then press tab. You'll now see the completion suggestions! Bonus code If you have more than one cd subdirectory alias like me, instead of manually defining the functions and their completions for all aliases, you can create an associative array and a simple for loop: typeset -A cdaliases cdaliases=( [cdc]="$HOME/Code" [cdd]="$HOME/Documents" ) for k in "${(@k)cdaliases}"; do function $k() { cd "$cdaliases[$0]/$1" } function $k() { ((CURRENT == 2)) && files -/ -W $cdaliases[${0:1}] } compdef _$k $k done I hope this can be as useful for you as it was for me!
Discussion in the ATmosphere