textwrap.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 = {}
  60. uspace = ord(' ')
  61. for x in _whitespace:
  62. unicode_whitespace_trans[ord(x)] = uspace
  63. # This funky little regex is just the trick for splitting
  64. # text up into word-wrappable chunks. E.g.
  65. # "Hello there -- you goof-ball, use the -b option!"
  66. # splits into
  67. # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
  68. # (after stripping out empty strings).
  69. word_punct = r'[\w!"\'&.,?]'
  70. letter = r'[^\d\W]'
  71. whitespace = r'[%s]' % re.escape(_whitespace)
  72. nowhitespace = '[^' + whitespace[1:]
  73. wordsep_re = re.compile(r'''
  74. ( # any whitespace
  75. %(ws)s+
  76. | # em-dash between words
  77. (?<=%(wp)s) -{2,} (?=\w)
  78. | # word, possibly hyphenated
  79. %(nws)s+? (?:
  80. # hyphenated word
  81. -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))
  82. (?= %(lt)s -? %(lt)s)
  83. | # end of word
  84. (?=%(ws)s|\Z)
  85. | # em-dash
  86. (?<=%(wp)s) (?=-{2,}\w)
  87. )
  88. )''' % {'wp': word_punct, 'lt': letter,
  89. 'ws': whitespace, 'nws': nowhitespace},
  90. re.VERBOSE)
  91. del word_punct, letter, nowhitespace
  92. # This less funky little regex just split on recognized spaces. E.g.
  93. # "Hello there -- you goof-ball, use the -b option!"
  94. # splits into
  95. # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
  96. wordsep_simple_re = re.compile(r'(%s+)' % whitespace)
  97. del whitespace
  98. # XXX this is not locale- or charset-aware -- string.lowercase
  99. # is US-ASCII only (and therefore English-only)
  100. sentence_end_re = re.compile(r'[a-z]' # lowercase letter
  101. r'[\.\!\?]' # sentence-ending punct.
  102. r'[\"\']?' # optional end-of-quote
  103. r'\Z') # end of chunk
  104. def __init__(self,
  105. width=70,
  106. initial_indent="",
  107. subsequent_indent="",
  108. expand_tabs=True,
  109. replace_whitespace=True,
  110. fix_sentence_endings=False,
  111. break_long_words=True,
  112. drop_whitespace=True,
  113. break_on_hyphens=True,
  114. tabsize=8,
  115. *,
  116. max_lines=None,
  117. placeholder=' [...]'):
  118. self.width = width
  119. self.initial_indent = initial_indent
  120. self.subsequent_indent = subsequent_indent
  121. self.expand_tabs = expand_tabs
  122. self.replace_whitespace = replace_whitespace
  123. self.fix_sentence_endings = fix_sentence_endings
  124. self.break_long_words = break_long_words
  125. self.drop_whitespace = drop_whitespace
  126. self.break_on_hyphens = break_on_hyphens
  127. self.tabsize = tabsize
  128. self.max_lines = max_lines
  129. self.placeholder = placeholder
  130. # -- Private methods -----------------------------------------------
  131. # (possibly useful for subclasses to override)
  132. def _munge_whitespace(self, text):
  133. """_munge_whitespace(text : string) -> string
  134. Munge whitespace in text: expand tabs and convert all other
  135. whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
  136. becomes " foo bar baz".
  137. """
  138. if self.expand_tabs:
  139. text = text.expandtabs(self.tabsize)
  140. if self.replace_whitespace:
  141. text = text.translate(self.unicode_whitespace_trans)
  142. return text
  143. def _split(self, text):
  144. """_split(text : string) -> [string]
  145. Split the text to wrap into indivisible chunks. Chunks are
  146. not quite the same as words; see _wrap_chunks() for full
  147. details. As an example, the text
  148. Look, goof-ball -- use the -b option!
  149. breaks into the following chunks:
  150. 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
  151. 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
  152. if break_on_hyphens is True, or in:
  153. 'Look,', ' ', 'goof-ball', ' ', '--', ' ',
  154. 'use', ' ', 'the', ' ', '-b', ' ', option!'
  155. otherwise.
  156. """
  157. if self.break_on_hyphens is True:
  158. chunks = self.wordsep_re.split(text)
  159. else:
  160. chunks = self.wordsep_simple_re.split(text)
  161. chunks = [c for c in chunks if c]
  162. return chunks
  163. def _fix_sentence_endings(self, chunks):
  164. """_fix_sentence_endings(chunks : [string])
  165. Correct for sentence endings buried in 'chunks'. Eg. when the
  166. original text contains "... foo.\\nBar ...", munge_whitespace()
  167. and split() will convert that to [..., "foo.", " ", "Bar", ...]
  168. which has one too few spaces; this method simply changes the one
  169. space to two.
  170. """
  171. i = 0
  172. patsearch = self.sentence_end_re.search
  173. while i < len(chunks)-1:
  174. if chunks[i+1] == " " and patsearch(chunks[i]):
  175. chunks[i+1] = " "
  176. i += 2
  177. else:
  178. i += 1
  179. def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
  180. """_handle_long_word(chunks : [string],
  181. cur_line : [string],
  182. cur_len : int, width : int)
  183. Handle a chunk of text (most likely a word, not whitespace) that
  184. is too long to fit in any line.
  185. """
  186. # Figure out when indent is larger than the specified width, and make
  187. # sure at least one character is stripped off on every pass
  188. if width < 1:
  189. space_left = 1
  190. else:
  191. space_left = width - cur_len
  192. # If we're allowed to break long words, then do so: put as much
  193. # of the next chunk onto the current line as will fit.
  194. if self.break_long_words:
  195. cur_line.append(reversed_chunks[-1][:space_left])
  196. reversed_chunks[-1] = reversed_chunks[-1][space_left:]
  197. # Otherwise, we have to preserve the long word intact. Only add
  198. # it to the current line if there's nothing already there --
  199. # that minimizes how much we violate the width constraint.
  200. elif not cur_line:
  201. cur_line.append(reversed_chunks.pop())
  202. # If we're not allowed to break long words, and there's already
  203. # text on the current line, do nothing. Next time through the
  204. # main loop of _wrap_chunks(), we'll wind up here again, but
  205. # cur_len will be zero, so the next line will be entirely
  206. # devoted to the long word that we can't handle right now.
  207. def _wrap_chunks(self, chunks):
  208. """_wrap_chunks(chunks : [string]) -> [string]
  209. Wrap a sequence of text chunks and return a list of lines of
  210. length 'self.width' or less. (If 'break_long_words' is false,
  211. some lines may be longer than this.) Chunks correspond roughly
  212. to words and the whitespace between them: each chunk is
  213. indivisible (modulo 'break_long_words'), but a line break can
  214. come between any two chunks. Chunks should not have internal
  215. whitespace; ie. a chunk is either all whitespace or a "word".
  216. Whitespace chunks will be removed from the beginning and end of
  217. lines, but apart from that whitespace is preserved.
  218. """
  219. lines = []
  220. if self.width <= 0:
  221. raise ValueError("invalid width %r (must be > 0)" % self.width)
  222. if self.max_lines is not None:
  223. if self.max_lines > 1:
  224. indent = self.subsequent_indent
  225. else:
  226. indent = self.initial_indent
  227. if len(indent) + len(self.placeholder.lstrip()) > self.width:
  228. raise ValueError("placeholder too large for max width")
  229. # Arrange in reverse order so items can be efficiently popped
  230. # from a stack of chucks.
  231. chunks.reverse()
  232. while chunks:
  233. # Start the list of chunks that will make up the current line.
  234. # cur_len is just the length of all the chunks in cur_line.
  235. cur_line = []
  236. cur_len = 0
  237. # Figure out which static string will prefix this line.
  238. if lines:
  239. indent = self.subsequent_indent
  240. else:
  241. indent = self.initial_indent
  242. # Maximum width for this line.
  243. width = self.width - len(indent)
  244. # First chunk on line is whitespace -- drop it, unless this
  245. # is the very beginning of the text (ie. no lines started yet).
  246. if self.drop_whitespace and chunks[-1].strip() == '' and lines:
  247. del chunks[-1]
  248. while chunks:
  249. l = len(chunks[-1])
  250. # Can at least squeeze this chunk onto the current line.
  251. if cur_len + l <= width:
  252. cur_line.append(chunks.pop())
  253. cur_len += l
  254. # Nope, this line is full.
  255. else:
  256. break
  257. # The current line is full, and the next chunk is too big to
  258. # fit on *any* line (not just this one).
  259. if chunks and len(chunks[-1]) > width:
  260. self._handle_long_word(chunks, cur_line, cur_len, width)
  261. cur_len = sum(map(len, cur_line))
  262. # If the last chunk on this line is all whitespace, drop it.
  263. if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
  264. cur_len -= len(cur_line[-1])
  265. del cur_line[-1]
  266. if cur_line:
  267. if (self.max_lines is None or
  268. len(lines) + 1 < self.max_lines or
  269. (not chunks or
  270. self.drop_whitespace and
  271. len(chunks) == 1 and
  272. not chunks[0].strip()) and cur_len <= width):
  273. # Convert current line back to a string and store it in
  274. # list of all lines (return value).
  275. lines.append(indent + ''.join(cur_line))
  276. else:
  277. while cur_line:
  278. if (cur_line[-1].strip() and
  279. cur_len + len(self.placeholder) <= width):
  280. cur_line.append(self.placeholder)
  281. lines.append(indent + ''.join(cur_line))
  282. break
  283. cur_len -= len(cur_line[-1])
  284. del cur_line[-1]
  285. else:
  286. if lines:
  287. prev_line = lines[-1].rstrip()
  288. if (len(prev_line) + len(self.placeholder) <=
  289. self.width):
  290. lines[-1] = prev_line + self.placeholder
  291. break
  292. lines.append(indent + self.placeholder.lstrip())
  293. break
  294. return lines
  295. def _split_chunks(self, text):
  296. text = self._munge_whitespace(text)
  297. return self._split(text)
  298. # -- Public interface ----------------------------------------------
  299. def wrap(self, text):
  300. """wrap(text : string) -> [string]
  301. Reformat the single paragraph in 'text' so it fits in lines of
  302. no more than 'self.width' columns, and return a list of wrapped
  303. lines. Tabs in 'text' are expanded with string.expandtabs(),
  304. and all other whitespace characters (including newline) are
  305. converted to space.
  306. """
  307. chunks = self._split_chunks(text)
  308. if self.fix_sentence_endings:
  309. self._fix_sentence_endings(chunks)
  310. return self._wrap_chunks(chunks)
  311. def fill(self, text):
  312. """fill(text : string) -> string
  313. Reformat the single paragraph in 'text' to fit in lines of no
  314. more than 'self.width' columns, and return a new string
  315. containing the entire wrapped paragraph.
  316. """
  317. return "\n".join(self.wrap(text))
  318. # -- Convenience interface ---------------------------------------------
  319. def wrap(text, width=70, **kwargs):
  320. """Wrap a single paragraph of text, returning a list of wrapped lines.
  321. Reformat the single paragraph in 'text' so it fits in lines of no
  322. more than 'width' columns, and return a list of wrapped lines. By
  323. default, tabs in 'text' are expanded with string.expandtabs(), and
  324. all other whitespace characters (including newline) are converted to
  325. space. See TextWrapper class for available keyword args to customize
  326. wrapping behaviour.
  327. """
  328. w = TextWrapper(width=width, **kwargs)
  329. return w.wrap(text)
  330. def fill(text, width=70, **kwargs):
  331. """Fill a single paragraph of text, returning a new string.
  332. Reformat the single paragraph in 'text' to fit in lines of no more
  333. than 'width' columns, and return a new string containing the entire
  334. wrapped paragraph. As with wrap(), tabs are expanded and other
  335. whitespace characters converted to space. See TextWrapper class for
  336. available keyword args to customize wrapping behaviour.
  337. """
  338. w = TextWrapper(width=width, **kwargs)
  339. return w.fill(text)
  340. def shorten(text, width, **kwargs):
  341. """Collapse and truncate the given text to fit in the given width.
  342. The text first has its whitespace collapsed. If it then fits in
  343. the *width*, it is returned as is. Otherwise, as many words
  344. as possible are joined and then the placeholder is appended::
  345. >>> textwrap.shorten("Hello world!", width=12)
  346. 'Hello world!'
  347. >>> textwrap.shorten("Hello world!", width=11)
  348. 'Hello [...]'
  349. """
  350. w = TextWrapper(width=width, max_lines=1, **kwargs)
  351. return w.fill(' '.join(text.strip().split()))
  352. # -- Loosely related functionality -------------------------------------
  353. _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
  354. _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
  355. def dedent(text):
  356. """Remove any common leading whitespace from every line in `text`.
  357. This can be used to make triple-quoted strings line up with the left
  358. edge of the display, while still presenting them in the source code
  359. in indented form.
  360. Note that tabs and spaces are both treated as whitespace, but they
  361. are not equal: the lines " hello" and "\\thello" are
  362. considered to have no common leading whitespace.
  363. Entirely blank lines are normalized to a newline character.
  364. """
  365. # Look for the longest leading string of spaces and tabs common to
  366. # all lines.
  367. margin = None
  368. text = _whitespace_only_re.sub('', text)
  369. indents = _leading_whitespace_re.findall(text)
  370. for indent in indents:
  371. if margin is None:
  372. margin = indent
  373. # Current line more deeply indented than previous winner:
  374. # no change (previous winner is still on top).
  375. elif indent.startswith(margin):
  376. pass
  377. # Current line consistent with and no deeper than previous winner:
  378. # it's the new winner.
  379. elif margin.startswith(indent):
  380. margin = indent
  381. # Find the largest common whitespace between current line and previous
  382. # winner.
  383. else:
  384. for i, (x, y) in enumerate(zip(margin, indent)):
  385. if x != y:
  386. margin = margin[:i]
  387. break
  388. # sanity check (testing/debugging only)
  389. if 0 and margin:
  390. for line in text.split("\n"):
  391. assert not line or line.startswith(margin), \
  392. "line = %r, margin = %r" % (line, margin)
  393. if margin:
  394. text = re.sub(r'(?m)^' + margin, '', text)
  395. return text
  396. def indent(text, prefix, predicate=None):
  397. """Adds 'prefix' to the beginning of selected lines in 'text'.
  398. If 'predicate' is provided, 'prefix' will only be added to the lines
  399. where 'predicate(line)' is True. If 'predicate' is not provided,
  400. it will default to adding 'prefix' to all non-empty lines that do not
  401. consist solely of whitespace characters.
  402. """
  403. if predicate is None:
  404. def predicate(line):
  405. return line.strip()
  406. def prefixed_lines():
  407. for line in text.splitlines(True):
  408. yield (prefix + line if predicate(line) else line)
  409. return ''.join(prefixed_lines())
  410. if __name__ == "__main__":
  411. #print dedent("\tfoo\n\tbar")
  412. #print dedent(" \thello there\n \t how are you?")
  413. print(dedent("Hello there.\n This is indented."))