diff --git a/CHANGES.md b/CHANGES.md index 3e10f5817..904f36877 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -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 diff --git a/docs/documentation.md b/docs/documentation.md index a4eab9995..7fdb5b657 100644 --- a/docs/documentation.md +++ b/docs/documentation.md @@ -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. @@ -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. diff --git a/src/click/_textwrap.py b/src/click/_textwrap.py index 82840f2df..2f067c1fc 100644 --- a/src/click/_textwrap.py +++ b/src/click/_textwrap.py @@ -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: @@ -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() @@ -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 diff --git a/src/click/formatting.py b/src/click/formatting.py index c4aa2de57..b9f86b798 100644 --- a/src/click/formatting.py +++ b/src/click/formatting.py @@ -45,7 +45,8 @@ 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 @@ -53,6 +54,10 @@ def wrap_text( :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 @@ -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) diff --git a/tests/test_compat.py b/tests/test_compat.py index cd7433268..64859c9ac 100644 --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -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" @@ -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) diff --git a/tests/test_formatting.py b/tests/test_formatting.py index 5d70c6b39..4b0d5e2ec 100644 --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -1,3 +1,5 @@ +import threading + import pytest import click @@ -437,12 +439,12 @@ def test_help_formatter_write_text(): ("body", "width", "initial_indent"), [ # Styled ``initial_indent`` must be measured by visible width, so the - # ``Usage:`` prefix shouldn't push ``[OPTIONS]`` to the second line. + # ``Usage:`` prefix shouldn't push ``CITY`` to the second line. # Regression for the asymmetry between ``HelpFormatter.write_usage`` # (which sized the prefix with ``term_len``) and ``wrap_text`` # (which previously used raw ``len``). pytest.param( - "[OPTIONS]", + "[OPTIONS] CITY", 30, "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m ", id="styled-initial-indent-does-not-break-body", @@ -455,14 +457,6 @@ def test_help_formatter_write_text(): "", id="styled-body-wraps-on-visible-width", ), - # ``_handle_long_word`` cuts a styled token between visible - # characters; the ANSI escape sequence must not be split. - pytest.param( - "\x1b[31mabcdefghij\x1b[0m", - 5, - "", - id="styled-long-word-breaks-on-visible-width", - ), # Colon-delimited true-color (ISO 8613-6) escapes are excluded from the # width budget too. pytest.param( @@ -485,9 +479,9 @@ def test_wrap_text_visible_width(body, width, initial_indent): """``wrap_text`` of styled input produces the same line layout as ``wrap_text`` of the ANSI-stripped input. - ANSI escape bytes must not count toward the width budget, regardless - of whether they appear in the body, in ``initial_indent``, or when a - styled token has to be broken in the middle. + ANSI escape bytes must not count toward the width budget, whether they + appear in the body or in ``initial_indent``. Wrapping moves or drops + whitespace only: every escape sequence survives, in order. """ styled = click.formatting.wrap_text( body, width=width, initial_indent=initial_indent @@ -498,20 +492,84 @@ def test_wrap_text_visible_width(body, width, initial_indent): styled_visible = [strip_ansi(line) for line in styled.splitlines()] assert styled_visible == plain.splitlines() + assert "".join(styled.split()) == "".join((initial_indent + body).split()) + + +@pytest.mark.parametrize( + ("text", "width", "expected"), + [ + # A line breaks between words, never after a hyphen inside one. + pytest.param( + "Add --avoid-motorways to stay on country roads.", + 20, + ["Add", "--avoid-motorways to", "stay on country", "roads."], + id="hyphenated-word", + ), + # A word wider than the line is not cut: it goes on a line of its own. + pytest.param( + "Visit Llanfairpwllgwyngyll in Wales.", + 10, + ["Visit", "Llanfairpwllgwyngyll", "in Wales."], + id="long-word", + ), + # A styled word wider than the line stays whole with its escape + # sequences. + pytest.param( + "Visit \x1b[31mLlanfairpwllgwyngyll\x1b[0m in Wales.", + 10, + ["Visit", "\x1b[31mLlanfairpwllgwyngyll\x1b[0m", "in Wales."], + id="styled-long-word", + ), + ], +) +def test_wrap_text_keeps_words_whole(text, width, expected): + """``wrap_text`` breaks lines between words only.""" + assert click.formatting.wrap_text(text, width).splitlines() == expected -def test_write_usage_styled_prefix_keeps_options_on_one_line(): +def test_wrap_text_rejects_width_below_one(): + """``wrap_text`` raises an error for a width that leaves no room for text.""" + with pytest.raises(ValueError, match="invalid width 0"): + click.formatting.wrap_text("Rain in Paris.", 0) + + +@pytest.mark.parametrize( + ("wrap", "expected"), + [ + pytest.param( + lambda: click.formatting.wrap_text( + " rain", 5, initial_indent=" " * 8, subsequent_indent=" " * 8 + ), + " rain", + id="wrap_text", + ), + ], +) +def test_wrap_under_indent_wider_than_width_returns(wrap, expected): + """Text that starts with a space wraps under an indent wider than the width.""" + result = [] + # The standard library's TextWrapper loops forever on this input with + # ``break_long_words=True``, on Python 3.10 to 3.16. Run the call in a thread, + # so a regression fails the test instead of an infinite loop. + thread = threading.Thread(target=lambda: result.append(wrap()), daemon=True) + thread.start() + thread.join(timeout=5) + assert not thread.is_alive(), "wrapping did not return" + assert result == [expected] + + +def test_write_usage_styled_prefix_keeps_arguments_on_one_line(): """End-to-end: a downstream-styled ``Usage:`` prefix should not split - ``[OPTIONS]`` across two lines. + the arguments across two lines. """ styled_prefix = "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m " formatter = click.HelpFormatter(width=40) - formatter.write_usage("cli", "[OPTIONS]", prefix=styled_prefix) + formatter.write_usage("cli", "[OPTIONS] CITY", prefix=styled_prefix) rendered = formatter.getvalue() visible = strip_ansi(rendered) - assert visible == "Usage: cli [OPTIONS]\n" + assert visible == "Usage: cli [OPTIONS] CITY\n" @pytest.mark.parametrize( @@ -600,6 +658,77 @@ def test_help_formatter_write_usage_without_args_styled_prefix(): assert "\x1b[" in rendered +@pytest.mark.parametrize( + ("width", "args", "expected"), + [ + # A line breaks between option names, never after a hyphen inside one. + pytest.param( + 65, + "--max-daily-temperature --min-nightly-temperature --wind-speed-unit" + " --rain-gauge-location --cloud-cover-percentage --sea-level-pressure" + " --snow-depth-threshold --dew-point-offset", + [ + "Usage: forecast --max-daily-temperature --min-nightly-temperature", + " --wind-speed-unit --rain-gauge-location", + " --cloud-cover-percentage --sea-level-pressure", + " --snow-depth-threshold --dew-point-offset", + ], + id="hyphenated-options", + ), + # An argument wider than the line is written whole on its own line, + # instead of being cut at a hyphen or between two letters. + pytest.param( + 40, + "[OPTIONS] --minimum-nightly-temperature CITY", + [ + "Usage: forecast [OPTIONS]", + " --minimum-nightly-temperature", + " CITY", + ], + id="argument-wider-than-line", + ), + # When the arguments go below the program name, each one stays whole + # too. + pytest.param( + 16, + "[OPTIONS] --minimum-nightly-temperature CITY", + [ + "Usage: forecast", + " [OPTIONS]", + " --minimum-nightly-temperature", + " CITY", + ], + id="arguments-below-program-name", + ), + ], +) +def test_help_formatter_write_usage_keeps_arguments_whole(width, args, expected): + """``HelpFormatter.write_usage`` breaks lines between arguments only.""" + f = click.HelpFormatter(width=width) + f.write_usage("forecast", args) + # Only line breaks are checked: the program name line can end with a space. + assert [line.rstrip() for line in f.getvalue().splitlines()] == expected + + +@pytest.mark.parametrize( + "write", + [ + pytest.param(lambda f, text: f.write_usage("forecast", text), id="write_usage"), + pytest.param(lambda f, text: f.write_text(text), id="write_text"), + pytest.param(lambda f, text: f.write_dl([("--city", text)]), id="write_dl"), + ], +) +def test_help_formatter_keeps_words_whole(write): + """Each ``HelpFormatter`` method that wraps text breaks lines between + words only. + """ + words = "Add --avoid-motorways to visit Llanfairpwllgwyngyll by bus.".split() + f = click.HelpFormatter(width=15) + write(f, " ".join(words)) + # The usage line and the definition list put a term before the words. + assert f.getvalue().split()[-len(words) :] == words + + @pytest.mark.parametrize( ("command_kwargs", "expected_usage_line"), [