Sub topic 15
Generating shell completions
Shell completion lets users press Tab to finish a flag, a subcommand, or a value. This chapter assumes you have a derived Parser, a Subcommand enum, and at least one ValueEnum, as built in earlier chapters. You also need to be comfortable with Cargo features and standard output.
How clap_complete works
clap_complete is a separate crate. It does not parse arguments. It reads a clap::Command, which is the same description that #[derive(Parser)] builds for you, and writes a completion script for a chosen shell.
Because the script comes from your real definition, it lists the same flags, subcommands, and ValueEnum choices that the parser accepts. If you add a flag, the next script you generate includes it.
Add the dependency
Add clap_complete next to clap. Its major version should match clap's, so use version 4 for both.
[dependencies]
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4"Print a script on request
The program below adds a --completions option. Its type is Option<Shell>. Shell implements ValueEnum, so clap accepts the names bash, elvish, fish, powershell, and zsh and rejects anything else.
use clap::{CommandFactory, Parser};
use clap_complete::{generate, Shell};
#[derive(Parser)]
#[command(name = "mytool", version)]
struct Cli {
/// Print a completion script for this shell and exit
#[arg(long, value_enum)]
completions: Option<Shell>,
}
fn main() {
let cli = Cli::parse();
if let Some(shell) = cli.completions {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
generate(shell, &mut cmd, name, &mut std::io::stdout());
}
}Three details matter here:
Cli::command()comes from theCommandFactorytrait. It returns theCommandthat the derive macro built.generatetakes the shell, a mutable command, the binary name, and a writer. The name is what the shell will match when the user types it, so it must equal the installed executable name.- The script goes to standard output. That lets the user redirect it into a file.
Install the script
Each shell looks for completion files in a different place. These paths are common examples, and your system may differ.
| Shell | Example command |
|---|---|
| bash | `mytool --completions bash > ~/.local/share/bash-completion/completions/mytool` |
| zsh | `mytool --completions zsh > ~/.zfunc/_mytool` |
| fish | `mytool --completions fish > ~/.config/fish/completions/mytool.fish` |
For zsh, the directory must be on fpath before compinit runs. Open a new shell after installing so it picks up the file.
Choosing where to generate
An option on the main command is quick, but it makes --completions appear in your help output. You have two other common choices:
- Make
completionsa subcommand, somytool completions bashworks and the top-level options stay clean. - Generate the files at build time in
build.rs, and ship them with your package.
Either choice uses the same generate call.
What you get from ValueEnum
When an argument uses ValueEnum, such as the Priority enum from the subcommands chapter, the script offers its variants as candidates. Typing --priority h and pressing Tab can complete to high. A free-form String or PathBuf argument gets no value suggestions, apart from file names in shells that provide them.
Exercise
Your tool is installed as mytool, but you call generate(shell, &mut cmd, "app", &mut std::io::stdout()). The script generates without error. Why do completions not work for mytool, and what is the fix?
Show answer
The third argument is the binary name the script registers completions for. With "app", the shell attaches the completions to a command called app, not mytool. Pass the real executable name, for example cmd.get_name().to_string() or the literal "mytool", and regenerate and reinstall the script.
Exercise
Why is a completions subcommand often better than a --completions option when the CLI has a required positional argument?
Show answer
Clap validates required arguments before your main code runs, so mytool --completions bash would fail with a missing-argument error. With a completions subcommand, the positional argument belongs to another subcommand and is not required here, so the script can be generated.