text.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """
  2. Utilities imported from ipython_genutils
  3. """
  4. from __future__ import annotations
  5. import re
  6. import textwrap
  7. from textwrap import dedent
  8. from textwrap import indent as _indent
  9. from typing import List
  10. def indent(val: str) -> str:
  11. return _indent(val, " ")
  12. def wrap_paragraphs(text: str, ncols: int = 80) -> List[str]:
  13. """Wrap multiple paragraphs to fit a specified width.
  14. This is equivalent to textwrap.wrap, but with support for multiple
  15. paragraphs, as separated by empty lines.
  16. Returns
  17. -------
  18. list of complete paragraphs, wrapped to fill `ncols` columns.
  19. """
  20. paragraph_re = re.compile(r"\n(\s*\n)+", re.MULTILINE)
  21. text = dedent(text).strip()
  22. paragraphs = paragraph_re.split(text)[::2] # every other entry is space
  23. out_ps = []
  24. indent_re = re.compile(r"\n\s+", re.MULTILINE)
  25. for p in paragraphs:
  26. # presume indentation that survives dedent is meaningful formatting,
  27. # so don't fill unless text is flush.
  28. if indent_re.search(p) is None:
  29. # wrap paragraph
  30. p = textwrap.fill(p, ncols)
  31. out_ps.append(p)
  32. return out_ps