Zsh Completion System
Initialization
Enable completion system
# Load and initialize
autoload -Uz compinit
compinit
# With caching (faster startup)
autoload -Uz compinit
if [[ -n ${ZDOTDIR:-$HOME}/.zcompdump(#qN.mh+24) ]]; then
compinit
else
compinit -C # skip security check (faster)
fi
Completion Styles
zstyle configuration
# Menu selection (navigate with arrows)
zstyle ':completion:*' menu select
# Case-insensitive matching
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'
# Partial word completion
zstyle ':completion:*' matcher-list '' \
'm:{a-zA-Z}={A-Za-z}' \
'r:|[._-]=* r:|=*' \
'l:|=* r:|=*'
# Group completions by category
zstyle ':completion:*' group-name ''
zstyle ':completion:*:descriptions' format '%F{green}-- %d --%f'
zstyle ':completion:*:warnings' format '%F{red}-- no matches --%f'
# Colors in completion menu
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
# Use caching
zstyle ':completion:*' use-cache yes
zstyle ':completion:*' cache-path "$HOME/.zsh/cache"
Custom Completions
Writing completion functions
# Simple word list completion
_mycommand() {
local -a options
options=(
'start:Start the service'
'stop:Stop the service'
'restart:Restart the service'
'status:Show status'
)
_describe 'command' options
}
compdef _mycommand mycommand
# File-type restricted completion
zstyle ':completion:*:*:nvim:*' file-patterns \
'*.{lua,py,sh,adoc,md,yml,yaml,json,toml}:source-files:Source Files' \
'*:all-files:All Files'
# SSH host completion from config
zstyle ':completion:*:ssh:*' hosts $(
awk '/^Host / && !/\*/ {print $2}' ~/.ssh/config 2>/dev/null
)
# Kill process completion with menu
zstyle ':completion:*:*:kill:*' menu yes select
zstyle ':completion:*:kill:*' force-list always
zstyle ':completion:*:*:kill:*' command 'ps -u $USER -o pid,%cpu,tty,cputime,cmd'
Completion Debugging
Troubleshooting completions
# Which completion function handles a command
echo ${(k)_comps[git]} # show function name
# Rebuild completion cache
rm -f ~/.zcompdump && compinit
# Trace completion
# Ctrl+x h # show completion context
# Ctrl+x ? # show completion info
# List all completions
print -l ${(k)_comps} | sort # all registered completions
# Add completion directory
fpath=(~/.zsh/completions $fpath)
Key Completions
Built-in completion features
# Tab complete
# Shift-Tab reverse cycle (with menu select)
# Ctrl-x Ctrl-f file completion anywhere
# Ctrl-x Ctrl-a expand alias
# Path completion
cd /u/l/b<Tab> # → /usr/local/bin
# Variable completion
echo $PA<Tab> # → $PATH
# Command option completion
git log --<Tab> # shows all --options
# Process completion
kill <Tab> # shows process list