'Return a patch containing a subset of the diff'

def generate_patch(self, first_line_idx, last_line_idx, reverse=False):

    ADDITION = u'+'
    DELETION = u'-'
    CONTEXT = u'    '
    NO_NEWLINE = u'\\'
    lines = [(u'---    a/%s' % self.filename), (u'+++    b/%s' % self.filename)]
    start_offset = 0
    for hunk in self.hunks:
        if (hunk.last_line_idx < first_line_idx):
            continue
        if (hunk.first_line_idx > last_line_idx):
            break
        prev_skipped = False
        counts = defaultdict(int)
        filtered_lines = []
        for (line_idx, line) in enumerate(hunk.lines[1:], start=(hunk.first_line_idx + 1)):
            (line_type, line_content) = (line[:1], line[1:])
            if reverse:
                if (line_type == ADDITION):
                    line_type = DELETION
                elif (line_type == DELETION):
                    line_type = ADDITION
            if (not (first_line_idx <= line_idx <= last_line_idx)):
                if (line_type == ADDITION):
                    prev_skipped = True
                    continue
                elif (line_type == DELETION):
                    line_type = CONTEXT
            if ((line_type == NO_NEWLINE) and prev_skipped):
                continue
            filtered_lines.append((line_type + line_content))
            counts[line_type] += 1
            prev_skipped = False
        if ((not counts[ADDITION]) and (not counts[DELETION])):
            continue
        old_count = (counts[CONTEXT] + counts[DELETION])
        new_count = (counts[CONTEXT] + counts[ADDITION])
        if reverse:
            old_start = hunk.new_start
        else:
            old_start = hunk.old_start
        new_start = (old_start + start_offset)
        if (old_count == 0):
            new_start += 1
        if (new_count == 0):
            new_start -= 1
        start_offset += (counts[ADDITION] - counts[DELETION])
        lines.append(_format_hunk_header(old_start, old_count, new_start, new_count, hunk.heading))
        lines.extend(filtered_lines)
    if (len(lines) == 2):
        return None
    else:
        lines.append(u'')
        return u'\n'.join(lines)
