Skip to content
Myr

_textwrap.py

This file

Path

src/click/_textwrap.py

188 lines · 6.1 KiB · Python

Last changed by

Make `TextWrapper` ANSI-aware (#3420)Rowlando13before adoption7c99ebe

History of this file

Take it

1from __future__ import annotations23import 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],52        cur_len: int,53        width: int,54    ) -> None:55        space_left = max(width - cur_len, 1)5657        if self.break_long_words:58            last = reversed_chunks[-1]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_indent168        self.initial_indent += indent169        self.subsequent_indent += indent170171        try:172            yield173        finally:174            self.initial_indent = old_initial_indent175            self.subsequent_indent = old_subsequent_indent176177    def indent_only(self, text: str) -> str:178        rv = []179180        for idx, line in enumerate(text.splitlines()):181            indent = self.initial_indent182183            if idx > 0:184                indent = self.subsequent_indent185186            rv.append(f"{indent}{line}")187188        return "\n".join(rv)