@@ -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
0 commit comments