_textwrap.py 1.2 KB

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