Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ Unreleased
- {meth}`CliRunner.invoke` accepts a new `context_settings` argument, to allow
passing settings to the {class}`Context` of the command which cannot be given as extra
keyword arguments like `color`. {issue}`2110` {pr}`3896`
- Help pages no longer break a line within a hyphenated word, like an option
name, or within a long word. {issue}`3362` {pr}`3902`

## Version 8.5.1

Expand Down
14 changes: 8 additions & 6 deletions docs/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,14 @@ Click's default wrapping ignores single new lines and rewraps the text based on
invoke(cli, args=['--help'])
```

To change the rendering maximum width, pass `max_content_width` when calling the command.

```python
cli(max_content_width=120)
```

To avoid ambiguity, line breaks are not added within hyphenated words (such as parameter names) or long words. This might cause a line to be longer than the max width, in which case it may be wrapped by the terminal.

## Escaping Click's Wrapping

Sometimes Click's wrapping can be a problem, such as when showing code examples where new lines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only `\b` . The `\b` is removed from the rendered help text.
Expand Down Expand Up @@ -261,12 +269,6 @@ Example:
invoke(cli, args=['--help'])
```

To change the rendering maximum width, pass `max_content_width` when calling the command.

```bash
cli(max_content_width=120)
```

## Truncating Help Texts

Click gets {class}`Command` help text from the docstring. If you do not want to include part of the docstring, add the `\f` escape marker to have Click truncate the help text after the marker.
Expand Down
102 changes: 8 additions & 94 deletions src/click/_textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,72 +4,28 @@
import textwrap
from contextlib import contextmanager

from ._compat import _ansi_re
from ._compat import term_len


def _truncate_visible(text: str, n: int) -> str:
"""Return the longest prefix of ``text`` containing at most ``n`` visible
characters.
ANSI escape sequences inside the prefix are kept intact and do not count
toward the visible width. A cut is never placed inside an escape sequence.
"""
if n <= 0:
return ""

visible = 0
i = 0
cut = 0
end = len(text)
while i < end:
m = _ansi_re.match(text, i)
if m is not None:
i = m.end()
continue
visible += 1
i += 1
cut = i
if visible >= n:
break
return text[:cut]


class TextWrapper(textwrap.TextWrapper):
"""``textwrap.TextWrapper`` variant that measures widths by visible
character count.
ANSI escape sequences embedded in chunks, indents, or the placeholder are
excluded from the width budget. Without this, styled help text (a styled
``Usage:`` prefix, a colorized option name, ...) would be wrapped earlier
than its visible length warrants and tokens would split mid-word.
ANSI escape sequences embedded in chunks or indents are excluded from the
width budget. Without this, styled help text (a styled ``Usage:`` prefix,
a colorized option name, ...) would be wrapped earlier than its visible
length warrants.
"""

def _handle_long_word(
self,
reversed_chunks: list[str],
cur_line: list[str],
cur_len: int,
width: int,
) -> None:
space_left = max(width - cur_len, 1)

if self.break_long_words:
last = reversed_chunks[-1]
cut = _truncate_visible(last, space_left)
res = last[len(cut) :]
cur_line.append(cut)
reversed_chunks[-1] = res
elif not cur_line:
cur_line.append(reversed_chunks.pop())

