Skip to content
Myr

Make `TextWrapper` ANSI-aware (#3420)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents d959898, 587e3cc · Browse files · 4 files+214 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+214 added−2 removed

  • tests:+66 added−0 removed
  • other:+148 added−2 removed

4 files+214 added−2 removed

modified:src/click/_textwrap.py+139 added-2 removed
2 unmodified lines
3import collections.abc as cabc4import textwrap5from contextlib import contextmanager67from ._compat import _ansi_re8from ._compat import term_len91011def _truncate_visible(text: str, n: int) -> str:12 """Return the longest prefix of ``text`` containing at most ``n`` visible13 characters.1415 ANSI escape sequences inside the prefix are kept intact and do not count16 toward the visible width. A cut is never placed inside an escape sequence.17 """18 if n <= 0:19 return ""2021 visible = 022 i = 023 cut = 024 end = len(text)25 while i < end:26 m = _ansi_re.match(text, i)27 if m is not None:28 i = m.end()29 continue30 visible += 131 i += 132 cut = i33 if visible >= n:34 break35 return text[:cut]363738class TextWrapper(textwrap.TextWrapper):39 """``textwrap.TextWrapper`` variant that measures widths by visible40 character count.4142 ANSI escape sequences embedded in chunks, indents, or the placeholder are43 excluded from the width budget. Without this, styled help text (a styled44 ``Usage:`` prefix, a colorized option name, ...) would be wrapped earlier45 than its visible length warrants and tokens would split mid-word.46 """4748 def _handle_long_word(49 self,50 reversed_chunks: list[str],51 cur_line: list[str],
3 unmodified lines
55 space_left = max(width - cur_len, 1)5657 if self.break_long_words:58 last = reversed_chunks[-1]20 cut = last[:space_left]21 res = last[space_left:]59 cut = _truncate_visible(last, space_left)60 res = last[len(cut) :]61 cur_line.append(cut)62 reversed_chunks[-1] = res63 elif not cur_line:64 cur_line.append(reversed_chunks.pop())6566 def _wrap_chunks(self, chunks: list[str]) -> list[str]:67 """Wrap chunks counting widths in visible characters.6869 Mirrors the algorithm of :meth:`textwrap.TextWrapper._wrap_chunks`70 with every width measurement routed through71 :func:`click._compat.term_len` instead of :func:`len`, so ANSI escape72 bytes in chunks, indents, or the placeholder do not inflate the count.7374 .. seealso::75 :class:`textwrap.TextWrapper` in the Python standard library documentation:76 https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper7778 Reference implementation in CPython:79 https://github.com/python/cpython/blob/main/Lib/textwrap.py80 """81 lines: list[str] = []82 if self.width <= 0:83 raise ValueError(f"invalid width {self.width!r} (must be > 0)")84 if self.max_lines is not None:85 if self.max_lines > 1:86 indent = self.subsequent_indent87 else:88 indent = self.initial_indent89 if term_len(indent) + term_len(self.placeholder.lstrip()) > self.width:90 raise ValueError("placeholder too large for max width")9192 chunks.reverse()9394 while chunks:95 cur_line: list[str] = []96 cur_len = 09798 if lines:99 indent = self.subsequent_indent100 else:101 indent = self.initial_indent102103 width = self.width - term_len(indent)104105 if self.drop_whitespace and chunks[-1].strip() == "" and lines:106 del chunks[-1]107108 while chunks:109 n = term_len(chunks[-1])110111 if cur_len + n <= width:112 cur_line.append(chunks.pop())113 cur_len += n114115 else:116 break117118 if chunks and term_len(chunks[-1]) > width:119 self._handle_long_word(chunks, cur_line, cur_len, width)120 cur_len = sum(map(term_len, cur_line))121122 if self.drop_whitespace and cur_line and cur_line[-1].strip() == "":123 cur_len -= term_len(cur_line[-1])124 del cur_line[-1]125126 if cur_line:127 if (128 self.max_lines is None129 or len(lines) + 1 < self.max_lines130 or (131 not chunks132 or self.drop_whitespace133 and len(chunks) == 1134 and not chunks[0].strip()135 )136 and cur_len <= width137 ):138 lines.append(indent + "".join(cur_line))139 else:140 while cur_line:141 if (142 cur_line[-1].strip()143 and cur_len + term_len(self.placeholder) <= width144 ):145 cur_line.append(self.placeholder)146 lines.append(indent + "".join(cur_line))147 break148 cur_len -= term_len(cur_line[-1])149 del cur_line[-1]150 else:151 if lines:152 prev_line = lines[-1].rstrip()153 if (154 term_len(prev_line) + term_len(self.placeholder)155 <= self.width156 ):157 lines[-1] = prev_line + self.placeholder158 break159 lines.append(indent + self.placeholder.lstrip())160 break161162 return lines163164 @contextmanager165 def extra_indent(self, indent: str) -> cabc.Iterator[None]:166 old_initial_indent = self.initial_indent167 old_subsequent_indent = self.subsequent_indent
21 unmodified lines
modified:src/click/formatting.py+6 added
50 unmodified lines
51 :param subsequent_indent: the indent string that should be placed on52 each consecutive line.53 :param preserve_paragraphs: if this flag is set then the wrapping will54 intelligently handle paragraphs.5556 .. versionchanged:: 8.457 Width is measured in visible characters. ANSI escape sequences in58 ``text``, ``initial_indent``, or ``subsequent_indent`` no longer59 count toward the width budget, so styled input wraps based on what60 the user sees instead of raw byte length.61 """62 from ._textwrap import TextWrapper6364 text = text.expandtabs()
243 unmodified lines
modified:tests/test_formatting.py+66 added
1import pytest23import click4from click._compat import strip_ansi567def test_basic_functionality(runner):8 @click.command()
424 unmodified lines
433 formatter.write_text(text)434 actual = formatter.getvalue()435 expected = " Lorem ipsum dolor sit amet,\n consectetur adipiscing elit\n"436 assert actual == expected437438439@pytest.mark.parametrize(440 ("body", "width", "initial_indent"),441 [442 # Styled ``initial_indent`` must be measured by visible width, so the443 # ``Usage:`` prefix shouldn't push ``[OPTIONS]`` to the second line.444 # Regression for the asymmetry between ``HelpFormatter.write_usage``445 # (which sized the prefix with ``term_len``) and ``wrap_text``446 # (which previously used raw ``len``).447 pytest.param(448 "[OPTIONS]",449 30,450 "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m ",451 id="styled-initial-indent-does-not-break-body",452 ),453 # Styled chunks in the body itself wrap on visible width.454 pytest.param(455 "\x1b[31malpha\x1b[0m \x1b[31mbeta\x1b[0m"456 " \x1b[31mgamma\x1b[0m \x1b[31mdelta\x1b[0m",457 15,458 "",459 id="styled-body-wraps-on-visible-width",460 ),461 # ``_handle_long_word`` cuts a styled token between visible462 # characters; the ANSI escape sequence must not be split.463 pytest.param(464 "\x1b[31mabcdefghij\x1b[0m",465 5,466 "",467 id="styled-long-word-breaks-on-visible-width",468 ),469 ],470)471def test_wrap_text_visible_width(body, width, initial_indent):472 """``wrap_text`` of styled input produces the same line layout as473 ``wrap_text`` of the ANSI-stripped input.474475 ANSI escape bytes must not count toward the width budget, regardless476 of whether they appear in the body, in ``initial_indent``, or when a477 styled token has to be broken in the middle.478 """479 styled = click.formatting.wrap_text(480 body, width=width, initial_indent=initial_indent481 )482 plain = click.formatting.wrap_text(483 strip_ansi(body), width=width, initial_indent=strip_ansi(initial_indent)484 )485486 styled_visible = [strip_ansi(line) for line in styled.splitlines()]487 assert styled_visible == plain.splitlines()488489490def test_write_usage_styled_prefix_keeps_options_on_one_line():491 """End-to-end: a downstream-styled ``Usage:`` prefix should not split492 ``[OPTIONS]`` across two lines.493 """494 styled_prefix = "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m "495496 formatter = click.HelpFormatter(width=40)497 formatter.write_usage("cli", "[OPTIONS]", prefix=styled_prefix)498 rendered = formatter.getvalue()499500 visible = strip_ansi(rendered)501 assert visible == "Usage: cli [OPTIONS]\n"
modified:CHANGES.rst+3 added
54 unmodified lines
55- Use :class:`ValueError` message when conversion in :class:`FuncParamType` would56 fail. :issue:`3105` :pr:`3211`57- Add ``click.get_pager_file`` for file-like access to an output58 pager. :pr:`1572`59- :class:`~click.formatting.TextWrapper` and60 :func:`~click.formatting.wrap_text` now measure line width in visible61 characters, ignoring ANSI escape sequences. :pr:`3420`62- Show custom error messages from types when :func:`prompt` with63 ``hide_input=True`` fails validation, instead of always showing a64 generic message. Built-in type messages mask the input value.65 :issue:`2809` :pr:`3256`
1397 unmodified lines