Skip to content
Prev Previous commit
Next Next commit
Apply changes, ensure min 1 char on line
  • Loading branch information
tiptenbrink committed Nov 10, 2021
commit 7b32d0b1228987e2e13fcd324988b854c754f51b
19 changes: 16 additions & 3 deletions Lib/test/test_textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -1118,18 +1118,31 @@ def test_shorten_placeholder(self):
text_len=self.text_len)


class ZeroWidthTestCase(BaseTestCase):
class CustomWidthTestCase(BaseTestCase):
def text_len(self, text):
lengths = {
'A': 4,
'B': 2,
'Q': 0,
}

return sum(
0 if c == 'Q' else 1
lengths[c] if c in lengths else 1
for c in text
)

def test_zero_width_text_len(self):

text = "0QQ1234QQ56789"
self.check_wrap(text, 6, ["0QQ1234QQ5", "6789"], text_len=self.text_len)

def test_char_longer_than_width(self):
text = "AA0123"
self.check_wrap(text, 3, ["A", "A", "012", "3"], text_len=self.text_len)

def test_next_char_overflow(self):
text = "BB0123"
self.check_wrap(text, 3, ["B", "B0", "123"], text_len=self.text_len)


if __name__ == '__main__':
unittest.main()
16 changes: 9 additions & 7 deletions Lib/textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,21 +200,23 @@ def _fix_sentence_endings(self, chunks):
i += 1

def _find_width_index(self, text, width):
"""_find_width_index(text : string, width: int)
"""_find_length_index(text : string, width : int)

Find at which index the text has the required width.
Find at which index the text has the required width, since when using a
different text_len, this index will not be equal to the required width.
"""
# In most cases text_len will just use the number of characters, so this heuristic prevents calculating width
# for each character
# When using default len as self.text_len, the required index and width
# will be equal, this prevents calculation time.
if self.text_len(text[:width]) == width:
# For character widths greater than one, width can be more than the number of characters
# For character widths greater than one, width can be more than the
# number of characters
return min(width, len(text))
cur_text = ''
for i, c in enumerate(text):
cur_text += c
cur_width = self.text_len(cur_text)
if cur_width >= width:
return i+1
if cur_width > width:
return max(i, 1)

def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
"""_handle_long_word(chunks : [string],
Expand Down