_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between
(self, chunks)
| 236 | # devoted to the long word that we can't handle right now. |
| 237 | |
| 238 | def _wrap_chunks(self, chunks): |
| 239 | """_wrap_chunks(chunks : [string]) -> [string] |
| 240 | |
| 241 | Wrap a sequence of text chunks and return a list of lines of |
| 242 | length 'self.width' or less. (If 'break_long_words' is false, |
| 243 | some lines may be longer than this.) Chunks correspond roughly |
| 244 | to words and the whitespace between them: each chunk is |
| 245 | indivisible (modulo 'break_long_words'), but a line break can |
| 246 | come between any two chunks. Chunks should not have internal |
| 247 | whitespace; ie. a chunk is either all whitespace or a "word". |
| 248 | Whitespace chunks will be removed from the beginning and end of |
| 249 | lines, but apart from that whitespace is preserved. |
| 250 | """ |
| 251 | lines = [] |
| 252 | if self.width <= 0: |
| 253 | raise ValueError("invalid width %r (must be > 0)" % self.width) |
| 254 | if self.max_lines is not None: |
| 255 | if self.max_lines > 1: |
| 256 | indent = self.subsequent_indent |
| 257 | else: |
| 258 | indent = self.initial_indent |
| 259 | if len(indent) + len(self.placeholder.lstrip()) > self.width: |
| 260 | raise ValueError("placeholder too large for max width") |
| 261 | |
| 262 | # Arrange in reverse order so items can be efficiently popped |
| 263 | # from a stack of chucks. |
| 264 | chunks.reverse() |
| 265 | |
| 266 | while chunks: |
| 267 | |
| 268 | # Start the list of chunks that will make up the current line. |
| 269 | # cur_len is just the length of all the chunks in cur_line. |
| 270 | cur_line = [] |
| 271 | cur_len = 0 |
| 272 | |
| 273 | # Figure out which static string will prefix this line. |
| 274 | if lines: |
| 275 | indent = self.subsequent_indent |
| 276 | else: |
| 277 | indent = self.initial_indent |
| 278 | |
| 279 | # Maximum width for this line. |
| 280 | width = self.width - len(indent) |
| 281 | |
| 282 | # First chunk on line is whitespace -- drop it, unless this |
| 283 | # is the very beginning of the text (ie. no lines started yet). |
| 284 | if self.drop_whitespace and chunks[-1].strip() == '' and lines: |
| 285 | del chunks[-1] |
| 286 | |
| 287 | while chunks: |
| 288 | l = len(chunks[-1]) |
| 289 | |
| 290 | # Can at least squeeze this chunk onto the current line. |
| 291 | if cur_len + l <= width: |
| 292 | cur_line.append(chunks.pop()) |
| 293 | cur_len += l |
| 294 | |
| 295 | # Nope, this line is full. |