'Refactors a docstring, looking for doctests.
This returns a modified version of the input string.  It looks
for doctests, which start with a ">>>" prompt, and may be
continued with "..." prompts, as long as the "..." is indented
the same as the ">>>".
(Unfortunately we can\'t use the doctest module\'s parser,
since, like most parsers, it is not geared towards preserving
the original source.)'

def refactor_docstring(self, input, filename):

    result = []
    block = None
    block_lineno = None
    indent = None
    lineno = 0
    for line in input.splitlines(True):
        lineno += 1
        if line.lstrip().startswith(self.PS1):
            if (block is not None):
                result.extend(self.refactor_doctest(block, block_lineno, indent, filename))
            block_lineno = lineno
            block = [line]
            i = line.find(self.PS1)
            indent = line[:i]
        elif ((indent is not None) and (line.startswith((indent + self.PS2)) or (line == ((indent + self.PS2.rstrip()) + u'\n')))):
            block.append(line)
        else:
            if (block is not None):
                result.extend(self.refactor_doctest(block, block_lineno, indent, filename))
            block = None
            indent = None
            result.append(line)
    if (block is not None):
        result.extend(self.refactor_doctest(block, block_lineno, indent, filename))
    return u''.join(result)
