formatting.py 9.5 KB

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