Rewrite `_wrap_chunks` in `TextWrapper` to be ANSI-aware
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent fc6c7c4 · 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
Provenance
- Commit
d946074- Tree
ec9094d- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
fc6c7c4
4 files changed+214 added−2 removed
modified:src/click/_textwrap.py+139 added-2 removed
2 unmodified lines3 import collections.abc as cabc4 import textwrap5 from contextlib import contextmanager6 7+from ._compat import _ansi_re8+from ._compat import term_len9 10+11+def _truncate_visible(text: str, n: int) -> str:12+ """Return the longest prefix of ``text`` containing at most ``n`` visible13+ characters.14+15+ 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 ""20+21+ 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]36+37+38 class TextWrapper(textwrap.TextWrapper):39+ """``textwrap.TextWrapper`` variant that measures widths by visible40+ character count.41+42+ 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+ """47+48 def _handle_long_word(49 self,50 reversed_chunks: list[str],51 cur_line: list[str],3 unmodified lines55 space_left = max(width - cur_len, 1)56 57 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())65 66+ def _wrap_chunks(self, chunks: list[str]) -> list[str]:67+ """Wrap chunks counting widths in visible characters.68+69+ 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.73+74+ .. seealso::75+ :class:`textwrap.TextWrapper` in the Python standard library documentation:76+ https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper77+78+ 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")91+92+ chunks.reverse()93+94+ while chunks:95+ cur_line: list[str] = []96+ cur_len = 097+98+ if lines:99+ indent = self.subsequent_indent100+ else:101+ indent = self.initial_indent102+103+ width = self.width - term_len(indent)104+105+ if self.drop_whitespace and chunks[-1].strip() == "" and lines:106+ del chunks[-1]107+108+ while chunks:109+ n = term_len(chunks[-1])110+111+ if cur_len + n <= width:112+ cur_line.append(chunks.pop())113+ cur_len += n114+115+ else:116+ break117+118+ 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))121+122+ 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]125+126+ 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+ break161+162+ return lines163+164 @contextmanager165 def extra_indent(self, indent: str) -> cabc.Iterator[None]:166 old_initial_indent = self.initial_indent167 old_subsequent_indent = self.subsequent_indent21 unmodified linesmodified:src/click/formatting.py+6 added
50 unmodified lines51 :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.55+56+ .. 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 TextWrapper63 64 text = text.expandtabs()243 unmodified linesmodified:tests/test_formatting.py+66 added
1 import pytest2 3 import click4+from click._compat import strip_ansi5 6 7 def test_basic_functionality(runner):8 @click.command()424 unmodified lines433 formatter.write_text(text)434 actual = formatter.getvalue()435 expected = " Lorem ipsum dolor sit amet,\n consectetur adipiscing elit\n"436 assert actual == expected437+438+439+@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+)471+def 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.474+475+ 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+ )485+486+ styled_visible = [strip_ansi(line) for line in styled.splitlines()]487+ assert styled_visible == plain.splitlines()488+489+490+def 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 "495+496+ formatter = click.HelpFormatter(width=40)497+ formatter.write_usage("cli", "[OPTIONS]", prefix=styled_prefix)498+ rendered = formatter.getvalue()499+500+ visible = strip_ansi(rendered)501+ assert visible == "Usage: cli [OPTIONS]\n"modified:CHANGES.rst+3 added
51 unmodified lines52 - Use :class:`ValueError` message when conversion in :class:`FuncParamType` would53 fail. :issue:`3105` :pr:`3211`54 - Add ``click.get_pager_file`` for file-like access to an output55 pager. :pr:`1572`56+- :class:`~click.formatting.TextWrapper` and57+ :func:`~click.formatting.wrap_text` now measure line width in visible58+ characters, ignoring ANSI escape sequences. :pr:`3420`59 60 Version 8.3.361 -------------62 1364 unmodified lines