| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import collections.abc as cabc |
| 4 |
import textwrap |
| 5 |
from contextlib import contextmanager |
| 6 |
|
| 7 |
|
| 8 |
class TextWrapper(textwrap.TextWrapper): |
| 9 |
def _handle_long_word( |
| 10 |
self, |
| 11 |
reversed_chunks: list[str], |
| 12 |
cur_line: list[str], |
| 13 |
cur_len: int, |
| 14 |
width: int, |
| 15 |
) -> None: |
| 16 |
space_left = max(width - cur_len, 1) |
| 17 |
|
| 18 |
if self.break_long_words: |
| 19 |
last = reversed_chunks[-1] |
| 20 |
cut = last[:space_left] |
| 21 |
res = last[space_left:] |
| 22 |
cur_line.append(cut) |
| 23 |
reversed_chunks[-1] = res |
| 24 |
elif not cur_line: |
| 25 |
cur_line.append(reversed_chunks.pop()) |
| 26 |
|
| 27 |
@contextmanager |
| 28 |
def extra_indent(self, indent: str) -> cabc.Iterator[None]: |
| 29 |
old_initial_indent = self.initial_indent |
| 30 |
old_subsequent_indent = self.subsequent_indent |
| 31 |
self.initial_indent += indent |
| 32 |
self.subsequent_indent += indent |
| 33 |
|
| 34 |
try: |
| 35 |
yield |
| 36 |
finally: |
| 37 |
self.initial_indent = old_initial_indent |
| 38 |
self.subsequent_indent = old_subsequent_indent |
| 39 |
|
| 40 |
def indent_only(self, text: str) -> str: |
| 41 |
rv = [] |
| 42 |
|
| 43 |
for idx, line in enumerate(text.splitlines()): |
| 44 |
indent = self.initial_indent |
| 45 |
|
| 46 |
if idx > 0: |
| 47 |
indent = self.subsequent_indent |
| 48 |
|
| 49 |
rv.append(f"{indent}{line}") |
| 50 |
|
| 51 |
return "\n".join(rv) |