Sub topic 15
Generating shell completions
Shell completions let users press Tab to finish subcommand names, long options, and enumerated values. This chapter shows how to produce completion scripts from the same definition your parser already uses.
This chapter assumes you have read the earlier chapters on #[derive(Parser)], Subcommand, and ValueEnum. You should also be comfortable editing Cargo.toml and running cargo build.
How clap_complete works
The clap crate does not generate completions. A separate crate, clap_complete, does. It reads a clap::Command, which is the structure that #[derive(Parser)] builds for you, and writes a script in the syntax of a chosen shell.
Because the script comes from the Command, it cannot drift away from the real options. If you add a --format option and rebuild, the next generated script includes it.
Adding the dependency
Add clap_complete next to clap. Its major version tracks clap's, so use 4 for both.
[dependencies]
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4"Generating a script at run time
The simplest approach is to ship a command that prints the script. Users run it once and save the output where their shell looks for completions.
A top-level --completions option is awkward for tools that have required arguments or subcommands. Clap would complain that those are missing before your code ever sees the flag. A completions subcommand avoids that problem.
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{generate, Shell};
use std::io;
#[derive(Parser)]
#[command(name = "mytool", version, about = "A tiny task manager")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Add a task
Add { title: String },
/// Print a shell completion script to standard output
Completions {
/// Shell to generate the script for
#[arg(value_enum)]
shell: Shell,
},
}
fn main() {
let cli = Cli::parse();
match cli.command {
Commands::Add { title } => println!("add {title:?}"),
Commands::Completions { shell } => {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
generate(shell, &mut cmd, name, &mut io::stdout());
}
}
}Three pieces make this work:
Shellis an enum fromclap_completethat already implementsValueEnum. Declaring the field with#[arg(value_enum)]gives youbash,elvish,fish,powershell, andzshas the accepted values, and clap lists them in--help.Cli::command()comes from theCommandFactorytrait, which#[derive(Parser)]implements for you. You must import the trait to call the method.generatetakes the shell, a mutableCommand, the program name to embed in the script, and anyio::Writetarget. Passingio::stdout()lets the user redirect the output.
Reading the name from cmd.get_name() keeps it in sync with the #[command(name = ...)] attribute. If you hard-code a second copy of the name, the two can disagree.
Installing the script
Each shell looks in a different place. The commands below assume the binary is named mytool and is on your PATH.
| Shell | Command | Column | Column |
|---|---|---|---|
| Bash | `mytool completions bash > ~/.local/share/bash-completion/completions/mytool` | ||
| Zsh | `mytool completions zsh > ~/.zfunc/_mytool` (the directory must be in `fpath` before `compinit` runs) | ||
| Fish | `mytool completions fish > ~/.config/fish/completions/mytool.fish` | ||
| PowerShell | Add `mytool completions powershell \ | Out-String \ | Invoke-Expression` to your profile |
| Elvish | Save the output to a file and `use` it from `rc.elv` |
For a quick test in Bash, you can load the script into the current session without saving it:
source <(mytool completions bash)
mytool <TAB>Open a new shell after installing a file. Most shells read completion files only at startup.
Improving what gets completed
By default, clap_complete knows the names of subcommands and options. It can also complete the values of ValueEnum arguments, since the allowed values are part of the definition. For other values, you can tell it what kind of thing to suggest with a ValueHint.
use clap::{Parser, ValueHint};
use std::path::PathBuf;
#[derive(Parser)]
struct Cli {
/// Input file
#[arg(value_hint = ValueHint::FilePath)]
input: PathBuf,
/// Directory to write results to
#[arg(long, value_hint = ValueHint::DirPath)]
out_dir: Option<PathBuf>,
/// Command to run after processing
#[arg(long, value_hint = ValueHint::CommandName)]
then: Option<String>,
}
fn main() {
let cli = Cli::parse();
println!("{:?} {:?} {:?}", cli.input, cli.out_dir, cli.then);
}Common hints include FilePath, DirPath, CommandName, Hostname, Username, and Url. How well a hint works depends on the shell. Zsh and Fish use most of them. Bash support is more limited.
A hint only affects the generated script. It does not validate anything at parse time.
Generating scripts at build time
Some projects ship completion files in release archives or system packages. A build.rs script can write them during cargo build, so nobody has to run the binary first.
Build scripts compile before your crate. They cannot use types from src/main.rs. The usual workaround is to put the CLI definition in its own file and pull it into both places with include!.
[dependencies]
clap = { version = "4", features = ["derive"] }
[build-dependencies]
clap = { version = "4", features = ["derive"] }
clap_complete = "4"// src/cli.rs
use clap::Parser;
#[derive(Parser)]
#[command(name = "mytool", version)]
pub struct Cli {
/// Output format
#[arg(long, default_value = "text")]
pub format: String,
}// build.rs
use clap::CommandFactory;
use clap_complete::{generate_to, Shell};
use std::env;
use std::io::Error;
include!("src/cli.rs");
fn main() -> Result<(), Error> {
let Some(outdir) = env::var_os("OUT_DIR") else {
return Ok(());
};
let mut cmd = Cli::command();
for shell in [Shell::Bash, Shell::Zsh, Shell::Fish] {
let path = generate_to(shell, &mut cmd, "mytool", &outdir)?;
println!("cargo:warning=wrote {}", path.display());
}
println!("cargo:rerun-if-changed=src/cli.rs");
Ok(())
}main.rs would then declare mod cli; and use cli::Cli. generate_to writes one file per call and returns its path. The files land under target/, in a hashed OUT_DIR directory, so your release process must copy them out.
The include! approach has limits:
src/cli.rscannot refer to other modules withcrate::paths, because in the build scriptcrateis the build script itself.- Any type the CLI uses, such as a custom
ValueEnum, has to live in that file or in another file you alsoinclude!. - Everything the CLI file depends on is compiled twice, which slows builds slightly.
Choose between the two approaches by who runs the script:
| Approach | Best when | Cost |
|---|---|---|
| `completions` subcommand | Users install with `cargo install` and set up their own shell | Adds a subcommand to your public interface |
| `build.rs` | You package releases and can install the files for users | Constrains how you split modules |
Limits of static scripts
The scripts above are static. They list the options known when the tool was built. They cannot suggest values that exist only at run time, such as the names of tasks in a database.
Clap offers an experimental dynamic mode behind the unstable-dynamic feature of clap_complete. In it, the shell calls your binary on each Tab press and the binary returns candidates. Its API has changed between releases, so check the current clap_complete documentation before relying on it.
Common mistakes
- Forgetting
CommandFactory. The error is "no function or associated item namedcommandfound". Importclap::CommandFactory. - Reusing one
Commandaftergenerate.generatetakes&mut Commandbecause it builds the command's internal state. Create a newCommandwithCli::command()if you need a clean one. - Writing to stdout and printing other text. A completion script must be the only output. Any extra
println!in the same code path corrupts the file when the user redirects it. - Not testing a clean shell. An old script loaded in your current session can hide a broken new one. Open a fresh shell after changing the file.
Exercise
A user runs mytool completions zsh > _mytool, copies the file into a directory on their fpath, and opens a new terminal. Tab completion still does nothing. Name two things you would check.
Show answer
First, that the directory is on fpath before compinit runs in .zshrc, because Zsh only scans fpath at that point. Second, that the file is named _mytool with the leading underscore and that the program name embedded in it matches the installed binary. A stale completion cache file such as ~/.zcompdump can also hide a new script, so deleting it and starting a fresh shell is a useful third check.
Exercise
Why does a build.rs that uses include!("src/cli.rs") fail to compile if cli.rs contains use crate::config::Level;?
Show answer
The build script is its own crate. When cli.rs is included there, crate refers to the build script, which has no config module. Move the type into cli.rs or include its file too.