aboutsummaryrefslogtreecommitdiff
path: root/bash/bash_completion.d/keep.bash
blob: 4b479eca552c297dd4ba9aec889bc4b3f9c27e4e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Load _completion_ignore_case helper function
if ! declare -F _completion_ignore_case >/dev/null ; then
    source "$HOME"/.bash_completion.d/_completion_ignore_case.bash
fi

# Complete calls to keep() with variables and functions, or if -d is given with
# stuff that's already kept
_keep() {

    # Determine what we're doing based on first completion word
    local mode
    mode=keep
    if ((COMP_CWORD > 1)) ; then
        case ${COMP_WORDS[1]} in
            # Help; no completion
            -h) return 1 ;;
            # Deleting; change mode
            -d) mode=delete ;;
        esac
    fi

    # Collect words from an appropriate type of completion
    local ci comp
    while read -r comp ; do
        COMPREPLY[ci++]=$comp
    done < <(

        # Switch on second word; is it a -d option?
        case $mode in

            # Keepable names: all functions and variables
            (keep)
                compgen -A function -A variable -- "$2"
                ;;

            # Kept names: .bash-suffixed names in keep dir
            (delete)

                # Make globs behave correctly
                shopt -u dotglob
                shopt -s nullglob
                if _completion_ignore_case ; then
                    shopt -s nocaseglob
                fi

                # Build list of kept names
                bashkeep=${BASHKEEP:-"$HOME"/.bashkeep.d}
                for keep in "$bashkeep"/"$2"*.bash ; do
                    # Skip directories
                    ! [[ -d $keep ]] || continue
                    # Strip leading path
                    keep=${keep##*/}
                    # Strip trailing extension
                    keep=${keep%.bash}
                    # Print kept name
                    printf '%s\n' "$keep"
                done
                ;;
        esac
    )
}
complete -F _keep keep