formatting.py 9.1 KB

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