@@ -319,10 +319,61 @@ def print_topics(self, header, cmds, cmdlen, maxcol):
319
319
print header
320
320
if self .ruler :
321
321
print self .ruler * len (header )
322
- (cmds_per_line ,junk )= divmod (maxcol ,cmdlen )
323
- col = cmds_per_line
324
- for cmd in cmds :
325
- if col == 0 : print
326
- print (("%-" + `cmdlen` + "s" ) % cmd ),
327
- col = (col + 1 ) % cmds_per_line
328
- print "\n "
322
+ self .columnize (cmds , maxcol - 1 )
323
+ print
324
+
325
+ def columnize (self , list , displaywidth = 80 ):
326
+ """Display a list of strings as a compact set of columns.
327
+
328
+ Each column is only as wide as necessary.
329
+ Columns are separated by two spaces (one was not legible enough).
330
+ """
331
+ if not list :
332
+ print "<empty>"
333
+ return
334
+ nonstrings = [i for i in range (len (list ))
335
+ if not isinstance (list [i ], str )]
336
+ if nonstrings :
337
+ raise TypeError , ("list[i] not a string for i in %s" %
338
+ ", " .join (map (str , nonstrings )))
339
+ size = len (list )
340
+ if size == 1 :
341
+ print list [0 ]
342
+ return
343
+ # Try every row count from 1 upwards
344
+ for nrows in range (1 , len (list )):
345
+ ncols = (size + nrows - 1 ) // nrows
346
+ colwidths = []
347
+ totwidth = - 2
348
+ for col in range (ncols ):
349
+ colwidth = 0
350
+ for row in range (nrows ):
351
+ i = row + nrows * col
352
+ if i >= size :
353
+ break
354
+ x = list [i ]
355
+ colwidth = max (colwidth , len (x ))
356
+ colwidths .append (colwidth )
357
+ totwidth += colwidth + 2
358
+ if totwidth > displaywidth :
359
+ break
360
+ if totwidth <= displaywidth :
361
+ break
362
+ else :
363
+ nrows = len (list )
364
+ ncols = 1
365
+ colwidths = [0 ]
366
+ for row in range (nrows ):
367
+ texts = []
368
+ for col in range (ncols ):
369
+ i = row + nrows * col
370
+ if i >= size :
371
+ x = ""
372
+ else :
373
+ x = list [i ]
374
+ texts .append (x )
375
+ while texts and not texts [- 1 ]:
376
+ del texts [- 1 ]
377
+ for col in range (len (texts )):
378
+ texts [col ] = texts [col ].ljust (colwidths [col ])
379
+ print " " .join (texts )
0 commit comments