Skip to main content

Module completion

Module completion 

Source
Available on crate feature completion only.
Expand description

Shell completion: one completion <SHELL> verb for a CLI.

The verb prints a short registration script. The script does not hold the command grammar. At each TAB the shell runs the CLI again with VAR set to the shell’s name, and App::completion prints the candidates before Clap parses anything. Candidates therefore come from the binary that is installed, including values a CLI computes at run time through clap_complete’s ArgValueCompleter.

A CLI flattens CompletionCommand into its subcommands, turns the hook on, routes the verb to shell::view, and returns the script. The example needs clap with its derive feature, as the crate quick start shows:

use ctl_core::completion::CompletionCommand;
use ctl_core::prelude::*;
use ctl_core::shell;

#[derive(Parser)]
struct Cli {
    #[command(flatten)]
    output: OutputArgs,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    #[command(flatten)]
    Completion(CompletionCommand),
}

fn main() -> ExitCode {
    App::<Cli>::new("toy")
        .completion()
        .view(|cli| match cli.command {
            Command::Completion(_) => shell::view(cli.output.format),
        })
        .run(|cli| match cli.command {
            Command::Completion(command) => Ok(command.script("toy")?),
        })
}

A user loads the script at shell start, so it always matches the installed binary:

ShellStartup fileLine
bash~/.bashrcsource <(toy completion bash)
zsh~/.zshrc, after compinitsource <(toy completion zsh)
fish~/.config/fish/config.fishtoy completion fish | source

A Homebrew formula installs the same script at every install and upgrade with generate_completions_from_executable(bin/"toy", "completion"), or with shell_parameter_format: :clap, which sets VAR instead.

Structs§

CompletionArgs
The arguments of the completion verb.

Enums§

CompletionCommand
The completion verb, flattened into a CLI’s subcommands with #[command(flatten)], so its name, help, and argument read the same in every CLI built on ctl-core.

Constants§

VAR
The environment variable that turns a run into a completion request.