# bash completion for screen

have screen &&
_screen_sessions()
{
    local pattern

    if [ -n "$1" ]; then
        pattern=".*$1.*"
    else
        pattern=".*"
    fi

    COMPREPLY=( $( command screen -ls | sed -ne \
        's|^['$'\t'']\{1,\}\('"$cur"'[0-9]\{1,\}\.[^'$'\t'']\{1,\}\)'"$pattern"'$|\1|p' ) )
} &&
_screen()
{
    local cur prev words cword

    COMPREPLY=()
    _get_comp_words_by_ref cur prev words cword

    if ((cword > 2)); then
        case ${words[cword-2]} in
            -[dD])
                _screen_sessions
                return 0
                ;;
        esac
    fi

    case $prev in
        -[rR])
            # list detached
            _screen_sessions 'Detached'
            return 0
            ;;
        -[dDx])
            # list attached
            _screen_sessions 'Attached'
            return 0
            ;;
        -s)
            _shells
            return 0
            ;;
        -c)
            _filedir
            return 0
            ;;
    esac

    if [[ "$cur" == -* ]]; then
        COMPREPLY=( $( compgen -W '-a -A -c -d -D -e -f -fn -fa -h -i -ln \
            -list -L -m -O -p -q -r -R -s -S -t -U -v -wipe -x -X --help \
            --version' -- "$cur" ) )
    fi
} &&
complete -F _screen -o default screen

# Local variables:
# mode: shell-script
# sh-basic-offset: 4
# sh-indent-comment: t
# indent-tabs-mode: nil
# End:
# ex: ts=4 sw=4 et filetype=sh
