pub fn generate<G, S>(gen: G, cmd: &mut Command, bin_name: S, buf: &mut dyn Write)where
    G: Generator,
    S: Into<String>,
Expand description

Generate a completions file for a specified shell at runtime.

Until cargo install can install extra files like a completion script, this may be used e.g. in a command that outputs the contents of the completion script, to be redirected into a file by the user.

Examples

Assuming a separate cli.rs like the generate_to example, we can let users generate a completion script using a command:

// src/main.rs

mod cli;
use std::io;
use clap_complete::{generate, shells::Bash};

fn main() {
    let matches = cli::build_cli().get_matches();

    if matches.is_present("generate-bash-completions") {
        generate(Bash, &mut cli::build_cli(), "myapp", &mut io::stdout());
    }

    // normal logic continues...
}

Usage:

$ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash
Examples found in repository?
clap_complete/examples/completion-derive.rs (line 70)
69
70
71
fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
    generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}
More examples
Hide additional examples
clap_complete/examples/completion.rs (line 98)
97
98
99
fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
    generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}
clap_complete_fig/examples/fig_completion.rs (line 11)
6
7
8
9
10
11
12
fn main() {
    let mut cmd = Command::new("myapp")
        .subcommand(Command::new("test").subcommand(Command::new("config")))
        .subcommand(Command::new("hello"));

    generate(Fig, &mut cmd, "myapp", &mut io::stdout());
}