A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines. Preserve all white space except added line breaks consume the space on which they break the line. Don't wrap long words, thus the output text may have lines longer t
(text, width)
| 39 | |
| 40 | @keep_lazy_text |
| 41 | def wrap(text, width): |
| 42 | """ |
| 43 | A word-wrap function that preserves existing line breaks. Expects that |
| 44 | existing line breaks are posix newlines. |
| 45 | |
| 46 | Preserve all white space except added line breaks consume the space on |
| 47 | which they break the line. |
| 48 | |
| 49 | Don't wrap long words, thus the output text may have lines longer than |
| 50 | ``width``. |
| 51 | """ |
| 52 | |
| 53 | wrapper = textwrap.TextWrapper( |
| 54 | width=width, |
| 55 | break_long_words=False, |
| 56 | break_on_hyphens=False, |
| 57 | replace_whitespace=False, |
| 58 | ) |
| 59 | result = [] |
| 60 | for line in text.splitlines(): |
| 61 | wrapped = wrapper.wrap(line) |
| 62 | if not wrapped: |
| 63 | # If `line` contains only whitespaces that are dropped, restore it. |
| 64 | result.append(line) |
| 65 | else: |
| 66 | result.extend(wrapped) |
| 67 | if text.endswith("\n"): |
| 68 | # If `text` ends with a newline, preserve it. |
| 69 | result.append("") |
| 70 | return "\n".join(result) |
| 71 | |
| 72 | |
| 73 | def add_truncation_text(text, truncate=None): |