5

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

pynexj
  • 19,215
  • 5
  • 38
  • 56
tamuhey
  • 2,904
  • 3
  • 21
  • 50

1 Answers1

11

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

pynexj
  • 19,215
  • 5
  • 38
  • 56
  • Related to this topic but not an actual answer to the OPs question: I wanted an auto complete just like the OP but to only include dirs. I was trying to tweak this answer when I found that the `_cd()` function for bash autocomplete has a `$CDPATH` var that does exactly what I needed. – Benjamin Goodacre Aug 15 '22 at 13:42
  • Awesome, worked perfectly, thanks – Patrick Michaelsen Aug 30 '23 at 02:39