//! How to use value hints and generate shell completions. //! //! Usage with zsh: //! ```console //! $ cargo run --example completion-derive -- --generate=zsh > /usr/local/share/zsh/site-functions/_completion_derive //! $ compinit //! $ ./target/debug/examples/completion_derive -- //! ``` //! fish: //! ```console //! $ cargo run --example completion-derive -- --generate=fish > completion_derive.fish //! $ . ./completion_derive.fish //! $ ./target/debug/examples/completion_derive -- //! ``` use clap::{Args, Command, CommandFactory, Parser, Subcommand, ValueHint}; use clap_complete::{generate, Generator, Shell}; use std::ffi::OsString; use std::io; use std::path::PathBuf; #[derive(Parser, Debug, PartialEq)] #[command(name = "completion-derive")] struct Opt { // If provided, outputs the completion file for given shell #[arg(long = "generate", value_enum)] generator: Option, #[command(subcommand)] command: Option, } #[derive(Subcommand, Debug, PartialEq)] enum Commands { #[command(visible_alias = "hint")] ValueHint(ValueHintOpt), } #[derive(Args, Debug, PartialEq)] struct ValueHintOpt { // Showcasing all possible ValueHints: #[arg(long, value_hint = ValueHint::Unknown)] unknown: Option, #[arg(long, value_hint = ValueHint::Other)] other: Option, #[arg(short, long, value_hint = ValueHint::AnyPath)] path: Option, #[arg(short, long, value_hint = ValueHint::FilePath)] file: Option, #[arg(short, long, value_hint = ValueHint::DirPath)] dir: Option, #[arg(short, long, value_hint = ValueHint::ExecutablePath)] exe: Option, #[arg(long, value_hint = ValueHint::CommandName)] cmd_name: Option, #[arg(short, long, value_hint = ValueHint::CommandString)] cmd: Option, // Command::trailing_var_ar is required to use ValueHint::CommandWithArguments #[arg(trailing_var_arg = true, value_hint = ValueHint::CommandWithArguments)] command_with_args: Vec, #[arg(short, long, value_hint = ValueHint::Username)] user: Option, #[arg(long, value_hint = ValueHint::Hostname)] host: Option, #[arg(long, value_hint = ValueHint::Url)] url: Option, #[arg(long, value_hint = ValueHint::EmailAddress)] email: Option, } fn print_completions(gen: G, cmd: &mut Command) { generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout()); } fn main() { let opt = Opt::parse(); if let Some(generator) = opt.generator { let mut cmd = Opt::command(); eprintln!("Generating completion file for {generator:?}..."); print_completions(generator, &mut cmd); } else { println!("{opt:#?}"); } }