def merge_lines(lines):
    """Merge lines when matching and contextual lines overlap.

    When matching and contextual lines overlap, some lines are
    duplicated. This function merges all lines so that they appear
    only once and have the right "line kind".
    """
    sorted_lines = sorted(lines, key=lambda l: (l[2], l[3]))
    seen = set()
    for repo, filename, line_number, line_kind, line in sorted_lines:
        if line_number in seen:
            continue
        seen.add(line_number)
        yield repo, filename, line_number, line_kind, line
