def append_lines(lines, wrap, buf):
    """Append lines to the buffer. If the first line can be appended to the last
    line of the buf without exceeding wrap characters, the two lines are merged.
    Args:
        lines: an iterable of lines to append
        wrap:  maximum number of characters per line. 0 or negative wrap means
               no limit.
        buf:   an iterable of lines to append to"""
    if not lines:
        return
    if not buf or wrap > 0 and len(buf[-1]) + len(lines[0]) > wrap:
        buf += lines
    else:
        buf[-1] += lines[0]
        buf += lines[1:]
