Search code examples
zshzsh-completion

Completion: Multiple similar options


I want to write completions for a program that takes --with-PROG= and --PROG-options as optional arguments. PROG may be one of different programs. There are many different programs, so I'd like to avoid manually writting out an options for each program. I did try the following:

#compdef hello

typeset -A opt_args
local context state line

_hello()
{
    typeset -a PROGS
    PROGS=('gcc' 'make')
    _arguments \
        '--with-'${^PROGS}'[path to PROG]:executable:_files' \
        '--'${^PROGS}'-options[PROG options]:string:'
}

Output:

$ hello --gcc-options
--make-options  --gcc-options  -- PROG  options                                                                                                                          
--with-make     --with-gcc     -- path to PROG

However, I'd like to have each individual option on a seperate line, and also replace PROG with the program name. What's the best way to do that?


Solution

  • You need to use array holding argument to _arguments:

    _hello()
    {
        emulate -L zsh
        local -a args_args
        local prog
        for prog in gcc make ; do
            args_args+=( 
                "--with-${prog}[path to $prog]:executable:_files"
                "--${prog}-options[$prog options]:string:"
            )
        done
        _arguments $args_args
    }