completion

ZSH Completion #

First Time Setup or Configure #

If you don’t have completions setup yet, or want to change what you currently have, run:

autoload -Uz compinstall && compinstall

This will update your .zshrc with the selections you make.

Configuration #

Some configuration options I like and use.

Allow completion to be selected with arrows or TAB.

zstyle ':completion:*' menu select

Only allow menu selection when there are MIN_NUMBER_OF_OPTIONS to select.

zstyle ':completion:*' menu select=${MIN_NUMBER_OF_OPTIONS:-5}

Load Completions #

Make sure your FPATH is set with all of the directories that contain completions.

# Prepends specified directories to fpath.
fpath=(
    /usr/local/share/zsh/site-functions
    /usr/share/zsh/site-functions
    # get zsh version number. full path should look something like: /usr/share/zsh/5.9/functions 
    /usr/share/zsh/$(zsh --version | awk '{print $2}')/functions
    # alternatively use a wildcard
    /usr/share/zsh/*/functions
    $fpath[@]
)
# Removes any directories that do not exist.
fpath=($^fpath(N-/))

Then run compinit.

# Make sure compinit is loaded and then call it.
autoload -Uz compinit && compinit

Cache Completions #

The completion system for zsh has the ability to cache completions, for functions that take a long to generate them. For example, brew on macOS will cache the list of casks and formulae so that it doesn’t have to fetch this information each time you run the command. To set up caching, we need to tell zsh where to store the cache. Add the following to your .zshrc file.

zstyle ':completion:*' cache-path ~/.cache/zsh/compcache

Bash Completions in ZSH #

It is also possible to run bash completion function with zsh. This is possible with bashcompinit. Add the following to your .zshrc file.

# Make sure bashcompinit is loaded and then call it.
autoload -U +X bashcompinit && bashcompinit

Full Config #

zstyle ':completion:*' menu select

# Prepends specified directories to fpath.
fpath=(
    /usr/local/share/zsh/site-functions
    /usr/share/zsh/site-functions
    /usr/share/zsh/*/functions
    $fpath[@]
)
# Removes any directories that do not exist.
fpath=($^fpath(N-/))

# Make sure compinit is loaded and then call it.
autoload -Uz compinit && compinit