formatting.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. from contextlib import contextmanager
  2. from .termui import get_terminal_size
  3. from .parser import split_opt
  4. from ._compat import term_len
  5. # Can force a width. This is used by the test system
  6. FORCED_WIDTH = None
  7. def measure_table(rows):
  8. widths = {}
  9. for row in rows:
  10. for idx, col in enumerate(row):
  11. widths[idx] = max(widths.get(idx, 0), term_len(col))
  12. return tuple(y for x, y in sorted(widths.items()))
  13. def iter_rows(rows, col_count):
  14. for row in rows:
  15. row = tuple(row)
  16. yield row + ('',) * (col_count - len(row))
  17. def wrap_text(text, width=78, initial_indent='', subsequent_indent='',
  18. preserve_paragraphs=False):
  19. """A helper function that intelligently wraps text. By default, it
  20. assumes that it operates on a single paragraph of text but if the
  21. `preserve_paragraphs` parameter is provided it will intelligently
  22. handle paragraphs (defined by two empty lines).
  23. If paragraphs are handled, a paragraph can be prefixed with an empty
  24. line containing the ``\\b`` character (``\\x08``) to indicate that
  25. no rewrapping should happen in that block.
  26. :param text: the text that should be rewrapped.
  27. :param width: the maximum width for the text.
  28. :param initial_indent: the initial indent that should be placed on the
  29. first line as a string.
  30. :param subsequent_indent: the indent string that should be placed on
  31. each consecutive line.
  32. :param preserve_paragraphs: if this flag is set then the wrapping will
  33. intelligently handle paragraphs.
  34. """
  35. from ._textwrap import TextWrapper
  36. text = text.expandtabs()
  37. wrapper = TextWrapper(width, initial_indent=initial_indent,
  38. subsequent_indent=subsequent_indent,
  39. replace_whitespace=False)
  40. if not preserve_paragraphs:
  41. return wrapper.fill(text)
  42. p = []
  43. buf = []
  44. indent = None
  45. def _flush_par():
  46. if not buf:
  47. return
  48. if buf[0].strip() == '\b':
  49. p.append((indent or 0, True, '\n'.join(buf[1:])))
  50. else:
  51. p.append((indent or 0, False, ' '.join(buf)))
  52. del buf[:]
  53. for line in text.splitlines():
  54. if not line:
  55. _flush_par()
  56. indent = None
  57. else:
  58. if indent is None:
  59. orig_len = term_len(line)
  60. line = line.lstrip()
  61. indent = orig_len - term_len(line)
  62. buf.append(line)
  63. _flush_par()
  64. rv = []
  65. for indent, raw, text in p:
  66. with wrapper.extra_indent(' ' * indent):
  67. if raw:
  68. rv.append(wrapper.indent_only(text))
  69. else:
  70. rv.append(wrapper.fill(text))
  71. return '\n\n'.join(rv)
  72. class HelpFormatter(object):
  73. """This class helps with formatting text-based help pages. It's
  74. usually just needed for very special internal cases, but it's also
  75. exposed so that developers can write their own fancy outputs.
  76. At present, it always writes into memory.
  77. :param indent_increment: the additional increment for each level.
  78. :param width: the width for the text. This defaults to the terminal
  79. width clamped to a maximum of 78.
  80. """
  81. def __init__(self, indent_increment=2, width=None, max_width=None):
  82. self.indent_increment = indent_increment
  83. if max_width is None:
  84. max_width = 80
  85. if width is None:
  86. width = FORCED_WIDTH
  87. if width is None:
  88. width = max(min(get_terminal_size()[0], max_width) - 2, 50)
  89. self.width = width
  90. self.current_indent = 0
  91. self.buffer = []
  92. def write(self, string):
  93. """Writes a unicode string into the internal buffer."""
  94. self.buffer.append(string)
  95. def indent(self):
  96. """Increases the indentation."""
  97. self.current_indent += self.indent_increment
  98. def dedent(self):
  99. """Decreases the indentation."""
  100. self.current_indent -= self.indent_increment
  101. def write_usage(self, prog, args='', prefix='Usage: '):
  102. """Writes a usage line into the buffer.
  103. :param prog: the program name.
  104. :param args: whitespace separated list of arguments.
  105. :param prefix: the prefix for the first line.
  106. """
  107. usage_prefix = '%*s%s ' % (self.current_indent, prefix, prog)
  108. text_width = self.width - self.current_indent
  109. if text_width >= (term_len(usage_prefix) + 20):
  110. # The arguments will fit to the right of the prefix.
  111. indent = ' ' * term_len(usage_prefix)
  112. self.write(wrap_text(args, text_width,
  113. initial_indent=usage_prefix,
  114. subsequent_indent=indent))
  115. else:
  116. # The prefix is too long, put the arguments on the next line.
  117. self.write(usage_prefix)
  118. self.write('\n')
  119. indent = ' ' * (max(self.current_indent, term_len(prefix)) + 4)
  120. self.write(wrap_text(args, text_width,
  121. initial_indent=indent,
  122. subsequent_indent=indent))
  123. self.write('\n')
  124. def write_heading(self, heading):
  125. """Writes a heading into the buffer."""
  126. self.write('%*s%s:\n' % (self.current_indent, '', heading))
  127. def write_paragraph(self):
  128. """Writes a paragraph into the buffer."""
  129. if self.buffer:
  130. self.write('\n')
  131. def write_text(self, text):
  132. """Writes re-indented text into the buffer. This rewraps and
  133. preserves paragraphs.
  134. """
  135. text_width = max(self.width - self.current_indent, 11)
  136. indent = ' ' * self.current_indent
  137. self.write(wrap_text(text, text_width,
  138. initial_indent=indent,
  139. subsequent_indent=indent,
  140. preserve_paragraphs=True))
  141. self.write('\n')
  142. def write_dl(self, rows, col_max=30, col_spacing=2):
  143. """Writes a definition list into the buffer. This is how options
  144. and commands are usually formatted.
  145. :param rows: a list of two item tuples for the terms and values.
  146. :param col_max: the maximum width of the first column.
  147. :param col_spacing: the number of spaces between the first and
  148. second column.
  149. """
  150. rows = list(rows)
  151. widths = measure_table(rows)
  152. if len(widths) != 2:
  153. raise TypeError('Expected two columns for definition list')
  154. first_col = min(widths[0], col_max) + col_spacing
  155. for first, second in iter_rows(rows, len(widths)):
  156. self.write('%*s%s' % (self.current_indent, '', first))
  157. if not second:
  158. self.write('\n')
  159. continue
  160. if term_len(first) <= first_col - col_spacing:
  161. self.write(' ' * (first_col - term_len(first)))
  162. else:
  163. self.write('\n')
  164. self.write(' ' * (first_col + self.current_indent))
  165. text_width = max(self.width - first_col - 2, 10)
  166. lines = iter(wrap_text(second, text_width).splitlines())
  167. if lines:
  168. self.write(next(lines) + '\n')
  169. for line in lines:
  170. self.write('%*s%s\n' % (
  171. first_col + self.current_indent, '', line))
  172. else:
  173. self.write('\n')
  174. @contextmanager
  175. def section(self, name):
  176. """Helpful context manager that writes a paragraph, a heading,
  177. and the indents.
  178. :param name: the section name that is written as heading.
  179. """
  180. self.write_paragraph()
  181. self.write_heading(name)
  182. self.indent()
  183. try:
  184. yield
  185. finally:
  186. self.dedent()
  187. @contextmanager
  188. def indentation(self):
  189. """A context manager that increases the indentation."""
  190. self.indent()
  191. try:
  192. yield
  193. finally:
  194. self.dedent()
  195. def getvalue(self):
  196. """Returns the buffer contents."""
  197. return ''.join(self.buffer)
  198. def join_options(options):
  199. """Given a list of option strings this joins them in the most appropriate
  200. way and returns them in the form ``(formatted_string,
  201. any_prefix_is_slash)`` where the second item in the tuple is a flag that
  202. indicates if any of the option prefixes was a slash.
  203. """
  204. rv = []
  205. any_prefix_is_slash = False
  206. for opt in options:
  207. prefix = split_opt(opt)[0]
  208. if prefix == '/':
  209. any_prefix_is_slash = True
  210. rv.append((len(prefix), opt))
  211. rv.sort(key=lambda x: x[0])
  212. rv = ', '.join(x[1] for x in rv)
  213. return rv, any_prefix_is_slash