in ✏️ Articles · terminal tip software

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:

1function cdc() {
2  cd "$HOME/Code/$1"
3}

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.

 1function cdc() {
 2  cd "$HOME/Code/$1"
 3}
 4
 5function _cdc() {
 6  ((CURRENT == 2)) &&
 7  _files -/ -W "$HOME/Code"
 8}
 9
10compdef _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:

 1typeset -A cd_aliases
 2cd_aliases=(
 3  [cdc]="$HOME/Code"
 4  [cdd]="$HOME/Documents"
 5)
 6
 7for k in "${(@k)cd_aliases}"; do
 8  function $k() {
 9    cd "$cd_aliases[$0]/$1"
10  }
11
12  function _$k() {
13    ((CURRENT == 2)) && _files -/ -W $cd_aliases[${0:1}]
14  }
15
16  compdef _$k $k
17done

I hope this can be as useful for you as it was for me!

Picture Henrique Dias
Interactions (0)

Or…