3.7 KiB
- Intro
- Getting started
- Utility functions with example code
- gotchas
- Putting it all together
- Other resources
Intro
The official documentation for writing zsh completion functions is difficult to understand, and doesn't give many examples. At the time of writing this document I was able to find two other tutorials on the web, however both of those tutorials only explain a small portion of the capabilities of the completion system. This document aims to give more complete and easy to understand explanation for creating zsh completion functions. I do not go into all the details, but will give enough information and examples to get you up and running. If you need more details you can look it up for yourself in the official documentation.
Please make any scripts that you create publically available for others (e.g. by forking this repo and making a pull request).
Getting started
Telling zsh which function to use for completing a command
Completion functions for commands are stored in files with names beginning with an underscore _, and these files should be placed in a directory listed in the $fpath variable. You can add a directory to $fpath by adding a line like this to your ~/.zshrc file:
fpath=(~/newdir $fpath)
The first line of a completion function file can look something like this:
#compdef foobar
This tells zsh that the file contains code for completing the foobar command. This is the format that you will use most often for the first line, but you can also use the same file for completing several different functions if you want. See here for more details.
You can also use the compdef command directly (e.g. in your ~/.zshrc file) to tell zsh which function to use for completing a command like this:
> compdef _function foobar
or if you want to supply arguments:
> compdef '_function arg1 arg2' foobar
See here for more details.
Completing generic gnu commands
Many gnu commands have a standardized way of listing option descriptions (when the –help option is used). For these commands you can use the _gnu_generic function for automatically creating completions, like this:
> compdef _gnu_generic foobar
Copying completions from another command
If you want a command, say cmd1, to have the same completions as another, say cmd2, you can do this:
> compdef cmd1=cmd2
This can be useful for example if you have created an alias for a command to help you remember it.
Writing your own completion functions
A good way to get started is to look at some already defined completion functions. On my linux installation these are found in /usr/share/zsh/functions/Completion/Unix and /usr/share/zsh/functions/Completion/Linux and a few other subdirs.
You will notice that the _arguments function is used a lot. This is a utility function that makes it easy to write simple completion functions.