Skip to content

Commit 7b32d0b

Browse files
committed
Apply changes, ensure min 1 char on line
1 parent e5d6d88 commit 7b32d0b

2 files changed

Lines changed: 25 additions & 10 deletions

File tree

Lib/test/test_textwrap.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,18 +1118,31 @@ def test_shorten_placeholder(self):
11181118
text_len=self.text_len)
11191119

11201120

1121-
class ZeroWidthTestCase(BaseTestCase):
1121+
class CustomWidthTestCase(BaseTestCase):
11221122
def text_len(self, text):
1123+
lengths = {
1124+
'A': 4,
1125+
'B': 2,
1126+
'Q': 0,
1127+
}
1128+
11231129
return sum(
1124-
0 if c == 'Q' else 1
1130+
lengths[c] if c in lengths else 1
11251131
for c in text
11261132
)
11271133

11281134
def test_zero_width_text_len(self):
1129-
11301135
text = "0QQ1234QQ56789"
11311136
self.check_wrap(text, 6, ["0QQ1234QQ5", "6789"], text_len=self.text_len)
11321137

1138+
def test_char_longer_than_width(self):
1139+
text = "AA0123"
1140+
self.check_wrap(text, 3, ["A", "A", "012", "3"], text_len=self.text_len)
1141+
1142+
def test_next_char_overflow(self):
1143+
text = "BB0123"
1144+
self.check_wrap(text, 3, ["B", "B0", "123"], text_len=self.text_len)
1145+
11331146

11341147
if __name__ == '__main__':
11351148
unittest.main()

Lib/textwrap.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -200,21 +200,23 @@ def _fix_sentence_endings(self, chunks):
200200
i += 1
201201

202202
def _find_width_index(self, text, width):
203-
"""_find_width_index(text : string, width: int)
203+
"""_find_length_index(text : string, width : int)
204204
205-
Find at which index the text has the required width.
205+
Find at which index the text has the required width, since when using a
206+
different text_len, this index will not be equal to the required width.
206207
"""
207-
# In most cases text_len will just use the number of characters, so this heuristic prevents calculating width
208-
# for each character
208+
# When using default len as self.text_len, the required index and width
209+
# will be equal, this prevents calculation time.
209210
if self.text_len(text[:width]) == width:
210-
# For character widths greater than one, width can be more than the number of characters
211+
# For character widths greater than one, width can be more than the
212+
# number of characters
211213
return min(width, len(text))
212214
cur_text = ''
213215
for i, c in enumerate(text):
214216
cur_text += c
215217
cur_width = self.text_len(cur_text)
216-
if cur_width >= width:
217-
return i+1
218+
if cur_width > width:
219+
return max(i, 1)
218220

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

0 commit comments

Comments
 (0)