_textwrap.py 1.3 KB

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