textwrap.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. import re
  7. __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten']
  8. # Hardcode the recognized whitespace characters to the US-ASCII
  9. # whitespace characters. The main reason for doing this is that
  10. # some Unicode spaces (like \u00a0) are non-breaking whitespaces.
  11. _whitespace = '\t\n\x0b\x0c\r '
  12. class TextWrapper:
  13. """
  14. Object for wrapping/filling text. The public interface consists of
  15. the wrap() and fill() methods; the other methods are just there for
  16. subclasses to override in order to tweak the default behaviour.
  17. If you want to completely replace the main wrapping algorithm,
  18. you'll probably have to override _wrap_chunks().
  19. Several instance attributes control various aspects of wrapping:
  20. width (default: 70)
  21. the maximum width of wrapped lines (unless break_long_words
  22. is false)
  23. initial_indent (default: "")
  24. string that will be prepended to the first line of wrapped
  25. output. Counts towards the line's width.
  26. subsequent_indent (default: "")
  27. string that will be prepended to all lines save the first
  28. of wrapped output; also counts towards each line's width.
  29. expand_tabs (default: true)
  30. Expand tabs in input text to spaces before further processing.
  31. Each tab will become 0 .. 'tabsize' spaces, depending on its position
  32. in its line. If false, each tab is treated as a single character.
  33. tabsize (default: 8)
  34. Expand tabs in input text to 0 .. 'tabsize' spaces, unless
  35. 'expand_tabs' is false.
  36. replace_whitespace (default: true)
  37. Replace all whitespace characters in the input text by spaces
  38. after tab expansion. Note that if expand_tabs is false and
  39. replace_whitespace is true, every tab will be converted to a
  40. single space!
  41. fix_sentence_endings (default: false)
  42. Ensure that sentence-ending punctuation is always followed
  43. by two spaces. Off by default because the algorithm is
  44. (unavoidably) imperfect.
  45. break_long_words (default: true)
  46. Break words longer than 'width'. If false, those words will not
  47. be broken, and some lines might be longer than 'width'.
  48. break_on_hyphens (default: true)
  49. Allow breaking hyphenated words. If true, wrapping will occur
  50. preferably on whitespaces and right after hyphens part of
  51. compound words.
  52. drop_whitespace (default: true)
  53. Drop leading and trailing whitespace from lines.
  54. max_lines (default: None)
  55. Truncate wrapped lines.
  56. placeholder (default: ' [...]')
  57. Append to the last line of truncated text.
  58. """
  59. unicode_whitespace_trans = dict.fromkeys(map(ord, _whitespace), ord(' '))
  60. # This funky little regex is just the trick for splitting
  61. # text up into word-wrappable chunks. E.g.
  62. # "Hello there -- you goof-ball, use the -b option!"
  63. # splits into
  64. # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
  65. # (after stripping out empty strings).
  66. word_punct = r'[\w!"\'&.,?]'
  67. letter = r'[^\d\W]'
  68. whitespace = r'[%s]' % re.escape(_whitespace)
  69. nowhitespace = '[^' + whitespace[1:]
  70. wordsep_re = re.compile(r'''
  71. ( # any whitespace
  72. %(ws)s+
  73. | # em-dash between words
  74. (?<=%(wp)s) -{2,} (?=\w)
  75. | # word, possibly hyphenated
  76. %(nws)s+? (?:
  77. # hyphenated word
  78. -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))
  79. (?= %(lt)s -? %(lt)s)
  80. | # end of word
  81. (?=%(ws)s|\Z)
  82. | # em-dash
  83. (?<=%(wp)s) (?=-{2,}\w)
  84. )
  85. )''' % {'wp': word_punct, 'lt': letter,
  86. 'ws': whitespace, 'nws': nowhitespace},
  87. re.VERBOSE)
  88. del word_punct, letter, nowhitespace
  89. # This less funky little regex just split on recognized spaces. E.g.
  90. # "Hello there -- you goof-ball, use the -b option!"
  91. # splits into
  92. # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
  93. wordsep_simple_re = re.compile(r'(%s+)' % whitespace)
  94. del whitespace
  95. # XXX this is not locale- or charset-aware -- string.lowercase
  96. # is US-ASCII only (and therefore English-only)
  97. sentence_end_re = re.compile(r'[a-z]' # lowercase letter
  98. r'[\.\!\?]' # sentence-ending punct.
  99. r'[\"\']?' # optional end-of-quote
  100. r'\Z') # end of chunk
  101. def __init__(self,
  102. width=70,
  103. initial_indent="",
  104. subsequent_indent="",
  105. expand_tabs=True,
  106. replace_whitespace=True,
  107. fix_sentence_endings=False,
  108. break_long_words=True,
  109. drop_whitespace=True,
  110. break_on_hyphens=True,
  111. tabsize=8,
  112. *,
  113. max_lines=None,
  114. placeholder=' [...]'):
  115. self.width = width
  116. self.initial_indent = initial_indent
  117. self.subsequent_indent = subsequent_indent
  118. self.expand_tabs = expand_tabs
  119. self.replace_whitespace = replace_whitespace
  120. self.fix_sentence_endings = fix_sentence_endings
  121. self.break_long_words = break_long_words
  122. self.drop_whitespace = drop_whitespace
  123. self.break_on_hyphens = break_on_hyphens
  124. self.tabsize = tabsize
  125. self.max_lines = max_lines
  126. self.placeholder = placeholder
  127. # -- Private methods -----------------------------------------------
  128. # (possibly useful for subclasses to override)
  129. def _munge_whitespace(self, text):
  130. """_munge_whitespace(text : string) -> string
  131. Munge whitespace in text: expand tabs and convert all other
  132. whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
  133. becomes " foo bar baz".
  134. """
  135. if self.expand_tabs:
  136. text = text.expandtabs(self.tabsize)
  137. if self.replace_whitespace:
  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 self.break_on_hyphens is True:
  155. chunks = self.wordsep_re.split(text)
  156. else:
  157. chunks = self.wordsep_simple_re.split(text)
  158. chunks = [c for c in chunks if c]
  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. end = space_left
  193. chunk = reversed_chunks[-1]
  194. if self.break_on_hyphens and len(chunk) > space_left:
  195. # break after last hyphen, but only if there are
  196. # non-hyphens before it
  197. hyphen = chunk.rfind('-', 0, space_left)
  198. if hyphen > 0 and any(c != '-' for c in chunk[:hyphen]):
  199. end = hyphen + 1
  200. cur_line.append(chunk[:end])
  201. reversed_chunks[-1] = chunk[end:]
  202. # Otherwise, we have to preserve the long word intact. Only add
  203. # it to the current line if there's nothing already there --
  204. # that minimizes how much we violate the width constraint.
  205. elif not cur_line:
  206. cur_line.append(reversed_chunks.pop())
  207. # If we're not allowed to break long words, and there's already
  208. # text on the current line, do nothing. Next time through the
  209. # main loop of _wrap_chunks(), we'll wind up here again, but
  210. # cur_len will be zero, so the next line will be entirely
  211. # devoted to the long word that we can't handle right now.
  212. def _wrap_chunks(self, chunks):
  213. """_wrap_chunks(chunks : [string]) -> [string]
  214. Wrap a sequence of text chunks and return a list of lines of
  215. length 'self.width' or less. (If 'break_long_words' is false,
  216. some lines may be longer than this.) Chunks correspond roughly
  217. to words and the whitespace between them: each chunk is
  218. indivisible (modulo 'break_long_words'), but a line break can
  219. come between any two chunks. Chunks should not have internal
  220. whitespace; ie. a chunk is either all whitespace or a "word".
  221. Whitespace chunks will be removed from the beginning and end of
  222. lines, but apart from that whitespace is preserved.
  223. """
  224. lines = []
  225. if self.width <= 0:
  226. raise ValueError("invalid width %r (must be > 0)" % self.width)
  227. if self.max_lines is not None:
  228. if self.max_lines > 1:
  229. indent = self.subsequent_indent
  230. else:
  231. indent = self.initial_indent
  232. if len(indent) + len(self.placeholder.lstrip()) > self.width:
  233. raise ValueError("placeholder too large for max width")
  234. # Arrange in reverse order so items can be efficiently popped
  235. # from a stack of chucks.
  236. chunks.reverse()
  237. while chunks:
  238. # Start the list of chunks that will make up the current line.
  239. # cur_len is just the length of all the chunks in cur_line.
  240. cur_line = []
  241. cur_len = 0
  242. # Figure out which static string will prefix this line.
  243. if lines:
  244. indent = self.subsequent_indent
  245. else:
  246. indent = self.initial_indent
  247. # Maximum width for this line.
  248. width = self.width - len(indent)
  249. # First chunk on line is whitespace -- drop it, unless this
  250. # is the very beginning of the text (ie. no lines started yet).
  251. if self.drop_whitespace and chunks[-1].strip() == '' and lines:
  252. del chunks[-1]
  253. while chunks:
  254. l = len(chunks[-1])
  255. # Can at least squeeze this chunk onto the current line.
  256. if cur_len + l <= width:
  257. cur_line.append(chunks.pop())
  258. cur_len += l
  259. # Nope, this line is full.
  260. else:
  261. break
  262. # The current line is full, and the next chunk is too big to
  263. # fit on *any* line (not just this one).
  264. if chunks and len(chunks[-1]) > width:
  265. self._handle_long_word(chunks, cur_line, cur_len, width)
  266. cur_len = sum(map(len, cur_line))
  267. # If the last chunk on this line is all whitespace, drop it.
  268. if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
  269. cur_len -= len(cur_line[-1])
  270. del cur_line[-1]
  271. if cur_line:
  272. if (self.max_lines is None or
  273. len(lines) + 1 < self.max_lines or
  274. (not chunks or
  275. self.drop_whitespace and
  276. len(chunks) == 1 and
  277. not chunks[0].strip()) and cur_len <= width):
  278. # Convert current line back to a string and store it in
  279. # list of all lines (return value).
  280. lines.append(indent + ''.join(cur_line))
  281. else:
  282. while cur_line:
  283. if (cur_line[-1].strip() and
  284. cur_len + len(self.placeholder) <= width):
  285. cur_line.append(self.placeholder)
  286. lines.append(indent + ''.join(cur_line))
  287. break
  288. cur_len -= len(cur_line[-1])
  289. del cur_line[-1]
  290. else:
  291. if lines:
  292. prev_line = lines[-1].rstrip()
  293. if (len(prev_line) + len(self.placeholder) <=
  294. self.width):
  295. lines[-1] = prev_line + self.placeholder
  296. break
  297. lines.append(indent + self.placeholder.lstrip())
  298. break
  299. return lines
  300. def _split_chunks(self, text):
  301. text = self._munge_whitespace(text)
  302. return self._split(text)
  303. # -- Public interface ----------------------------------------------
  304. def wrap(self, text):
  305. """wrap(text : string) -> [string]
  306. Reformat the single paragraph in 'text' so it fits in lines of
  307. no more than 'self.width' columns, and return a list of wrapped
  308. lines. Tabs in 'text' are expanded with string.expandtabs(),
  309. and all other whitespace characters (including newline) are
  310. converted to space.
  311. """
  312. chunks = self._split_chunks(text)
  313. if self.fix_sentence_endings:
  314. self._fix_sentence_endings(chunks)
  315. return self._wrap_chunks(chunks)
  316. def fill(self, text):
  317. """fill(text : string) -> string
  318. Reformat the single paragraph in 'text' to fit in lines of no
  319. more than 'self.width' columns, and return a new string
  320. containing the entire wrapped paragraph.
  321. """
  322. return "\n".join(self.wrap(text))
  323. # -- Convenience interface ---------------------------------------------
  324. def wrap(text, width=70, **kwargs):
  325. """Wrap a single paragraph of text, returning a list of wrapped lines.
  326. Reformat the single paragraph in 'text' so it fits in lines of no
  327. more than 'width' columns, and return a list of wrapped lines. By
  328. default, tabs in 'text' are expanded with string.expandtabs(), and
  329. all other whitespace characters (including newline) are converted to
  330. space. See TextWrapper class for available keyword args to customize
  331. wrapping behaviour.
  332. """
  333. w = TextWrapper(width=width, **kwargs)
  334. return w.wrap(text)
  335. def fill(text, width=70, **kwargs):
  336. """Fill a single paragraph of text, returning a new string.
  337. Reformat the single paragraph in 'text' to fit in lines of no more
  338. than 'width' columns, and return a new string containing the entire
  339. wrapped paragraph. As with wrap(), tabs are expanded and other
  340. whitespace characters converted to space. See TextWrapper class for
  341. available keyword args to customize wrapping behaviour.
  342. """
  343. w = TextWrapper(width=width, **kwargs)
  344. return w.fill(text)
  345. def shorten(text, width, **kwargs):
  346. """Collapse and truncate the given text to fit in the given width.
  347. The text first has its whitespace collapsed. If it then fits in
  348. the *width*, it is returned as is. Otherwise, as many words
  349. as possible are joined and then the placeholder is appended::
  350. >>> textwrap.shorten("Hello world!", width=12)
  351. 'Hello world!'
  352. >>> textwrap.shorten("Hello world!", width=11)
  353. 'Hello [...]'
  354. """
  355. w = TextWrapper(width=width, max_lines=1, **kwargs)
  356. return w.fill(' '.join(text.strip().split()))
  357. # -- Loosely related functionality -------------------------------------
  358. _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
  359. _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
  360. def dedent(text):
  361. """Remove any common leading whitespace from every line in `text`.
  362. This can be used to make triple-quoted strings line up with the left
  363. edge of the display, while still presenting them in the source code
  364. in indented form.
  365. Note that tabs and spaces are both treated as whitespace, but they
  366. are not equal: the lines " hello" and "\\thello" are
  367. considered to have no common leading whitespace.
  368. Entirely blank lines are normalized to a newline character.
  369. """
  370. # Look for the longest leading string of spaces and tabs common to
  371. # all lines.
  372. margin = None
  373. text = _whitespace_only_re.sub('', text)
  374. indents = _leading_whitespace_re.findall(text)
  375. for indent in indents:
  376. if margin is None:
  377. margin = indent
  378. # Current line more deeply indented than previous winner:
  379. # no change (previous winner is still on top).
  380. elif indent.startswith(margin):
  381. pass
  382. # Current line consistent with and no deeper than previous winner:
  383. # it's the new winner.
  384. elif margin.startswith(indent):
  385. margin = indent
  386. # Find the largest common whitespace between current line and previous
  387. # winner.
  388. else:
  389. for i, (x, y) in enumerate(zip(margin, indent)):
  390. if x != y:
  391. margin = margin[:i]
  392. break
  393. # sanity check (testing/debugging only)
  394. if 0 and margin:
  395. for line in text.split("\n"):
  396. assert not line or line.startswith(margin), \
  397. "line = %r, margin = %r" % (line, margin)
  398. if margin:
  399. text = re.sub(r'(?m)^' + margin, '', text)
  400. return text
  401. def indent(text, prefix, predicate=None):
  402. """Adds 'prefix' to the beginning of selected lines in 'text'.
  403. If 'predicate' is provided, 'prefix' will only be added to the lines
  404. where 'predicate(line)' is True. If 'predicate' is not provided,
  405. it will default to adding 'prefix' to all non-empty lines that do not
  406. consist solely of whitespace characters.
  407. """
  408. if predicate is None:
  409. def predicate(line):
  410. return line.strip()
  411. def prefixed_lines():
  412. for line in text.splitlines(True):
  413. yield (prefix + line if predicate(line) else line)
  414. return ''.join(prefixed_lines())
  415. if __name__ == "__main__":
  416. #print dedent("\tfoo\n\tbar")
  417. #print dedent(" \thello there\n \t how are you?")
  418. print(dedent("Hello there.\n This is indented."))