_tl_complete()
{
    local cur prev quoted
    _get_comp_words_by_ref cur prev
    _quote_readline_by_ref "$cur" quoted
    _expand || return 0

    COMPREPLY=( $( \

            # It's problematic to set the whole shell array COMP_WORDS as an env
            # var and parse that in python, so we treat every element as
            # separate variables COMP_WORD_n.
            let n=0
            for cw in "${COMP_WORDS[@]}"; do
                export COMP_WORD_"${n}"="${cw}"
                let n=n+1
            done
            export N_COMP_WORDS="${n}"

            # FIXME: It seems bash unsets COMP_WORDBREAKS when running bash
            # subshells. Our python3 wrapper is a bash script, this means that
            # when we call the python script below, COMP_WORDBREAKS is not
            # set. Using a different variable name makes it work. Perhaps we
            # should use our own namespace for all of these variables to avoid
            # problems due to bash magic?
            export COMP_BREAKS="$COMP_WORDBREAKS"

            export COMP_LINE="$COMP_LINE"
            export COMP_POINT="$COMP_POINT"
            export COMP_CWORD="$COMP_CWORD"
            export OPTPARSE_AUTO_COMPLETE=1

            # Run script
            $1

                ) )

    exit_code=$?

    # See optcomplete.py for list of completion exit codes

    if [ $exit_code -eq 52 ]; then
        # Don't append a space after completion
        compopt -o nospace
    elif [ $exit_code -eq 53 ]; then
        # Use bash-completion's file completion
        compopt -o nospace
        _filedir
    fi
}
complete -F _tl_complete $1
