'Output completion suggestions for BASH.
The output of this function is passed to BASH\'s `COMREPLY` variable and
treated as completion suggestions. `COMREPLY` expects a space
separated string as the result.
The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used
to get information about the cli input. Please refer to the BASH
man-page for more information about this variables.
Subcommand options are saved as pairs. A pair consists of
the long option string (e.g. \'--exclude\') and a boolean
value indicating if the option requires arguments. When printing to
stdout, a equal sign is appended to options which require arguments.
Note: If debugging this function, it is recommended to write the debug
output in a separate file. Otherwise the debug output will be treated
and formatted as potential completion suggestions.'

def autocomplete(self):

    if (not os.environ.has_key('DJANGO_AUTO_COMPLETE')):
        return
    cwords = os.environ['COMP_WORDS'].split()[1:]
    cword = int(os.environ['COMP_CWORD'])
    try:
        curr = cwords[(cword - 1)]
    except IndexError:
        curr = ''
    subcommands = (get_commands().keys() + ['help'])
    options = [('--help', None)]
    if (cword == 1):
        print '    '.join(sorted(filter((lambda x: x.startswith(curr)), subcommands)))
    elif ((cwords[0] in subcommands) and (cwords[0] != 'help')):
        subcommand_cls = self.fetch_command(cwords[0])
        if (cwords[0] == 'runfcgi'):
            from django.core.servers.fastcgi import FASTCGI_OPTIONS
            options += [(k, 1) for k in FASTCGI_OPTIONS]
        elif (cwords[0] in ('dumpdata', 'reset', 'sql', 'sqlall', 'sqlclear', 'sqlcustom', 'sqlindexes', 'sqlreset', 'sqlsequencereset', 'test')):
            try:
                from django.conf import settings
                options += [(a.split('.')[(-1)], 0) for a in settings.INSTALLED_APPS]
            except ImportError:
                pass
        options += [(s_opt.get_opt_string(), s_opt.nargs) for s_opt in subcommand_cls.option_list]
        prev_opts = [x.split('=')[0] for x in cwords[1:(cword - 1)]]
        options = filter((lambda (x, v): (x not in prev_opts)), options)
        options = sorted([(k, v) for (k, v) in options if k.startswith(curr)])
        for option in options:
            opt_label = option[0]
            if option[1]:
                opt_label += '='
            print opt_label
    sys.exit(1)
