2

I have a function which can take main arguments and then sub-arguments. Some of these sub-arguments are filenames. The current completion code I have is as follows.

_scm() {
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts=$(mpv -input cmdlist | awk '{print $1}')

    case "${prev}" in
        sub_add)
            COMPREPLY=( $(compgen -f ${cur}) )
            return 0
            ;;
        *)
            ;;
    esac

    COMPREPLY=( $(compgen -W "${opts}" -- ${cur} ) )
}
complete -o plusdirs -F _scm scm

I want the sub_add arg to take a filename as subarg and the current code is able to do that. But, I also want to get autocompletion of args again, once sub_add and it's aubargs are completed. But instead file completion keeps happening again and again.

For eg, right now, pressing

scm sub_add <TAB>

gives me completion for filenames. What I also want is that after completing the filename, the original arg completion should kick in

scm sub_add ~/filename.txt <TAB>

should give sub_add sub_load seek.... etc.

The reason for filename completion happening again and again is beacuse of complete -o plusdirs. But, without it bash completes both directories and files, while I want only filenames. How can I modify my code to achieve what I want?

0

I don't think there are any builtin or bash-completion standard function to complete only bare filenames. Directories can contain files so the standard behaviour for completing a filename is to complete on files and directories (as bash-completion's _filedir does. It has an option for only directories, but not for only files.).

You could write a custom function to only return bare filename matches, e.g. iterating on completions=( "$word"* ) and checking [[ -f "$i" ]] to build COMPREPLY.

I read your code more carefully. If you're generating completions for mpv, you shouldn't restrict it to only working for bare filenames in the current directory. That's not how any other custom completion function I'm aware of behaves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.