Skip to content
Open
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
26 changes: 26 additions & 0 deletions Lib/test/test_textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions Lib/textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix quadratic time complexity in :mod:`textwrap` when breaking a long word
into many lines.
Loading