@@ -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,25 @@ def _fix_sentence_endings(self, chunks):
194201 else :
195202 i += 1
196203
204+ def _fit_index (self , text , width ):
205+ """_fit_index(text : string, width : int) -> int
206+
207+ Return the end index of the longest prefix of *text* whose width,
208+ as measured by self.text_len, does not exceed *width*. The index
209+ is 0 when the first character is wider than *width*.
210+ """
211+ # Fast path for the default len(): one character is one column.
212+ if self .text_len is len :
213+ return min (width , len (text ))
214+ # text_len is additive: the width of a prefix is the sum of the
215+ # widths of its characters.
216+ prefix_width = 0
217+ for i , char in enumerate (text ):
218+ prefix_width += self .text_len (char )
219+ if prefix_width > width :
220+ return i
221+ return len (text )
222+
197223 def _handle_long_word (self , reversed_chunks , cur_line , cur_len , width ):
198224 """_handle_long_word(chunks : [string],
199225 cur_line : [string],
@@ -212,16 +238,22 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
212238 # If we're allowed to break long words, then do so: put as much
213239 # of the next chunk onto the current line as will fit.
214240 if self .break_long_words and space_left > 0 :
215- end = space_left
216241 chunk = reversed_chunks [- 1 ]
217- if self .break_on_hyphens and len (chunk ) > space_left :
242+ # Keep as many leading characters as fit in the width. A wide
243+ # character that does not fit moves to the next line, but an
244+ # empty line takes one anyway, so that wrapping makes progress.
245+ end = self ._fit_index (chunk , space_left )
246+ if not end and not cur_line :
247+ end = 1
248+ if self .break_on_hyphens and self .text_len (chunk ) > space_left :
218249 # break after last hyphen, but only if there are
219250 # non-hyphens before it
220- hyphen = chunk .rfind ('-' , 0 , space_left )
251+ hyphen = chunk .rfind ('-' , 0 , end )
221252 if hyphen > 0 and any (c != '-' for c in chunk [:hyphen ]):
222253 end = hyphen + 1
223- cur_line .append (chunk [:end ])
224- reversed_chunks [- 1 ] = chunk [end :]
254+ if end :
255+ cur_line .append (chunk [:end ])
256+ reversed_chunks [- 1 ] = chunk [end :]
225257
226258 # Otherwise, we have to preserve the long word intact. Only add
227259 # it to the current line if there's nothing already there --
@@ -256,7 +288,8 @@ def _wrap_chunks(self, chunks):
256288 indent = self .subsequent_indent
257289 else :
258290 indent = self .initial_indent
259- if len (indent ) + len (self .placeholder .lstrip ()) > self .width :
291+ if (self .text_len (indent ) +
292+ self .text_len (self .placeholder .lstrip ()) > self .width ):
260293 raise ValueError ("placeholder too large for max width" )
261294
262295 # Arrange in reverse order so items can be efficiently popped
@@ -277,15 +310,15 @@ def _wrap_chunks(self, chunks):
277310 indent = self .initial_indent
278311
279312 # Maximum width for this line.
280- width = self .width - len (indent )
313+ width = self .width - self . text_len (indent )
281314
282315 # First chunk on line is whitespace -- drop it, unless this
283316 # is the very beginning of the text (ie. no lines started yet).
284317 if self .drop_whitespace and chunks [- 1 ].strip () == '' and lines :
285318 del chunks [- 1 ]
286319
287320 while chunks :
288- l = len (chunks [- 1 ])
321+ l = self . text_len (chunks [- 1 ])
289322
290323 # Can at least squeeze this chunk onto the current line.
291324 if cur_len + l <= width :
@@ -298,13 +331,13 @@ def _wrap_chunks(self, chunks):
298331
299332 # The current line is full, and the next chunk is too big to
300333 # fit on *any* line (not just this one).
301- if chunks and len (chunks [- 1 ]) > width :
334+ if chunks and self . text_len (chunks [- 1 ]) > width :
302335 self ._handle_long_word (chunks , cur_line , cur_len , width )
303- cur_len = sum (map (len , cur_line ))
336+ cur_len = sum (map (self . text_len , cur_line ))
304337
305338 # If the last chunk on this line is all whitespace, drop it.
306339 if self .drop_whitespace and cur_line and cur_line [- 1 ].strip () == '' :
307- cur_len -= len (cur_line [- 1 ])
340+ cur_len -= self . text_len (cur_line [- 1 ])
308341 del cur_line [- 1 ]
309342
310343 if cur_line :
@@ -320,16 +353,17 @@ def _wrap_chunks(self, chunks):
320353 else :
321354 while cur_line :
322355 if (cur_line [- 1 ].strip () and
323- cur_len + len (self .placeholder ) <= width ):
356+ cur_len + self . text_len (self .placeholder ) <= width ):
324357 cur_line .append (self .placeholder )
325358 lines .append (indent + '' .join (cur_line ))
326359 break
327- cur_len -= len (cur_line [- 1 ])
360+ cur_len -= self . text_len (cur_line [- 1 ])
328361 del cur_line [- 1 ]
329362 else :
330363 if lines :
331364 prev_line = lines [- 1 ].rstrip ()
332- if (len (prev_line ) + len (self .placeholder ) <=
365+ if (self .text_len (prev_line ) +
366+ self .text_len (self .placeholder ) <=
333367 self .width ):
334368 lines [- 1 ] = prev_line + self .placeholder
335369 break
0 commit comments