Files

37 lines
1.1 KiB
Python

"""Greedy word wrapping."""
from __future__ import annotations
from typing import List
def _chunks(word: str, width: int) -> List[str]:
"""Break a single word into pieces of at most ``width`` characters."""
if len(word) <= width:
return [word]
return [word[i:i + width] for i in range(0, len(word), width)]
def wrap_text(text: str, width: int) -> List[str]:
"""Wrap ``text`` into lines of at most ``width`` characters.
Whitespace runs collapse to a single space. Words longer than ``width``
are split into pieces that fill whole lines.
"""
if width < 1:
raise ValueError("width must be at least 1")
lines: List[str] = []
current = ""
for word in text.split():
for piece in _chunks(word, width):
if not current:
current = piece
elif len(current) + 1 + len(piece) <= width:
current += " " + piece
else:
lines.append(current)
current = piece
if current:
lines.append(current)
return lines