Writing a custom bash rule -completion

I have directories with files with the same prefix that I want to quickly open in vim. For example, I could:

$ ls *
bar:
bar_10  bar_20  bar_30

foo:
foo_10  foo_20  foo_30

I want to be in one of these directories and type:

$ vim <TAB>

and it autocompletes to:

$ vim bar_

To achieve this, I am pleased to have a file in a directory called ".completion" that has "bar_" in it.

The problem I have is this:

  * "vim <TAB>"  -->  "vim bar_"           // no space
  * "vim bar_1"  -->  "vim bar_10 "        // space

Where | it is a cursor, so if the file matches, add a space to the end. If we match the prefix, do not add a space.

The best I have so far is the behavior minus adding a space to the end. I tried all kinds of things, all to no avail. The following is what I have:

_vim()
{
    local cur opts
    local -a toks

    cur="${COMP_WORDS[COMP_CWORD]}"

    if [ -f .completion ]; then
        opts=`cat .completion`

        if [[ ${opts} = ${cur} ]]; then
            toks=( $(compgen -f ${cur} | sed -e 's/$/ /') )
        else
            if [[ -z ${cur} ]]; then
                toks=( $(compgen -W "${opts}" -- ${cur}) )
            else
                toks=( $(compgen -f ${cur} | sed -e 's/$/ /') )
            fi
        fi
    else
        toks=( $(compgen -f ${cur} | sed -e 's/$/ /') )
    fi

    COMPREPLY=( "${toks[@]}" )
}

complete -F _vim -o nospace vim

, , , .

+3
1

, sed, . :

saveIFS=$IFS
IFS=$'\n'    # this will allow filenames with spaces (but not filenames with newlines)
toks=( $(compgen -f -- "${cur}" ))    # the -- protects against filenames that start with a hyphen
toks=("${toks[@]/%/ }")    # add a trailing space to each element
IFS=$saveIFS
0

Source: https://habr.com/ru/post/1754446/


All Articles