PageRenderTime 49ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/textwrap.py

https://bitbucket.org/ltratt/pypy
Python | 425 lines | 389 code | 9 blank | 27 comment | 2 complexity | e50bdfc1c6eef57c0edcdc4e184462e1 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0, BSD-3-Clause
  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 <gward@python.net>
  6. __revision__ = "$Id$"
  7. import string, re
  8. try:
  9. _unicode = unicode
  10. except NameError:
  11. # If Python is built without Unicode support, the unicode type
  12. # will not exist. Fake one.
  13. class _unicode(object):
  14. pass
  15. # Do the right thing with boolean values for all known Python versions
  16. # (so this module can be copied to projects that don't depend on Python
  17. # 2.3, e.g. Optik and Docutils) by uncommenting the block of code below.
  18. #try:
  19. # True, False
  20. #except NameError:
  21. # (True, False) = (1, 0)
  22. __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent']
  23. # Hardcode the recognized whitespace characters to the US-ASCII
  24. # whitespace characters. The main reason for doing this is that in
  25. # ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales
  26. # that character winds up in string.whitespace. Respecting
  27. # string.whitespace in those cases would 1) make textwrap treat 0xa0 the
  28. # same as any other whitespace char, which is clearly wrong (it's a
  29. # *non-breaking* space), 2) possibly cause problems with Unicode,
  30. # since 0xa0 is not in range(128).
  31. _whitespace = '\t\n\x0b\x0c\r '
  32. class TextWrapper:
  33. """
  34. Object for wrapping/filling text. The public interface consists of
  35. the wrap() and fill() methods; the other methods are just there for
  36. subclasses to override in order to tweak the default behaviour.
  37. If you want to completely replace the main wrapping algorithm,
  38. you'll probably have to override _wrap_chunks().
  39. Several instance attributes control various aspects of wrapping:
  40. width (default: 70)
  41. the maximum width of wrapped lines (unless break_long_words
  42. is false)
  43. initial_indent (default: "")
  44. string that will be prepended to the first line of wrapped
  45. output. Counts towards the line's width.
  46. subsequent_indent (default: "")
  47. string that will be prepended to all lines save the first
  48. of wrapped output; also counts towards each line's width.
  49. expand_tabs (default: true)
  50. Expand tabs in input text to spaces before further processing.
  51. Each tab will become 1 .. 8 spaces, depending on its position in
  52. its line. If false, each tab is treated as a single character.
  53. replace_whitespace (default: true)
  54. Replace all whitespace characters in the input text by spaces
  55. after tab expansion. Note that if expand_tabs is false and
  56. replace_whitespace is true, every tab will be converted to a
  57. single space!
  58. fix_sentence_endings (default: false)
  59. Ensure that sentence-ending punctuation is always followed
  60. by two spaces. Off by default because the algorithm is
  61. (unavoidably) imperfect.
  62. break_long_words (default: true)
  63. Break words longer than 'width'. If false, those words will not
  64. be broken, and some lines might be longer than 'width'.
  65. break_on_hyphens (default: true)
  66. Allow breaking hyphenated words. If true, wrapping will occur
  67. preferably on whitespaces and right after hyphens part of
  68. compound words.
  69. drop_whitespace (default: true)
  70. Drop leading and trailing whitespace from lines.
  71. """
  72. whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
  73. unicode_whitespace_trans = {}
  74. uspace = ord(u' ')
  75. for x in map(ord, _whitespace):
  76. unicode_whitespace_trans[x] = uspace
  77. # This funky little regex is just the trick for splitting
  78. # text up into word-wrappable chunks. E.g.
  79. # "Hello there -- you goof-ball, use the -b option!"
  80. # splits into
  81. # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
  82. # (after stripping out empty strings).
  83. wordsep_re = re.compile(
  84. r'(\s+|' # any whitespace
  85. r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words
  86. r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
  87. # This less funky little regex just split on recognized spaces. E.g.
  88. # "Hello there -- you goof-ball, use the -b option!"
  89. # splits into
  90. # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
  91. wordsep_simple_re = re.compile(r'(\s+)')
  92. # XXX this is not locale- or charset-aware -- string.lowercase
  93. # is US-ASCII only (and therefore English-only)
  94. sentence_end_re = re.compile(r'[%s]' # lowercase letter
  95. r'[\.\!\?]' # sentence-ending punct.
  96. r'[\"\']?' # optional end-of-quote
  97. r'\Z' # end of chunk
  98. % string.lowercase)
  99. def __init__(self,
  100. width=70,
  101. initial_indent="",
  102. subsequent_indent="",
  103. expand_tabs=True,
  104. replace_whitespace=True,
  105. fix_sentence_endings=False,
  106. break_long_words=True,
  107. drop_whitespace=True,
  108. break_on_hyphens=True):
  109. self.width = width
  110. self.initial_indent = initial_indent
  111. self.subsequent_indent = subsequent_indent
  112. self.expand_tabs = expand_tabs
  113. self.replace_whitespace = replace_whitespace
  114. self.fix_sentence_endings = fix_sentence_endings
  115. self.break_long_words = break_long_words
  116. self.drop_whitespace = drop_whitespace
  117. self.break_on_hyphens = break_on_hyphens
  118. # recompile the regexes for Unicode mode -- done in this clumsy way for
  119. # backwards compatibility because it's rather common to monkey-patch
  120. # the TextWrapper class' wordsep_re attribute.
  121. self.wordsep_re_uni = re.compile(self.wordsep_re.pattern, re.U)
  122. self.wordsep_simple_re_uni = re.compile(
  123. self.wordsep_simple_re.pattern, re.U)
  124. # -- Private methods -----------------------------------------------
  125. # (possibly useful for subclasses to override)
  126. def _munge_whitespace(self, text):
  127. """_munge_whitespace(text : string) -> string
  128. Munge whitespace in text: expand tabs and convert all other
  129. whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
  130. becomes " foo bar baz".
  131. """
  132. if self.expand_tabs:
  133. text = text.expandtabs()
  134. if self.replace_whitespace:
  135. if isinstance(text, str):
  136. text = text.translate(self.whitespace_trans)
  137. elif isinstance(text, _unicode):
  138. text = text.translate(self.unicode_whitespace_trans)
  139. return text
  140. def _split(self, text):
  141. """_split(text : string) -> [string]
  142. Split the text to wrap into indivisible chunks. Chunks are
  143. not quite the same as words; see _wrap_chunks() for full
  144. details. As an example, the text
  145. Look, goof-ball -- use the -b option!
  146. breaks into the following chunks:
  147. 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
  148. 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
  149. if break_on_hyphens is True, or in:
  150. 'Look,', ' ', 'goof-ball', ' ', '--', ' ',
  151. 'use', ' ', 'the', ' ', '-b', ' ', option!'
  152. otherwise.
  153. """
  154. if isinstance(text, _unicode):
  155. if self.break_on_hyphens:
  156. pat = self.wordsep_re_uni
  157. else:
  158. pat = self.wordsep_simple_re_uni
  159. else:
  160. if self.break_on_hyphens:
  161. pat = self.wordsep_re
  162. else:
  163. pat = self.wordsep_simple_re
  164. chunks = pat.split(text)
  165. chunks = filter(None, chunks) # remove empty chunks
  166. return chunks
  167. def _fix_sentence_endings(self, chunks):
  168. """_fix_sentence_endings(chunks : [string])
  169. Correct for sentence endings buried in 'chunks'. Eg. when the
  170. original text contains "... foo.\\nBar ...", munge_whitespace()
  171. and split() will convert that to [..., "foo.", " ", "Bar", ...]
  172. which has one too few spaces; this method simply changes the one
  173. space to two.
  174. """
  175. i = 0
  176. patsearch = self.sentence_end_re.search
  177. while i < len(chunks)-1:
  178. if chunks[i+1] == " " and patsearch(chunks[i]):
  179. chunks[i+1] = " "
  180. i += 2
  181. else:
  182. i += 1
  183. def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
  184. """_handle_long_word(chunks : [string],
  185. cur_line : [string],
  186. cur_len : int, width : int)
  187. Handle a chunk of text (most likely a word, not whitespace) that
  188. is too long to fit in any line.
  189. """
  190. # Figure out when indent is larger than the specified width, and make
  191. # sure at least one character is stripped off on every pass
  192. if width < 1:
  193. space_left = 1
  194. else:
  195. space_left = width - cur_len
  196. # If we're allowed to break long words, then do so: put as much
  197. # of the next chunk onto the current line as will fit.
  198. if self.break_long_words:
  199. cur_line.append(reversed_chunks[-1][:space_left])
  200. reversed_chunks[-1] = reversed_chunks[-1][space_left:]
  201. # Otherwise, we have to preserve the long word intact. Only add
  202. # it to the current line if there's nothing already there --
  203. # that minimizes how much we violate the width constraint.
  204. elif not cur_line:
  205. cur_line.append(reversed_chunks.pop())
  206. # If we're not allowed to break long words, and there's already
  207. # text on the current line, do nothing. Next time through the
  208. # main loop of _wrap_chunks(), we'll wind up here again, but
  209. # cur_len will be zero, so the next line will be entirely
  210. # devoted to the long word that we can't handle right now.
  211. def _wrap_chunks(self, chunks):
  212. """_wrap_chunks(chunks : [string]) -> [string]
  213. Wrap a sequence of text chunks and return a list of lines of
  214. length 'self.width' or less. (If 'break_long_words' is false,
  215. some lines may be longer than this.) Chunks correspond roughly
  216. to words and the whitespace between them: each chunk is
  217. indivisible (modulo 'break_long_words'), but a line break can
  218. come between any two chunks. Chunks should not have internal
  219. whitespace; ie. a chunk is either all whitespace or a "word".
  220. Whitespace chunks will be removed from the beginning and end of
  221. lines, but apart from that whitespace is preserved.
  222. """
  223. lines = []
  224. if self.width <= 0:
  225. raise ValueError("invalid width %r (must be > 0)" % self.width)
  226. # Arrange in reverse order so items can be efficiently popped
  227. # from a stack of chucks.
  228. chunks.reverse()
  229. while chunks:
  230. # Start the list of chunks that will make up the current line.
  231. # cur_len is just the length of all the chunks in cur_line.
  232. cur_line = []
  233. cur_len = 0
  234. # Figure out which static string will prefix this line.
  235. if lines:
  236. indent = self.subsequent_indent
  237. else:
  238. indent = self.initial_indent
  239. # Maximum width for this line.
  240. width = self.width - len(indent)
  241. # First chunk on line is whitespace -- drop it, unless this
  242. # is the very beginning of the text (ie. no lines started yet).
  243. if self.drop_whitespace and chunks[-1].strip() == '' and lines:
  244. del chunks[-1]
  245. while chunks:
  246. l = len(chunks[-1])
  247. # Can at least squeeze this chunk onto the current line.
  248. if cur_len + l <= width:
  249. cur_line.append(chunks.pop())
  250. cur_len += l
  251. # Nope, this line is full.
  252. else:
  253. break
  254. # The current line is full, and the next chunk is too big to
  255. # fit on *any* line (not just this one).
  256. if chunks and len(chunks[-1]) > width:
  257. self._handle_long_word(chunks, cur_line, cur_len, width)
  258. # If the last chunk on this line is all whitespace, drop it.
  259. if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
  260. del cur_line[-1]
  261. # Convert current line back to a string and store it in list
  262. # of all lines (return value).
  263. if cur_line:
  264. lines.append(indent + ''.join(cur_line))
  265. return lines
  266. # -- Public interface ----------------------------------------------
  267. def wrap(self, text):
  268. """wrap(text : string) -> [string]
  269. Reformat the single paragraph in 'text' so it fits in lines of
  270. no more than 'self.width' columns, and return a list of wrapped
  271. lines. Tabs in 'text' are expanded with string.expandtabs(),
  272. and all other whitespace characters (including newline) are
  273. converted to space.
  274. """
  275. text = self._munge_whitespace(text)
  276. chunks = self._split(text)
  277. if self.fix_sentence_endings:
  278. self._fix_sentence_endings(chunks)
  279. return self._wrap_chunks(chunks)
  280. def fill(self, text):
  281. """fill(text : string) -> string
  282. Reformat the single paragraph in 'text' to fit in lines of no
  283. more than 'self.width' columns, and return a new string
  284. containing the entire wrapped paragraph.
  285. """
  286. return "\n".join(self.wrap(text))
  287. # -- Convenience interface ---------------------------------------------
  288. def wrap(text, width=70, **kwargs):
  289. """Wrap a single paragraph of text, returning a list of wrapped lines.
  290. Reformat the single paragraph in 'text' so it fits in lines of no
  291. more than 'width' columns, and return a list of wrapped lines. By
  292. default, tabs in 'text' are expanded with string.expandtabs(), and
  293. all other whitespace characters (including newline) are converted to
  294. space. See TextWrapper class for available keyword args to customize
  295. wrapping behaviour.
  296. """
  297. w = TextWrapper(width=width, **kwargs)
  298. return w.wrap(text)
  299. def fill(text, width=70, **kwargs):
  300. """Fill a single paragraph of text, returning a new string.
  301. Reformat the single paragraph in 'text' to fit in lines of no more
  302. than 'width' columns, and return a new string containing the entire
  303. wrapped paragraph. As with wrap(), tabs are expanded and other
  304. whitespace characters converted to space. See TextWrapper class for
  305. available keyword args to customize wrapping behaviour.
  306. """
  307. w = TextWrapper(width=width, **kwargs)
  308. return w.fill(text)
  309. # -- Loosely related functionality -------------------------------------
  310. _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
  311. _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
  312. def dedent(text):
  313. """Remove any common leading whitespace from every line in `text`.
  314. This can be used to make triple-quoted strings line up with the left
  315. edge of the display, while still presenting them in the source code
  316. in indented form.
  317. Note that tabs and spaces are both treated as whitespace, but they
  318. are not equal: the lines " hello" and "\\thello" are
  319. considered to have no common leading whitespace. (This behaviour is
  320. new in Python 2.5; older versions of this module incorrectly
  321. expanded tabs before searching for common leading whitespace.)
  322. """
  323. # Look for the longest leading string of spaces and tabs common to
  324. # all lines.
  325. margin = None
  326. text = _whitespace_only_re.sub('', text)
  327. indents = _leading_whitespace_re.findall(text)
  328. for indent in indents:
  329. if margin is None:
  330. margin = indent
  331. # Current line more deeply indented than previous winner:
  332. # no change (previous winner is still on top).
  333. elif indent.startswith(margin):
  334. pass
  335. # Current line consistent with and no deeper than previous winner:
  336. # it's the new winner.
  337. elif margin.startswith(indent):
  338. margin = indent
  339. # Current line and previous winner have no common whitespace:
  340. # there is no margin.
  341. else:
  342. margin = ""
  343. break
  344. # sanity check (testing/debugging only)
  345. if 0 and margin:
  346. for line in text.split("\n"):
  347. assert not line or line.startswith(margin), \
  348. "line = %r, margin = %r" % (line, margin)
  349. if margin:
  350. text = re.sub(r'(?m)^' + margin, '', text)
  351. return text
  352. if __name__ == "__main__":
  353. #print dedent("\tfoo\n\tbar")
  354. #print dedent(" \thello there\n \t how are you?")
  355. print dedent("Hello there.\n This is indented.")