def wrap(text, cols):
    lines = []
    while len(text) > cols:
        end = text.rfind(' ', 0, cols + 1)
        if end == -1 and not text[:cols].isspace():
            end = cols
        line, text = text[:end], text[end:].lstrip()
        lines.append(line)
    if text:
        lines.append(text)
    return lines