blob: dfb400548bd4d77723e25bad9eb73a0f597d46b3 [file] [log] [blame]
Greg Warde807e572002-07-04 14:51:49 +00001"""Text wrapping and filling.
Greg Ward00935822002-06-07 21:43:37 +00002"""
3
Greg Ward78cc0512002-10-13 19:23:18 +00004# Copyright (C) 1999-2001 Gregory P. Ward.
Greg Ward523008c2003-06-15 15:37:18 +00005# Copyright (C) 2002, 2003 Python Software Foundation.
Greg Ward698d9f02002-06-07 22:40:23 +00006# Written by Greg Ward <gward@python.net>
7
Greg Ward00935822002-06-07 21:43:37 +00008import string, re
9
Georg Brandlaf265f42008-12-07 15:06:20 +000010__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent']
Greg Ward4c6c9c42003-02-03 14:46:57 +000011
Greg Wardafd44de2002-12-12 17:24:35 +000012# Hardcode the recognized whitespace characters to the US-ASCII
13# whitespace characters. The main reason for doing this is that in
14# ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales
15# that character winds up in string.whitespace. Respecting
16# string.whitespace in those cases would 1) make textwrap treat 0xa0 the
17# same as any other whitespace char, which is clearly wrong (it's a
18# *non-breaking* space), 2) possibly cause problems with Unicode,
19# since 0xa0 is not in range(128).
Greg Ward4c6c9c42003-02-03 14:46:57 +000020_whitespace = '\t\n\x0b\x0c\r '
Greg Wardafd44de2002-12-12 17:24:35 +000021
Greg Ward00935822002-06-07 21:43:37 +000022class TextWrapper:
23 """
24 Object for wrapping/filling text. The public interface consists of
25 the wrap() and fill() methods; the other methods are just there for
26 subclasses to override in order to tweak the default behaviour.
27 If you want to completely replace the main wrapping algorithm,
28 you'll probably have to override _wrap_chunks().
29
Greg Wardd34c9592002-06-10 20:26:02 +000030 Several instance attributes control various aspects of wrapping:
31 width (default: 70)
32 the maximum width of wrapped lines (unless break_long_words
33 is false)
Greg Ward62080be2002-06-10 21:37:12 +000034 initial_indent (default: "")
35 string that will be prepended to the first line of wrapped
36 output. Counts towards the line's width.
37 subsequent_indent (default: "")
38 string that will be prepended to all lines save the first
39 of wrapped output; also counts towards each line's width.
Greg Ward62e4f3b2002-06-07 21:56:16 +000040 expand_tabs (default: true)
41 Expand tabs in input text to spaces before further processing.
42 Each tab will become 1 .. 8 spaces, depending on its position in
43 its line. If false, each tab is treated as a single character.
44 replace_whitespace (default: true)
45 Replace all whitespace characters in the input text by spaces
46 after tab expansion. Note that if expand_tabs is false and
47 replace_whitespace is true, every tab will be converted to a
48 single space!
49 fix_sentence_endings (default: false)
50 Ensure that sentence-ending punctuation is always followed
Andrew M. Kuchlinga2ecabe2003-02-14 01:14:15 +000051 by two spaces. Off by default because the algorithm is
Greg Ward62e4f3b2002-06-07 21:56:16 +000052 (unavoidably) imperfect.
53 break_long_words (default: true)
Greg Wardd34c9592002-06-10 20:26:02 +000054 Break words longer than 'width'. If false, those words will not
55 be broken, and some lines might be longer than 'width'.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000056 break_on_hyphens (default: true)
57 Allow breaking hyphenated words. If true, wrapping will occur
58 preferably on whitespaces and right after hyphens part of
59 compound words.
Guido van Rossumd8faa362007-04-27 19:54:29 +000060 drop_whitespace (default: true)
61 Drop leading and trailing whitespace from lines.
Greg Ward00935822002-06-07 21:43:37 +000062 """
63
Greg Ward2e745412002-12-09 16:23:08 +000064 unicode_whitespace_trans = {}
Guido van Rossumef87d6e2007-05-02 19:09:54 +000065 uspace = ord(' ')
Guido van Rossumc1f779c2007-07-03 08:25:58 +000066 for x in _whitespace:
67 unicode_whitespace_trans[ord(x)] = uspace
Greg Ward2e745412002-12-09 16:23:08 +000068
Tim Petersc411dba2002-07-16 21:35:23 +000069 # This funky little regex is just the trick for splitting
Greg Ward00935822002-06-07 21:43:37 +000070 # text up into word-wrappable chunks. E.g.
71 # "Hello there -- you goof-ball, use the -b option!"
72 # splits into
73 # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
74 # (after stripping out empty strings).
Greg Ward40407942005-03-05 02:53:17 +000075 wordsep_re = re.compile(
76 r'(\s+|' # any whitespace
Antoine Pitrou7c59bc62008-12-13 23:20:54 +000077 r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words
Greg Ward40407942005-03-05 02:53:17 +000078 r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
Greg Ward00935822002-06-07 21:43:37 +000079
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000080 # 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
86 # XXX this is not locale- or charset-aware -- string.lowercase
87 # is US-ASCII only (and therefore English-only)
Guido van Rossum9264ecd2007-08-11 16:40:13 +000088 sentence_end_re = re.compile(r'[a-z]' # lowercase letter
Greg Ward9b4864e2002-06-07 22:04:15 +000089 r'[\.\!\?]' # sentence-ending punct.
90 r'[\"\']?' # optional end-of-quote
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000091 r'\Z') # end of chunk
Greg Ward62e4f3b2002-06-07 21:56:16 +000092
Greg Ward00935822002-06-07 21:43:37 +000093
Greg Wardf0ba7642004-05-13 01:53:10 +000094 def __init__(self,
95 width=70,
96 initial_indent="",
97 subsequent_indent="",
98 expand_tabs=True,
99 replace_whitespace=True,
100 fix_sentence_endings=False,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000101 break_long_words=True,
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000102 drop_whitespace=True,
103 break_on_hyphens=True):
Greg Wardd34c9592002-06-10 20:26:02 +0000104 self.width = width
Greg Ward62080be2002-06-10 21:37:12 +0000105 self.initial_indent = initial_indent
106 self.subsequent_indent = subsequent_indent
Greg Ward47df99d2002-06-09 00:22:07 +0000107 self.expand_tabs = expand_tabs
108 self.replace_whitespace = replace_whitespace
109 self.fix_sentence_endings = fix_sentence_endings
110 self.break_long_words = break_long_words
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111 self.drop_whitespace = drop_whitespace
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000112 self.break_on_hyphens = break_on_hyphens
Tim Petersc411dba2002-07-16 21:35:23 +0000113
Greg Ward00935822002-06-07 21:43:37 +0000114
115 # -- Private methods -----------------------------------------------
116 # (possibly useful for subclasses to override)
117
Greg Wardcb320eb2002-06-07 22:32:15 +0000118 def _munge_whitespace(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000119 """_munge_whitespace(text : string) -> string
120
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:
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000128 text = text.translate(self.unicode_whitespace_trans)
Greg Ward00935822002-06-07 21:43:37 +0000129 return text
130
131
Greg Wardcb320eb2002-06-07 22:32:15 +0000132 def _split(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000133 """_split(text : string) -> [string]
134
135 Split the text to wrap into indivisible chunks. Chunks are
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000136 not quite the same as words; see _wrap_chunks() for full
Greg Ward00935822002-06-07 21:43:37 +0000137 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!'
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000142 if break_on_hyphens is True, or in:
143 'Look,', ' ', 'goof-ball', ' ', '--', ' ',
144 'use', ' ', 'the', ' ', '-b', ' ', option!'
145 otherwise.
Greg Ward00935822002-06-07 21:43:37 +0000146 """
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000147 if self.break_on_hyphens is True:
148 chunks = self.wordsep_re.split(text)
149 else:
150 chunks = self.wordsep_simple_re.split(text)
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000151 chunks = [c for c in chunks if c]
Greg Ward00935822002-06-07 21:43:37 +0000152 return chunks
153
Greg Wardcb320eb2002-06-07 22:32:15 +0000154 def _fix_sentence_endings(self, chunks):
Greg Ward00935822002-06-07 21:43:37 +0000155 """_fix_sentence_endings(chunks : [string])
156
157 Correct for sentence endings buried in 'chunks'. Eg. when the
158 original text contains "... foo.\nBar ...", munge_whitespace()
159 and split() will convert that to [..., "foo.", " ", "Bar", ...]
160 which has one too few spaces; this method simply changes the one
161 space to two.
162 """
163 i = 0
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000164 patsearch = self.sentence_end_re.search
Greg Ward00935822002-06-07 21:43:37 +0000165 while i < len(chunks)-1:
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000166 if chunks[i+1] == " " and patsearch(chunks[i]):
Greg Ward00935822002-06-07 21:43:37 +0000167 chunks[i+1] = " "
168 i += 2
169 else:
170 i += 1
171
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000172 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
Greg Ward00935822002-06-07 21:43:37 +0000173 """_handle_long_word(chunks : [string],
174 cur_line : [string],
Greg Ward62080be2002-06-10 21:37:12 +0000175 cur_len : int, width : int)
Greg Ward00935822002-06-07 21:43:37 +0000176
177 Handle a chunk of text (most likely a word, not whitespace) that
178 is too long to fit in any line.
179 """
Georg Brandlfceab5a2008-01-19 20:08:23 +0000180 # Figure out when indent is larger than the specified width, and make
181 # sure at least one character is stripped off on every pass
182 if width < 1:
183 space_left = 1
184 else:
185 space_left = width - cur_len
Greg Ward00935822002-06-07 21:43:37 +0000186
187 # If we're allowed to break long words, then do so: put as much
188 # of the next chunk onto the current line as will fit.
189 if self.break_long_words:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000190 cur_line.append(reversed_chunks[-1][:space_left])
191 reversed_chunks[-1] = reversed_chunks[-1][space_left:]
Greg Ward00935822002-06-07 21:43:37 +0000192
193 # Otherwise, we have to preserve the long word intact. Only add
194 # it to the current line if there's nothing already there --
195 # that minimizes how much we violate the width constraint.
196 elif not cur_line:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000197 cur_line.append(reversed_chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000198
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
Greg Wardd34c9592002-06-10 20:26:02 +0000205 def _wrap_chunks(self, chunks):
206 """_wrap_chunks(chunks : [string]) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000207
208 Wrap a sequence of text chunks and return a list of lines of
Greg Wardd34c9592002-06-10 20:26:02 +0000209 length 'self.width' or less. (If 'break_long_words' is false,
210 some lines may be longer than this.) Chunks correspond roughly
211 to words and the whitespace between them: each chunk is
212 indivisible (modulo 'break_long_words'), but a line break can
213 come between any two chunks. Chunks should not have internal
214 whitespace; ie. a chunk is either all whitespace or a "word".
215 Whitespace chunks will be removed from the beginning and end of
216 lines, but apart from that whitespace is preserved.
Greg Ward00935822002-06-07 21:43:37 +0000217 """
218 lines = []
Greg Ward21820cd2003-05-07 00:55:35 +0000219 if self.width <= 0:
220 raise ValueError("invalid width %r (must be > 0)" % self.width)
Greg Ward00935822002-06-07 21:43:37 +0000221
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000222 # Arrange in reverse order so items can be efficiently popped
223 # from a stack of chucks.
224 chunks.reverse()
225
Greg Ward00935822002-06-07 21:43:37 +0000226 while chunks:
227
Greg Ward62080be2002-06-10 21:37:12 +0000228 # Start the list of chunks that will make up the current line.
229 # cur_len is just the length of all the chunks in cur_line.
230 cur_line = []
231 cur_len = 0
232
233 # Figure out which static string will prefix this line.
234 if lines:
235 indent = self.subsequent_indent
236 else:
237 indent = self.initial_indent
238
239 # Maximum width for this line.
240 width = self.width - len(indent)
Greg Ward00935822002-06-07 21:43:37 +0000241
Greg Wardab73d462002-12-09 16:26:05 +0000242 # First chunk on line is whitespace -- drop it, unless this
243 # is the very beginning of the text (ie. no lines started yet).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000245 del chunks[-1]
Greg Ward00935822002-06-07 21:43:37 +0000246
247 while chunks:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000248 l = len(chunks[-1])
Greg Ward00935822002-06-07 21:43:37 +0000249
250 # Can at least squeeze this chunk onto the current line.
251 if cur_len + l <= width:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000252 cur_line.append(chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000253 cur_len += l
254
255 # Nope, this line is full.
256 else:
257 break
258
259 # The current line is full, and the next chunk is too big to
Tim Petersc411dba2002-07-16 21:35:23 +0000260 # fit on *any* line (not just this one).
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000261 if chunks and len(chunks[-1]) > width:
Greg Ward62080be2002-06-10 21:37:12 +0000262 self._handle_long_word(chunks, cur_line, cur_len, width)
Greg Ward00935822002-06-07 21:43:37 +0000263
264 # If the last chunk on this line is all whitespace, drop it.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265 if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
Greg Ward00935822002-06-07 21:43:37 +0000266 del cur_line[-1]
267
268 # Convert current line back to a string and store it in list
269 # of all lines (return value).
270 if cur_line:
Greg Ward62080be2002-06-10 21:37:12 +0000271 lines.append(indent + ''.join(cur_line))
Greg Ward00935822002-06-07 21:43:37 +0000272
273 return lines
274
275
276 # -- Public interface ----------------------------------------------
277
Greg Wardd34c9592002-06-10 20:26:02 +0000278 def wrap(self, text):
279 """wrap(text : string) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000280
Greg Warde807e572002-07-04 14:51:49 +0000281 Reformat the single paragraph in 'text' so it fits in lines of
282 no more than 'self.width' columns, and return a list of wrapped
283 lines. Tabs in 'text' are expanded with string.expandtabs(),
284 and all other whitespace characters (including newline) are
285 converted to space.
Greg Ward00935822002-06-07 21:43:37 +0000286 """
287 text = self._munge_whitespace(text)
Greg Ward00935822002-06-07 21:43:37 +0000288 chunks = self._split(text)
Greg Ward62e4f3b2002-06-07 21:56:16 +0000289 if self.fix_sentence_endings:
290 self._fix_sentence_endings(chunks)
Greg Wardd34c9592002-06-10 20:26:02 +0000291 return self._wrap_chunks(chunks)
Greg Ward00935822002-06-07 21:43:37 +0000292
Greg Ward62080be2002-06-10 21:37:12 +0000293 def fill(self, text):
294 """fill(text : string) -> string
Greg Ward00935822002-06-07 21:43:37 +0000295
Greg Warde807e572002-07-04 14:51:49 +0000296 Reformat the single paragraph in 'text' to fit in lines of no
297 more than 'self.width' columns, and return a new string
298 containing the entire wrapped paragraph.
Greg Ward00935822002-06-07 21:43:37 +0000299 """
Greg Ward62080be2002-06-10 21:37:12 +0000300 return "\n".join(self.wrap(text))
Greg Ward00935822002-06-07 21:43:37 +0000301
302
Greg Warde807e572002-07-04 14:51:49 +0000303# -- Convenience interface ---------------------------------------------
Greg Ward00935822002-06-07 21:43:37 +0000304
Greg Wardcf02ac62002-06-10 20:36:07 +0000305def wrap(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000306 """Wrap a single paragraph of text, returning a list of wrapped lines.
307
308 Reformat the single paragraph in 'text' so it fits in lines of no
309 more than 'width' columns, and return a list of wrapped lines. By
310 default, tabs in 'text' are expanded with string.expandtabs(), and
311 all other whitespace characters (including newline) are converted to
312 space. See TextWrapper class for available keyword args to customize
313 wrapping behaviour.
314 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000315 w = TextWrapper(width=width, **kwargs)
316 return w.wrap(text)
Greg Ward00935822002-06-07 21:43:37 +0000317
Greg Ward62080be2002-06-10 21:37:12 +0000318def fill(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000319 """Fill a single paragraph of text, returning a new string.
320
321 Reformat the single paragraph in 'text' to fit in lines of no more
322 than 'width' columns, and return a new string containing the entire
323 wrapped paragraph. As with wrap(), tabs are expanded and other
324 whitespace characters converted to space. See TextWrapper class for
325 available keyword args to customize wrapping behaviour.
326 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000327 w = TextWrapper(width=width, **kwargs)
Greg Ward62080be2002-06-10 21:37:12 +0000328 return w.fill(text)
Greg Ward478cd482003-05-08 01:58:05 +0000329
330
331# -- Loosely related functionality -------------------------------------
332
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000333_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
334_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
335
Greg Ward478cd482003-05-08 01:58:05 +0000336def dedent(text):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000337 """Remove any common leading whitespace from every line in `text`.
Greg Ward478cd482003-05-08 01:58:05 +0000338
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000339 This can be used to make triple-quoted strings line up with the left
340 edge of the display, while still presenting them in the source code
341 in indented form.
Greg Ward478cd482003-05-08 01:58:05 +0000342
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000343 Note that tabs and spaces are both treated as whitespace, but they
344 are not equal: the lines " hello" and "\thello" are
345 considered to have no common leading whitespace. (This behaviour is
346 new in Python 2.5; older versions of this module incorrectly
347 expanded tabs before searching for common leading whitespace.)
Greg Ward478cd482003-05-08 01:58:05 +0000348 """
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000349 # Look for the longest leading string of spaces and tabs common to
350 # all lines.
Greg Ward478cd482003-05-08 01:58:05 +0000351 margin = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000352 text = _whitespace_only_re.sub('', text)
353 indents = _leading_whitespace_re.findall(text)
354 for indent in indents:
Greg Ward478cd482003-05-08 01:58:05 +0000355 if margin is None:
356 margin = indent
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000357
358 # Current line more deeply indented than previous winner:
359 # no change (previous winner is still on top).
360 elif indent.startswith(margin):
361 pass
362
363 # Current line consistent with and no deeper than previous winner:
364 # it's the new winner.
365 elif margin.startswith(indent):
366 margin = indent
367
368 # Current line and previous winner have no common whitespace:
369 # there is no margin.
Greg Ward478cd482003-05-08 01:58:05 +0000370 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000371 margin = ""
372 break
Greg Ward478cd482003-05-08 01:58:05 +0000373
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000374 # sanity check (testing/debugging only)
375 if 0 and margin:
376 for line in text.split("\n"):
377 assert not line or line.startswith(margin), \
378 "line = %r, margin = %r" % (line, margin)
Greg Ward478cd482003-05-08 01:58:05 +0000379
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000380 if margin:
381 text = re.sub(r'(?m)^' + margin, '', text)
382 return text
383
384if __name__ == "__main__":
385 #print dedent("\tfoo\n\tbar")
386 #print dedent(" \thello there\n \t how are you?")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000387 print(dedent("Hello there.\n This is indented."))