def _wrap_chunks(self, chunks: list[str]) -> list[str]:
"""Wrap chunks counting widths in visible characters.
Mirrors the algorithm of :meth:`textwrap.TextWrapper._wrap_chunks`
with every width measurement routed through
:func:`click._compat.term_len` instead of :func:`len`, so ANSI escape
bytes in chunks, indents, or the placeholder do not inflate the count.
bytes in chunks or indents do not inflate the count. ``max_lines`` is
not supported, because :func:`~click.formatting.wrap_text` never sets
it.
.. seealso::
:class:`textwrap.TextWrapper` in the Python standard library documentation:
Expand All @@ -81,13 +37,6 @@ def _wrap_chunks(self, chunks: list[str]) -> list[str]:
lines: list[str] = []
if self.width <= 0:
raise ValueError(f"invalid width {self.width!r} (must be > 0)")
if self.max_lines is not None:
if self.max_lines > 1:
indent = self.subsequent_indent
else:
indent = self.initial_indent
if term_len(indent) + term_len(self.placeholder.lstrip()) > self.width:
raise ValueError("placeholder too large for max width")

chunks.reverse()

Expand Down Expand Up @@ -117,47 +66,12 @@ def _wrap_chunks(self, chunks: list[str]) -> list[str]:

if chunks and term_len(chunks[-1]) > width:
self._handle_long_word(chunks, cur_line, cur_len, width)
cur_len = sum(map(term_len, cur_line))

if self.drop_whitespace and cur_line and cur_line[-1].strip() == "":
cur_len -= term_len(cur_line[-1])
del cur_line[-1]

if cur_line:
if (
self.max_lines is None
or len(lines) + 1 < self.max_lines
or (
not chunks
or self.drop_whitespace
and len(chunks) == 1
and not chunks[0].strip()
)
and cur_len <= width
):
lines.append(indent + "".join(cur_line))
else:
while cur_line:
if (
cur_line[-1].strip()
and cur_len + term_len(self.placeholder) <= width
):
cur_line.append(self.placeholder)
lines.append(indent + "".join(cur_line))
break
cur_len -= term_len(cur_line[-1])
del cur_line[-1]
else:
if lines:
prev_line = lines[-1].rstrip()
if (
term_len(prev_line) + term_len(self.placeholder)
<= self.width
):
lines[-1] = prev_line + self.placeholder
break
lines.append(indent + self.placeholder.lstrip())
break
lines.append(indent + "".join(cur_line))

return lines

Expand Down
11 changes: 10 additions & 1 deletion src/click/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,19 @@ def wrap_text(
no rewrapping should happen in that block.
:param text: the text that should be rewrapped.
:param width: the maximum width for the text.
:param width: the maximum width for the text. A word wider than that is not cut, and
goes on a line of its own.
:param initial_indent: the initial indent that should be placed on the
first line as a string.
:param subsequent_indent: the indent string that should be placed on
each consecutive line.
:param preserve_paragraphs: if this flag is set then the wrapping will
intelligently handle paragraphs.
.. versionchanged:: 8.6.0
Lines no longer break within a hyphenated word or a long word. A word
wider than ``width`` goes on a line of its own.
.. versionchanged:: 8.4.0
Width is measured in visible characters. ANSI escape sequences in
``text``, ``initial_indent``, or ``subsequent_indent`` no longer
Expand All @@ -62,11 +67,15 @@ def wrap_text(
from ._textwrap import TextWrapper

text = text.expandtabs()
# Lines break between words only. A break after a hyphen or inside a long
# word would show one term, like an option name, as two.
wrapper = TextWrapper(
width,
initial_indent=initial_indent,
subsequent_indent=subsequent_indent,
replace_whitespace=False,
break_on_hyphens=False,
break_long_words=False,
)
if not preserve_paragraphs:
return wrapper.fill(text)
Expand Down
23 changes: 0 additions & 23 deletions tests/test_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from click._compat import _ansi_re
from click._compat import strip_ansi
from click._compat import term_len
from click._textwrap import _truncate_visible

ESC = "\033"

Expand Down Expand Up @@ -246,25 +245,3 @@ def test_ansi_re_matches_whole_sequence(seq):
assert m is not None
assert m.start() == 0
assert m.end() == len(seq)


@pytest.mark.parametrize(
("text", "n", "expected"),
[
# No escapes: behaves like a plain prefix slice.
("abcdef", 3, "abc"),
("abc", 10, "abc"),
("abc", 0, ""),
("abc", -1, ""),
# A leading escape is kept and does not count toward the budget.
(f"{ESC}[31mabcdef{ESC}[0m", 3, f"{ESC}[31mabc"),
# A colon true-color escape stays intact; the cut lands after 3 chars.
(f"{ESC}[38:2:1:2:3mabcdef", 3, f"{ESC}[38:2:1:2:3mabc"),
# A trailing escape past the cut is not pulled in.
(f"{ESC}[31mabc{ESC}[0m", 3, f"{ESC}[31mabc"),
],
)
def test_truncate_visible(text, n, expected):
out = _truncate_visible(text, n)
assert out == expected
assert term_len(out) <= max(n, 0)
Loading
Loading