def _wordwrap(text, chars_per_line=80):
    """Split the lines of a text between whitespaces when a line length exceeds
    the specified number of characters. Newlines already present in text are 
    kept.
    """
    text_ = text.split('\n')
    text = []
    for l in text_:
        if len(l) > chars_per_line:
            l = l.split()
            c = 0
            i = 0
            _prev_i = 0
            while i < len(l):
                while c <= chars_per_line and i < len(l):
                    c += len(l[i])
                    if i < (len(l) - 1):
                        c += 1  # whitespace char
                    i += 1
                if c > chars_per_line:
                    i -= 1
                text.append(' '.join(l[_prev_i:i]))
                _prev_i = i
                c = 0
        else:
            text.append(l)
    # drop any trailing empty lines
    while not text[-1].strip():
        text.pop()
    return '\n'.join(text)