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