diff --git a/Lib/test/test_textwrap.py b/Lib/test/test_textwrap.py index aca1f427656bb5..3d467f109e58fa 100644 --- a/Lib/test/test_textwrap.py +++ b/Lib/test/test_textwrap.py @@ -615,6 +615,32 @@ def test_break_long(self): 'word,', 'anyways?']) + def test_break_very_long_word(self): + # A word much longer than the width is broken into many lines. + text = ''.join(map(str, range(1000))) + lines = wrap(text, 7) + self.assertEqual(''.join(lines), text) + self.assertEqual([len(line) for line in lines], + [7] * (len(text) // 7) + [len(text) % 7]) + + # The first line can be narrower than the following ones, and the + # last piece of the word shares its line with the next words. + self.check_wrap('a' * 25 + ' b c', 10, + ['* aaaaaaaa', ' aaaaaaaa', ' aaaaaaaa', ' a b c'], + initial_indent='* ', subsequent_indent=' ') + self.check_wrap('x ' + 'a' * 25, 10, + ['x aaaaaaaa', ' aaaaaaaa', ' aaaaaaaa', ' a'], + subsequent_indent=' ') + + # Each piece is broken after its last hyphen. + self.check_wrap('12345-67890-12345-67890-12345', 10, + ['12345-', '67890-', '12345-', '67890-', '12345']) + self.check_wrap('abc-1234567890123-4567890123456', 10, + ['abc-', '1234567890', '123-', '4567890123', '456']) + self.check_wrap('abc-1234567890123-4567890123456', 10, + ['abc-123456', '7890123-45', '6789012345', '6'], + break_on_hyphens=False) + def test_nobreak_long(self): # Test with break_long_words disabled self.wrapper.break_long_words = 0 diff --git a/Lib/textwrap.py b/Lib/textwrap.py index 2f213e34c2c329..cc5b30e91a9903 100644 --- a/Lib/textwrap.py +++ b/Lib/textwrap.py @@ -279,6 +279,18 @@ def _wrap_chunks(self, chunks): # Maximum width for this line. width = self.width - len(indent) + # This and all following lines have the same width, so split a + # long word for all of them at once. Breaking off one line at a + # time would copy the rest of the word each time. + word = chunks[-1] + if (lines and self.max_lines is None and self.break_long_words and + 0 < width < len(word) and + not (self.break_on_hyphens and '-' in word) and + word.split(None, 1) == [word]): + del chunks[-1] + chunks.extend(word[i:i + width] + for i in reversed(range(0, len(word), width))) + # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if self.drop_whitespace and chunks[-1].strip() == '' and lines: diff --git a/Misc/NEWS.d/next/Library/2026-11-14-05-18-59.gh-issue-161977.mZurHK.rst b/Misc/NEWS.d/next/Library/2026-11-14-05-18-59.gh-issue-161977.mZurHK.rst new file mode 100644 index 00000000000000..412742067f2fa5 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-14-05-18-59.gh-issue-161977.mZurHK.rst @@ -0,0 +1,2 @@ +Fix quadratic time complexity in :mod:`textwrap` when breaking a long word +into many lines.