PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Text.py

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