tamuhey
tamuhey

Reputation: 3545

How to autocomplete files under specific directory?

I created a command memo as follows:

memo() {
  vi $HOME/memo/$1
}

I want to apply bash-completion to my memo to open files that is already in $HOME/memo directory:

$ memo [TAB] # to show files in $HOME/memo

$HOME/memo contains directory, so listing the file under memo is not sufficient. In other words, I want to apply what is used in ls command in $HOME/memo to memo:

$ ls [TAB]
foo.md bar/

I tried the below but it doesn't work for nested directories:

_memo() {
    local cur
    local files
    _get_comp_words_by_ref -n : cur
    files=$(ls $MEMODIR)
    COMPREPLY=( $(compgen -W "${files}" -- "${cur}") )
}
complete -F _memo memo

MEMODIR=$HOME/memo

Upvotes: 6

Views: 2097

Answers (1)

pynexj
pynexj

Reputation: 20797

Here's a simple example:

_memo()
{
    local MEMO_DIR=$HOME/memo
    local cmd=$1 cur=$2 pre=$3
    local arr i file

    arr=( $( cd "$MEMO_DIR" && compgen -f -- "$cur" ) )
    COMPREPLY=()
    for ((i = 0; i < ${#arr[@]}; ++i)); do
        file=${arr[i]}
        if [[ -d $MEMO_DIR/$file ]]; then
            file=$file/
        fi
        COMPREPLY[i]=$file
    done
}
complete -F _memo -o nospace memo

auto-complete

Upvotes: 12

Related Questions