Transform whitespace in ``text`` according to ``mode``. Available modes are: * ``all``: Return all whitespace unmodified. * ``single``: Collapse consecutive whitespace with a single whitespace character, preserving newlines. * ``oneline``: Collapse all runs of whitespace into
(mode: str, text: str)
| 225 | |
| 226 | |
| 227 | def filter_whitespace(mode: str, text: str) -> str: |
| 228 | """Transform whitespace in ``text`` according to ``mode``. |
| 229 | |
| 230 | Available modes are: |
| 231 | |
| 232 | * ``all``: Return all whitespace unmodified. |
| 233 | * ``single``: Collapse consecutive whitespace with a single whitespace |
| 234 | character, preserving newlines. |
| 235 | * ``oneline``: Collapse all runs of whitespace into a single space |
| 236 | character, removing all newlines in the process. |
| 237 | |
| 238 | .. versionadded:: 4.3 |
| 239 | """ |
| 240 | if mode == "all": |
| 241 | return text |
| 242 | elif mode == "single": |
| 243 | text = re.sub(r"([\t ]+)", " ", text) |
| 244 | text = re.sub(r"(\s*\n\s*)", "\n", text) |
| 245 | return text |
| 246 | elif mode == "oneline": |
| 247 | return re.sub(r"(\s+)", " ", text) |
| 248 | else: |
| 249 | raise Exception("invalid whitespace mode %s" % mode) |
| 250 | |
| 251 | |
| 252 | class Template(object): |