completion routine for when user presses tab

def complete(text, state):
    '''completion routine for when user presses tab'''
    global last_clist
    global rline_mpstate
    if state != 0 and last_clist is not None:
        return last_clist[state]

    # split the command so far
    cmd = readline.get_line_buffer().split()

    if len(cmd) == 1:
        # if on first part then complete on commands and aliases
        last_clist = complete_command(text) + complete_alias(text)
    elif cmd[0] in rline_mpstate.completions:
        # we have a completion rule for this command
        last_clist = complete_rules(rline_mpstate.completions[cmd[0]], cmd[1:])
    else:
        # assume completion by filename
        last_clist = glob.glob(text+'*')
    ret = []
    for c in last_clist:
        if c.startswith(text) or c.startswith(text.upper()):
            ret.append(c)
    if len(ret) == 0:
        # if we had no matches then try case insensitively
        text = text.lower()
        for c in last_clist:
            if c.lower().startswith(text):
                ret.append(c)
    ret.append(None)
    last_clist = ret
    return last_clist[state]