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
14 changes: 14 additions & 0 deletions Lib/test/test_textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,20 @@ def test_placeholder(self):
placeholder=' [truncated]...')
self.check_wrap(self.text, 80, [self.text], placeholder='.' * 1000)

def test_placeholder_not_needed_when_text_fits(self):
# With max_lines set, text that fits must be returned as is even when
# the placeholder would not fit in the width; the placeholder is only
# required when the text is actually truncated.
self.assertEqual(shorten('ab', width=4), 'ab')
self.assertEqual(shorten('a', width=1), 'a')
self.assertEqual(
wrap('hello world', width=20, max_lines=3,
subsequent_indent=' ' * 17),
['hello world'])
# Truncation that cannot place the placeholder still raises.
with self.assertRaises(ValueError):
shorten('a very long text goes here', width=4)

def test_placeholder_backtrack(self):
# Test special case when max_lines insufficient, but what
# would be last wrapped line so long the placeholder cannot
Expand Down
11 changes: 4 additions & 7 deletions Lib/textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,13 +251,6 @@ def _wrap_chunks(self, chunks):
lines = []
if self.width <= 0:
raise ValueError("invalid width %r (must be > 0)" % self.width)
if self.max_lines is not None:
if self.max_lines > 1:
indent = self.subsequent_indent
else:
indent = self.initial_indent
if len(indent) + len(self.placeholder.lstrip()) > self.width:
raise ValueError("placeholder too large for max width")

# Arrange in reverse order so items can be efficiently popped
# from a stack of chucks.
Expand Down Expand Up @@ -333,6 +326,10 @@ def _wrap_chunks(self, chunks):
self.width):
lines[-1] = prev_line + self.placeholder
break
if (len(indent) + len(self.placeholder.lstrip())
> self.width):
raise ValueError(
"placeholder too large for max width")
lines.append(indent + self.placeholder.lstrip())
break

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:func:`textwrap.shorten` and :func:`textwrap.wrap` with *max_lines* no longer
raise :exc:`ValueError` for text that fits in *width* when the *placeholder* is
wider than *width*. The placeholder is only required when the text is actually
truncated.
Loading