Skip to content

Bash completion offers subcommand suggestions ahead of time #5986

@mernen

Description

@mernen

Please complete the following tasks

Rust Version

rustc 1.86.0 (05f9846f8 2025-03-31)

Clap Version

v4.5.48

Minimal reproducible code

use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{CompleteEnv, Shell};

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[command(subcommand)]
    action: Action,
}

#[derive(Subcommand)]
enum Action {
    Complete(CompleteArgs),
}

#[derive(Parser)]
struct CompleteArgs {
    /// The shell to generate completion for
    #[arg(long, value_enum)]
    shell: Shell,
}

fn main() {
    CompleteEnv::with_factory(Cli::command).complete();

    let cli = Cli::parse();

    match cli.action {
        Action::Complete(args) => {
            let mut cmd = Cli::command();
            let name = cmd.get_name().to_string();
            clap_complete::generate(args.shell, &mut cmd, name, &mut std::io::stdout());
        }
    }
}

Steps to reproduce the bug with the above code

  1. Use Bash
  2. source <(cargo run -- complete --shell bash)
  3. Type <app-name> -- complete in the shell (don't run it)
  4. Position caret immediately after -- and press Tab twice

Actual Behaviour

Suggestions:

--shell  --help   

--shell is only valid after complete, so it shouldn't be an option.

Expected Behaviour

Only global flags should be available in this position:

--help     --version  

Additional Context

This also applies to nested subcommands. For example, for exhaustive, exhaustive ⇥ pacman would suggest one, two and help, which are subcommands of pacman.

The fix is to only consider $COMP_WORDS that come before $COMP_CWORD. This does not affect dynamic completion.

Debug Output

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-completionArea: completion generatorC-bugCategory: bugE-hardCall for participation: Experience needed to fix: Hard / a lot

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions