Skip to content

Commit 56ea2d3

Browse files
committed
gh-154686: Add text_len to TextWrapper (#152702)
1 parent b76b6e7 commit 56ea2d3

6 files changed

Lines changed: 179 additions & 19 deletions

File tree

‎Doc/library/textwrap.rst‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ functions should be good enough; otherwise, you should use an instance of
1919
replace_whitespace=True, fix_sentence_endings=False, \
2020
break_long_words=True, drop_whitespace=True, \
2121
break_on_hyphens=True, tabsize=8, max_lines=None, \
22-
placeholder=' [...]')
22+
placeholder=' [...]', text_len=len)
2323

2424
Wraps the single paragraph in *text* (a string) so every line is at most
2525
*width* characters long. Returns a list of output lines, without final
@@ -37,7 +37,7 @@ functions should be good enough; otherwise, you should use an instance of
3737
replace_whitespace=True, fix_sentence_endings=False, \
3838
break_long_words=True, drop_whitespace=True, \
3939
break_on_hyphens=True, tabsize=8, \
40-
max_lines=None, placeholder=' [...]')
40+
max_lines=None, placeholder=' [...]', text_len=len)
4141

4242
Wraps the single paragraph in *text*, and returns a single string containing the
4343
wrapped paragraph. :func:`fill` is shorthand for ::
@@ -50,7 +50,7 @@ functions should be good enough; otherwise, you should use an instance of
5050

5151
.. function:: shorten(text, width, *, fix_sentence_endings=False, \
5252
break_long_words=True, break_on_hyphens=True, \
53-
placeholder=' [...]')
53+
placeholder=' [...]', text_len=len)
5454

5555
Collapse and truncate the given *text* to fit in the given *width*.
5656

@@ -293,6 +293,31 @@ hyphenated words; only then will long words be broken if necessary, unless
293293
.. versionadded:: 3.4
294294

295295

296+
.. attribute:: text_len
297+
298+
(default: :func:`len`) Callable used to measure the width of a string
299+
when deciding where to wrap. Override the default to account for
300+
characters that are not a single column wide, such as double-width East
301+
Asian characters or zero-width combining characters::
302+
303+
>>> import textwrap, unicodedata
304+
>>> def display_width(text):
305+
... return sum(
306+
... 2 if unicodedata.east_asian_width(char) in 'FW' else 1
307+
... for char in text)
308+
...
309+
>>> textwrap.wrap('東京 大阪 京都 札幌', width=10)
310+
['東京 大阪 京都', '札幌']
311+
>>> textwrap.wrap('東京 大阪 京都 札幌', width=10, text_len=display_width)
312+
['東京 大阪', '京都 札幌']
313+
314+
The callable must return a non-negative integer, and it must be
315+
additive: the width of a string is the sum of the widths of its
316+
characters.
317+
318+
.. versionadded:: next
319+
320+
296321
:class:`TextWrapper` also provides some public methods, analogous to the
297322
module-level convenience functions:
298323

‎Doc/whatsnew/3.16.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,16 @@ symtable
758758
(Contributed by Irit Katriel in :gh:`124697`.)
759759

760760

761+
textwrap
762+
--------
763+
764+
* Add a *text_len* parameter to :func:`textwrap.wrap`, :func:`textwrap.fill`,
765+
:func:`textwrap.shorten`, and :class:`textwrap.TextWrapper`. It customizes
766+
how the width of a string is measured, so text that contains double-width
767+
or zero-width characters can be wrapped correctly.
768+
(Contributed by Kevin Deldycke in :gh:`154686`.)
769+
770+
761771
tkinter
762772
-------
763773

‎Lib/idlelib/idle_test/test_calltip.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def test_signature_wrap(self):
105105
(width=70, initial_indent='', subsequent_indent='', expand_tabs=True,
106106
replace_whitespace=True, fix_sentence_endings=False, break_long_words=True,
107107
drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None,
108-
placeholder=' [...]')
108+
placeholder=' [...]', text_len=<built-in function len>)
109109
Object for wrapping/filling text. The public interface consists of
110110
the wrap() and fill() methods; the other methods are just there for
111111
subclasses to override in order to tweak the default behaviour.

‎Lib/test/test_textwrap.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
# $Id$
99
#
1010

11+
import unicodedata
1112
import unittest
1213

1314
from textwrap import TextWrapper, wrap, fill, dedent, indent, shorten
@@ -1133,5 +1134,90 @@ def test_first_word_too_long_but_placeholder_fits(self):
11331134
self.check_shorten("Helloo", 5, "[...]")
11341135

11351136

1137+
class TextLenTestCase(BaseTestCase):
1138+
# The text_len option measures the width of a string, for text with
1139+
# characters that are not one column wide.
1140+
1141+
@staticmethod
1142+
def display_width(text):
1143+
# East Asian wide characters take two columns, combining characters
1144+
# take none.
1145+
return sum(
1146+
0 if unicodedata.combining(char)
1147+
else 2 if unicodedata.east_asian_width(char) in "FW"
1148+
else 1
1149+
for char in text
1150+
)
1151+
1152+
def check_shorten(self, text, width, expect, **kwargs):
1153+
self.check(shorten(text, width, **kwargs), expect)
1154+
1155+
def test_default_text_len_is_len(self):
1156+
self.assertIs(TextWrapper().text_len, len)
1157+
1158+
def test_explicit_len_matches_default(self):
1159+
text = "Hello there, how are you this fine day? I'm glad to hear it!"
1160+
self.check_wrap(text, 12, wrap(text, 12), text_len=len)
1161+
1162+
def test_wide_characters(self):
1163+
text = "東京 大阪 京都 札幌"
1164+
self.check_wrap(text, 10, ["東京 大阪 京都", "札幌"])
1165+
self.check_wrap(text, 10, ["東京 大阪", "京都 札幌"],
1166+
text_len=self.display_width)
1167+
1168+
def test_zero_width_characters(self):
1169+
text = "cafe\u0301 cafe\u0301 cafe\u0301"
1170+
self.check_wrap(text, 10, ["cafe\u0301"] * 3)
1171+
self.check_wrap(text, 10, ["cafe\u0301 cafe\u0301", "cafe\u0301"],
1172+
text_len=self.display_width)
1173+
1174+
def test_lines_fit_width(self):
1175+
text = "東京 大阪 名古屋 札幌 福岡 神戸 京都 横浜 仙台 広島"
1176+
for width in range(2, 30):
1177+
with self.subTest(width=width):
1178+
for line in wrap(text, width, text_len=self.display_width):
1179+
self.assertLessEqual(self.display_width(line), width)
1180+
1181+
def test_indent_width(self):
1182+
self.check_wrap("aa bb cc", 7, ["東東aa bb", "東東cc"],
1183+
initial_indent="東東", subsequent_indent="東東")
1184+
self.check_wrap("aa bb cc", 7, ["東東aa", "東東bb", "東東cc"],
1185+
initial_indent="東東", subsequent_indent="東東",
1186+
text_len=self.display_width)
1187+
1188+
def test_break_long_word_by_width(self):
1189+
word = "東" * 10
1190+
self.check_wrap(word, 8, ["東" * 8, "東" * 2])
1191+
self.check_wrap(word, 8, ["東" * 4, "東" * 4, "東" * 2],
1192+
text_len=self.display_width)
1193+
1194+
def test_break_long_word_keeps_one_character(self):
1195+
# A character wider than the line still goes on a line of its own.
1196+
self.check_wrap("東東", 1, ["東", "東"], text_len=self.display_width)
1197+
1198+
def test_break_long_word_moves_wide_character(self):
1199+
# A wide character that does not fit at the end of a line moves to
1200+
# the next one.
1201+
self.check_wrap("aaaa 東京大阪", 6, ["aaaa", "東京大阪"])
1202+
self.check_wrap("aaaa 東京大阪", 6, ["aaaa", "東京大", "阪"],
1203+
text_len=self.display_width)
1204+
1205+
def test_doubled_measure_and_width_keep_layout(self):
1206+
# Doubling both the measure and the width must not move any line
1207+
# break, including a hyphen break inside an over-long word.
1208+
double = lambda s: 2 * len(s)
1209+
for text in ("aa bb cc dd", "1234-5678-9012", "spam-egg-ham-bacon"):
1210+
for width in range(1, len(text) + 1):
1211+
with self.subTest(text=text, width=width):
1212+
self.assertEqual(wrap(text, 2 * width, text_len=double),
1213+
wrap(text, width))
1214+
1215+
def test_shorten_with_text_len(self):
1216+
text = "東京 大阪 京都 札幌"
1217+
self.check_shorten(text, 12, text)
1218+
self.check_shorten(text, 12, "東京 [...]",
1219+
text_len=self.display_width)
1220+
1221+
11361222
if __name__ == '__main__':
11371223
unittest.main()

‎Lib/textwrap.py‎

Lines changed: 50 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,11 @@ class TextWrapper:
6161
Truncate wrapped lines.
6262
placeholder (default: ' [...]')
6363
Append to the last line of truncated text.
64+
text_len (default: len)
65+
Callable returning the width of a string. Override the default to
66+
account for characters that are not one column wide, such as
67+
double-width or zero-width characters. The width of a string must
68+
be the sum of the widths of its characters.
6469
"""
6570

6671
unicode_whitespace_trans = dict.fromkeys(map(ord, _whitespace), ord(' '))
@@ -122,7 +127,8 @@ def __init__(self,
122127
tabsize=8,
123128
*,
124129
max_lines=None,
125-
placeholder=' [...]'):
130+
placeholder=' [...]',
131+
text_len=len):
126132
self.width = width
127133
self.initial_indent = initial_indent
128134
self.subsequent_indent = subsequent_indent
@@ -135,6 +141,7 @@ def __init__(self,
135141
self.tabsize = tabsize
136142
self.max_lines = max_lines
137143
self.placeholder = placeholder
144+
self.text_len = text_len
138145

139146

140147
# -- Private methods -----------------------------------------------
@@ -194,6 +201,26 @@ def _fix_sentence_endings(self, chunks):
194201
else:
195202
i += 1
196203

204+
def _truncate_to_width(self, text, width):
205+
"""_truncate_to_width(text : string, width : int) -> string
206+
207+
Return the longest prefix of *text* whose width, as measured by
208+
self.text_len, does not exceed *width*. The prefix is empty when
209+
the first character is wider than *width*.
210+
"""
211+
# Fast path for the default len(): the width is the number of
212+
# characters, so the prefix can be sliced directly.
213+
if self.text_len is len:
214+
return text[:width]
215+
# text_len is additive: the width of a prefix is the sum of the
216+
# widths of its characters.
217+
prefix_width = 0
218+
for i, char in enumerate(text):
219+
prefix_width += self.text_len(char)
220+
if prefix_width > width:
221+
return text[:i]
222+
return text
223+
197224
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
198225
"""_handle_long_word(chunks : [string],
199226
cur_line : [string],
@@ -212,16 +239,22 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
212239
# If we're allowed to break long words, then do so: put as much
213240
# of the next chunk onto the current line as will fit.
214241
if self.break_long_words and space_left > 0:
215-
end = space_left
216242
chunk = reversed_chunks[-1]
217-
if self.break_on_hyphens and len(chunk) > space_left:
243+
# Keep as many leading characters as fit in the width. A wide
244+
# character that does not fit moves to the next line, but an
245+
# empty line takes one anyway, so that wrapping makes progress.
246+
end = len(self._truncate_to_width(chunk, space_left))
247+
if not end and not cur_line:
248+
end = 1
249+
if self.break_on_hyphens and self.text_len(chunk) > space_left:
218250
# break after last hyphen, but only if there are
219251
# non-hyphens before it
220-
hyphen = chunk.rfind('-', 0, space_left)
252+
hyphen = chunk.rfind('-', 0, end)
221253
if hyphen > 0 and any(c != '-' for c in chunk[:hyphen]):
222254
end = hyphen + 1
223-
cur_line.append(chunk[:end])
224-
reversed_chunks[-1] = chunk[end:]
255+
if end:
256+
cur_line.append(chunk[:end])
257+
reversed_chunks[-1] = chunk[end:]
225258

226259
# Otherwise, we have to preserve the long word intact. Only add
227260
# it to the current line if there's nothing already there --
@@ -256,7 +289,8 @@ def _wrap_chunks(self, chunks):
256289
indent = self.subsequent_indent
257290
else:
258291
indent = self.initial_indent
259-
if len(indent) + len(self.placeholder.lstrip()) > self.width:
292+
if (self.text_len(indent) +
293+
self.text_len(self.placeholder.lstrip()) > self.width):
260294
raise ValueError("placeholder too large for max width")
261295

262296
# Arrange in reverse order so items can be efficiently popped
@@ -277,15 +311,15 @@ def _wrap_chunks(self, chunks):
277311
indent = self.initial_indent
278312

279313
# Maximum width for this line.
280-
width = self.width - len(indent)
314+
width = self.width - self.text_len(indent)
281315

282316
# First chunk on line is whitespace -- drop it, unless this
283317
# is the very beginning of the text (ie. no lines started yet).
284318
if self.drop_whitespace and chunks[-1].strip() == '' and lines:
285319
del chunks[-1]
286320

287321
while chunks:
288-
l = len(chunks[-1])
322+
l = self.text_len(chunks[-1])
289323

290324
# Can at least squeeze this chunk onto the current line.
291325
if cur_len + l <= width:
@@ -298,13 +332,13 @@ def _wrap_chunks(self, chunks):
298332

299333
# The current line is full, and the next chunk is too big to
300334
# fit on *any* line (not just this one).
301-
if chunks and len(chunks[-1]) > width:
335+
if chunks and self.text_len(chunks[-1]) > width:
302336
self._handle_long_word(chunks, cur_line, cur_len, width)
303-
cur_len = sum(map(len, cur_line))
337+
cur_len = sum(map(self.text_len, cur_line))
304338

305339
# If the last chunk on this line is all whitespace, drop it.
306340
if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
307-
cur_len -= len(cur_line[-1])
341+
cur_len -= self.text_len(cur_line[-1])
308342
del cur_line[-1]
309343

310344
if cur_line:
@@ -320,16 +354,17 @@ def _wrap_chunks(self, chunks):
320354
else:
321355
while cur_line:
322356
if (cur_line[-1].strip() and
323-
cur_len + len(self.placeholder) <= width):
357+
cur_len + self.text_len(self.placeholder) <= width):
324358
cur_line.append(self.placeholder)
325359
lines.append(indent + ''.join(cur_line))
326360
break
327-
cur_len -= len(cur_line[-1])
361+
cur_len -= self.text_len(cur_line[-1])
328362
del cur_line[-1]
329363
else:
330364
if lines:
331365
prev_line = lines[-1].rstrip()
332-
if (len(prev_line) + len(self.placeholder) <=
366+
if (self.text_len(prev_line) +
367+
self.text_len(self.placeholder) <=
333368
self.width):
334369
lines[-1] = prev_line + self.placeholder
335370
break
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Add a *text_len* parameter to :func:`textwrap.wrap`, :func:`textwrap.fill`,
2+
:func:`textwrap.shorten`, and :class:`textwrap.TextWrapper`. It customizes how
3+
the width of a string is measured, so that text containing double-width or
4+
zero-width characters can be wrapped correctly.

0 commit comments

Comments
 (0)