textwrap.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. """Text wrapping and filling.
  2. """
  3. # Copyright (C) 1999-2001 Gregory P. Ward.
  4. # Copyright (C) 2002, 2003 Python Software Foundation.
  5. # Written by Greg Ward <[email protected]>
  6. __revision__ = "$Id: textwrap.py 39547 2005-09-15 17:21:59Z rhettinger $"
  7. import string, re
  8. # Do the right thing with boolean values for all known Python versions
  9. # (so this module can be copied to projects that don't depend on Python
  10. # 2.3, e.g. Optik and Docutils).
  11. try:
  12. True, False
  13. except NameError:
  14. (True, False) = (1, 0)
  15. __all__ = ['TextWrapper', 'wrap', 'fill']
  16. # Hardcode the recognized whitespace characters to the US-ASCII
  17. # whitespace characters. The main reason for doing this is that in
  18. # ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales
  19. # that character winds up in string.whitespace. Respecting
  20. # string.whitespace in those cases would 1) make textwrap treat 0xa0 the
  21. # same as any other whitespace char, which is clearly wrong (it's a
  22. # *non-breaking* space), 2) possibly cause problems with Unicode,
  23. # since 0xa0 is not in range(128).
  24. _whitespace = '\t\n\x0b\x0c\r '
  25. class TextWrapper:
  26. """
  27. Object for wrapping/filling text. The public interface consists of
  28. the wrap() and fill() methods; the other methods are just there for
  29. subclasses to override in order to tweak the default behaviour.
  30. If you want to completely replace the main wrapping algorithm,
  31. you'll probably have to override _wrap_chunks().
  32. Several instance attributes control various aspects of wrapping:
  33. width (default: 70)
  34. the maximum width of wrapped lines (unless break_long_words
  35. is false)
  36. initial_indent (default: "")
  37. string that will be prepended to the first line of wrapped
  38. output. Counts towards the line's width.
  39. subsequent_indent (default: "")
  40. string that will be prepended to all lines save the first
  41. of wrapped output; also counts towards each line's width.
  42. expand_tabs (default: true)
  43. Expand tabs in input text to spaces before further processing.
  44. Each tab will become 1 .. 8 spaces, depending on its position in
  45. its line. If false, each tab is treated as a single character.
  46. replace_whitespace (default: true)
  47. Replace all whitespace characters in the input text by spaces
  48. after tab expansion. Note that if expand_tabs is false and
  49. replace_whitespace is true, every tab will be converted to a
  50. single space!
  51. fix_sentence_endings (default: false)
  52. Ensure that sentence-ending punctuation is always followed
  53. by two spaces. Off by default because the algorithm is
  54. (unavoidably) imperfect.
  55. break_long_words (default: true)
  56. Break words longer than 'width'. If false, those words will not
  57. be broken, and some lines might be longer than 'width'.
  58. """
  59. whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
  60. unicode_whitespace_trans = {}
  61. uspace = ord(u' ')
  62. for x in map(ord, _whitespace):
  63. unicode_whitespace_trans[x] = uspace
  64. # This funky little regex is just the trick for splitting
  65. # text up into word-wrappable chunks. E.g.
  66. # "Hello there -- you goof-ball, use the -b option!"
  67. # splits into
  68. # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
  69. # (after stripping out empty strings).
  70. wordsep_re = re.compile(
  71. r'(\s+|' # any whitespace
  72. r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words
  73. r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
  74. # XXX this is not locale- or charset-aware -- string.lowercase
  75. # is US-ASCII only (and therefore English-only)
  76. sentence_end_re = re.compile(r'[%s]' # lowercase letter
  77. r'[\.\!\?]' # sentence-ending punct.
  78. r'[\"\']?' # optional end-of-quote
  79. % string.lowercase)
  80. def __init__(self,
  81. width=70,
  82. initial_indent="",
  83. subsequent_indent="",
  84. expand_tabs=True,
  85. replace_whitespace=True,
  86. fix_sentence_endings=False,
  87. break_long_words=True):
  88. self.width = width
  89. self.initial_indent = initial_indent
  90. self.subsequent_indent = subsequent_indent
  91. self.expand_tabs = expand_tabs
  92. self.replace_whitespace = replace_whitespace
  93. self.fix_sentence_endings = fix_sentence_endings
  94. self.break_long_words = break_long_words
  95. # -- Private methods -----------------------------------------------
  96. # (possibly useful for subclasses to override)
  97. def _munge_whitespace(self, text):
  98. """_munge_whitespace(text : string) -> string
  99. Munge whitespace in text: expand tabs and convert all other
  100. whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
  101. becomes " foo bar baz".
  102. """
  103. if self.expand_tabs:
  104. text = text.expandtabs()
  105. if self.replace_whitespace:
  106. if isinstance(text, str):
  107. text = text.translate(self.whitespace_trans)
  108. elif isinstance(text, unicode):
  109. text = text.translate(self.unicode_whitespace_trans)
  110. return text
  111. def _split(self, text):
  112. """_split(text : string) -> [string]
  113. Split the text to wrap into indivisible chunks. Chunks are
  114. not quite the same as words; see wrap_chunks() for full
  115. details. As an example, the text
  116. Look, goof-ball -- use the -b option!
  117. breaks into the following chunks:
  118. 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
  119. 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
  120. """
  121. chunks = self.wordsep_re.split(text)
  122. chunks = filter(None, chunks)
  123. return chunks
  124. def _fix_sentence_endings(self, chunks):
  125. """_fix_sentence_endings(chunks : [string])
  126. Correct for sentence endings buried in 'chunks'. Eg. when the
  127. original text contains "... foo.\nBar ...", munge_whitespace()
  128. and split() will convert that to [..., "foo.", " ", "Bar", ...]
  129. which has one too few spaces; this method simply changes the one
  130. space to two.
  131. """
  132. i = 0
  133. pat = self.sentence_end_re
  134. while i < len(chunks)-1:
  135. if chunks[i+1] == " " and pat.search(chunks[i]):
  136. chunks[i+1] = " "
  137. i += 2
  138. else:
  139. i += 1
  140. def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
  141. """_handle_long_word(chunks : [string],
  142. cur_line : [string],
  143. cur_len : int, width : int)
  144. Handle a chunk of text (most likely a word, not whitespace) that
  145. is too long to fit in any line.
  146. """
  147. space_left = max(width - cur_len, 1)
  148. # If we're allowed to break long words, then do so: put as much
  149. # of the next chunk onto the current line as will fit.
  150. if self.break_long_words:
  151. cur_line.append(reversed_chunks[-1][:space_left])
  152. reversed_chunks[-1] = reversed_chunks[-1][space_left:]
  153. # Otherwise, we have to preserve the long word intact. Only add
  154. # it to the current line if there's nothing already there --
  155. # that minimizes how much we violate the width constraint.
  156. elif not cur_line:
  157. cur_line.append(reversed_chunks.pop())
  158. # If we're not allowed to break long words, and there's already
  159. # text on the current line, do nothing. Next time through the
  160. # main loop of _wrap_chunks(), we'll wind up here again, but
  161. # cur_len will be zero, so the next line will be entirely
  162. # devoted to the long word that we can't handle right now.
  163. def _wrap_chunks(self, chunks):
  164. """_wrap_chunks(chunks : [string]) -> [string]
  165. Wrap a sequence of text chunks and return a list of lines of
  166. length 'self.width' or less. (If 'break_long_words' is false,
  167. some lines may be longer than this.) Chunks correspond roughly
  168. to words and the whitespace between them: each chunk is
  169. indivisible (modulo 'break_long_words'), but a line break can
  170. come between any two chunks. Chunks should not have internal
  171. whitespace; ie. a chunk is either all whitespace or a "word".
  172. Whitespace chunks will be removed from the beginning and end of
  173. lines, but apart from that whitespace is preserved.
  174. """
  175. lines = []
  176. if self.width <= 0:
  177. raise ValueError("invalid width %r (must be > 0)" % self.width)
  178. # Arrange in reverse order so items can be efficiently popped
  179. # from a stack of chucks.
  180. chunks.reverse()
  181. while chunks:
  182. # Start the list of chunks that will make up the current line.
  183. # cur_len is just the length of all the chunks in cur_line.
  184. cur_line = []
  185. cur_len = 0
  186. # Figure out which static string will prefix this line.
  187. if lines:
  188. indent = self.subsequent_indent
  189. else:
  190. indent = self.initial_indent
  191. # Maximum width for this line.
  192. width = self.width - len(indent)
  193. # First chunk on line is whitespace -- drop it, unless this
  194. # is the very beginning of the text (ie. no lines started yet).
  195. if chunks[-1].strip() == '' and lines:
  196. del chunks[-1]
  197. while chunks:
  198. l = len(chunks[-1])
  199. # Can at least squeeze this chunk onto the current line.
  200. if cur_len + l <= width:
  201. cur_line.append(chunks.pop())
  202. cur_len += l
  203. # Nope, this line is full.
  204. else:
  205. break
  206. # The current line is full, and the next chunk is too big to
  207. # fit on *any* line (not just this one).
  208. if chunks and len(chunks[-1]) > width:
  209. self._handle_long_word(chunks, cur_line, cur_len, width)
  210. # If the last chunk on this line is all whitespace, drop it.
  211. if cur_line and cur_line[-1].strip() == '':
  212. del cur_line[-1]
  213. # Convert current line back to a string and store it in list
  214. # of all lines (return value).
  215. if cur_line:
  216. lines.append(indent + ''.join(cur_line))
  217. return lines
  218. # -- Public interface ----------------------------------------------
  219. def wrap(self, text):
  220. """wrap(text : string) -> [string]
  221. Reformat the single paragraph in 'text' so it fits in lines of
  222. no more than 'self.width' columns, and return a list of wrapped
  223. lines. Tabs in 'text' are expanded with string.expandtabs(),
  224. and all other whitespace characters (including newline) are
  225. converted to space.
  226. """
  227. text = self._munge_whitespace(text)
  228. chunks = self._split(text)
  229. if self.fix_sentence_endings:
  230. self._fix_sentence_endings(chunks)
  231. return self._wrap_chunks(chunks)
  232. def fill(self, text):
  233. """fill(text : string) -> string
  234. Reformat the single paragraph in 'text' to fit in lines of no
  235. more than 'self.width' columns, and return a new string
  236. containing the entire wrapped paragraph.
  237. """
  238. return "\n".join(self.wrap(text))
  239. # -- Convenience interface ---------------------------------------------
  240. def wrap(text, width=70, **kwargs):
  241. """Wrap a single paragraph of text, returning a list of wrapped lines.
  242. Reformat the single paragraph in 'text' so it fits in lines of no
  243. more than 'width' columns, and return a list of wrapped lines. By
  244. default, tabs in 'text' are expanded with string.expandtabs(), and
  245. all other whitespace characters (including newline) are converted to
  246. space. See TextWrapper class for available keyword args to customize
  247. wrapping behaviour.
  248. """
  249. w = TextWrapper(width=width, **kwargs)
  250. return w.wrap(text)
  251. def fill(text, width=70, **kwargs):
  252. """Fill a single paragraph of text, returning a new string.
  253. Reformat the single paragraph in 'text' to fit in lines of no more
  254. than 'width' columns, and return a new string containing the entire
  255. wrapped paragraph. As with wrap(), tabs are expanded and other
  256. whitespace characters converted to space. See TextWrapper class for
  257. available keyword args to customize wrapping behaviour.
  258. """
  259. w = TextWrapper(width=width, **kwargs)
  260. return w.fill(text)
  261. # -- Loosely related functionality -------------------------------------
  262. def dedent(text):
  263. """dedent(text : string) -> string
  264. Remove any whitespace than can be uniformly removed from the left
  265. of every line in `text`.
  266. This can be used e.g. to make triple-quoted strings line up with
  267. the left edge of screen/whatever, while still presenting it in the
  268. source code in indented form.
  269. For example:
  270. def test():
  271. # end first line with \ to avoid the empty line!
  272. s = '''\
  273. hello
  274. world
  275. '''
  276. print repr(s) # prints ' hello\n world\n '
  277. print repr(dedent(s)) # prints 'hello\n world\n'
  278. """
  279. lines = text.expandtabs().split('\n')
  280. margin = None
  281. for line in lines:
  282. content = line.lstrip()
  283. if not content:
  284. continue
  285. indent = len(line) - len(content)
  286. if margin is None:
  287. margin = indent
  288. else:
  289. margin = min(margin, indent)
  290. if margin is not None and margin > 0:
  291. for i in range(len(lines)):
  292. lines[i] = lines[i][margin:]
  293. return '\n'.join(lines)