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

/lib-python/2.7/textwrap.py

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