blob: 1f2e9b4a7996f606f0af71f51563c85696a556a1 [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 +00008__revision__ = "$Id$"
9
10import string, re
11
Georg Brandlaf265f42008-12-07 15:06:20 +000012__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent']
Greg Ward4c6c9c42003-02-03 14:46:57 +000013
Greg Wardafd44de2002-12-12 17:24:35 +000014# Hardcode the recognized whitespace characters to the US-ASCII
15# whitespace characters. The main reason for doing this is that in
16# ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales
17# that character winds up in string.whitespace. Respecting
18# string.whitespace in those cases would 1) make textwrap treat 0xa0 the
19# same as any other whitespace char, which is clearly wrong (it's a
20# *non-breaking* space), 2) possibly cause problems with Unicode,
21# since 0xa0 is not in range(128).
Greg Ward4c6c9c42003-02-03 14:46:57 +000022_whitespace = '\t\n\x0b\x0c\r '
Greg Wardafd44de2002-12-12 17:24:35 +000023
Greg Ward00935822002-06-07 21:43:37 +000024class TextWrapper:
25 """
26 Object for wrapping/filling text. The public interface consists of
27 the wrap() and fill() methods; the other methods are just there for
28 subclasses to override in order to tweak the default behaviour.
29 If you want to completely replace the main wrapping algorithm,
30 you'll probably have to override _wrap_chunks().
31
Greg Wardd34c9592002-06-10 20:26:02 +000032 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)
Greg Ward62080be2002-06-10 21:37:12 +000036 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.
Greg Ward62e4f3b2002-06-07 21:56:16 +000042 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
Andrew M. Kuchlinga2ecabe2003-02-14 01:14:15 +000053 by two spaces. Off by default because the algorithm is
Greg Ward62e4f3b2002-06-07 21:56:16 +000054 (unavoidably) imperfect.
55 break_long_words (default: true)
Greg Wardd34c9592002-06-10 20:26:02 +000056 Break words longer than 'width'. If false, those words will not
57 be broken, and some lines might be longer than 'width'.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000058 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.
Guido van Rossumd8faa362007-04-27 19:54:29 +000062 drop_whitespace (default: true)
63 Drop leading and trailing whitespace from lines.
Greg Ward00935822002-06-07 21:43:37 +000064 """
65
Greg Ward2e745412002-12-09 16:23:08 +000066 unicode_whitespace_trans = {}
Guido van Rossumef87d6e2007-05-02 19:09:54 +000067 uspace = ord(' ')
Guido van Rossumc1f779c2007-07-03 08:25:58 +000068 for x in _whitespace:
69 unicode_whitespace_trans[ord(x)] = uspace
Greg Ward2e745412002-12-09 16:23:08 +000070
Tim Petersc411dba2002-07-16 21:35:23 +000071 # This funky little regex is just the trick for splitting
Greg Ward00935822002-06-07 21:43:37 +000072 # text up into word-wrappable chunks. E.g.
73 # "Hello there -- you goof-ball, use the -b option!"
74 # splits into
75 # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
76 # (after stripping out empty strings).
Greg Ward40407942005-03-05 02:53:17 +000077 wordsep_re = re.compile(
78 r'(\s+|' # any whitespace
Antoine Pitrou7c59bc62008-12-13 23:20:54 +000079 r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words
Greg Ward40407942005-03-05 02:53:17 +000080 r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
Greg Ward00935822002-06-07 21:43:37 +000081
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000082 # This less funky little regex just split on recognized spaces. E.g.
83 # "Hello there -- you goof-ball, use the -b option!"
84 # splits into
85 # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
86 wordsep_simple_re = re.compile(r'(\s+)')
87
88 # XXX this is not locale- or charset-aware -- string.lowercase
89 # is US-ASCII only (and therefore English-only)
Guido van Rossum9264ecd2007-08-11 16:40:13 +000090 sentence_end_re = re.compile(r'[a-z]' # lowercase letter
Greg Ward9b4864e2002-06-07 22:04:15 +000091 r'[\.\!\?]' # sentence-ending punct.
92 r'[\"\']?' # optional end-of-quote
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000093 r'\Z') # end of chunk
Greg Ward62e4f3b2002-06-07 21:56:16 +000094
Greg Ward00935822002-06-07 21:43:37 +000095
Greg Wardf0ba7642004-05-13 01:53:10 +000096 def __init__(self,
97 width=70,
98 initial_indent="",
99 subsequent_indent="",
100 expand_tabs=True,
101 replace_whitespace=True,
102 fix_sentence_endings=False,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000103 break_long_words=True,
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000104 drop_whitespace=True,
105 break_on_hyphens=True):
Greg Wardd34c9592002-06-10 20:26:02 +0000106 self.width = width
Greg Ward62080be2002-06-10 21:37:12 +0000107 self.initial_indent = initial_indent
108 self.subsequent_indent = subsequent_indent
Greg Ward47df99d2002-06-09 00:22:07 +0000109 self.expand_tabs = expand_tabs
110 self.replace_whitespace = replace_whitespace
111 self.fix_sentence_endings = fix_sentence_endings
112 self.break_long_words = break_long_words
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113 self.drop_whitespace = drop_whitespace
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000114 self.break_on_hyphens = break_on_hyphens
Tim Petersc411dba2002-07-16 21:35:23 +0000115
Greg Ward00935822002-06-07 21:43:37 +0000116
117 # -- Private methods -----------------------------------------------
118 # (possibly useful for subclasses to override)
119
Greg Wardcb320eb2002-06-07 22:32:15 +0000120 def _munge_whitespace(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000121 """_munge_whitespace(text : string) -> string
122
123 Munge whitespace in text: expand tabs and convert all other
124 whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
125 becomes " foo bar baz".
126 """
127 if self.expand_tabs:
128 text = text.expandtabs()
129 if self.replace_whitespace:
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000130 text = text.translate(self.unicode_whitespace_trans)
Greg Ward00935822002-06-07 21:43:37 +0000131 return text
132
133
Greg Wardcb320eb2002-06-07 22:32:15 +0000134 def _split(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000135 """_split(text : string) -> [string]
136
137 Split the text to wrap into indivisible chunks. Chunks are
138 not quite the same as words; see wrap_chunks() for full
139 details. As an example, the text
140 Look, goof-ball -- use the -b option!
141 breaks into the following chunks:
142 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
143 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000144 if break_on_hyphens is True, or in:
145 'Look,', ' ', 'goof-ball', ' ', '--', ' ',
146 'use', ' ', 'the', ' ', '-b', ' ', option!'
147 otherwise.
Greg Ward00935822002-06-07 21:43:37 +0000148 """
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000149 if self.break_on_hyphens is True:
150 chunks = self.wordsep_re.split(text)
151 else:
152 chunks = self.wordsep_simple_re.split(text)
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000153 chunks = [c for c in chunks if c]
Greg Ward00935822002-06-07 21:43:37 +0000154 return chunks
155
Greg Wardcb320eb2002-06-07 22:32:15 +0000156 def _fix_sentence_endings(self, chunks):
Greg Ward00935822002-06-07 21:43:37 +0000157 """_fix_sentence_endings(chunks : [string])
158
159 Correct for sentence endings buried in 'chunks'. Eg. when the
160 original text contains "... foo.\nBar ...", munge_whitespace()
161 and split() will convert that to [..., "foo.", " ", "Bar", ...]
162 which has one too few spaces; this method simply changes the one
163 space to two.
164 """
165 i = 0
Greg Ward9b4864e2002-06-07 22:04:15 +0000166 pat = self.sentence_end_re
Greg Ward00935822002-06-07 21:43:37 +0000167 while i < len(chunks)-1:
Greg Ward9b4864e2002-06-07 22:04:15 +0000168 if chunks[i+1] == " " and pat.search(chunks[i]):
Greg Ward00935822002-06-07 21:43:37 +0000169 chunks[i+1] = " "
170 i += 2
171 else:
172 i += 1
173
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000174 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
Greg Ward00935822002-06-07 21:43:37 +0000175 """_handle_long_word(chunks : [string],
176 cur_line : [string],
Greg Ward62080be2002-06-10 21:37:12 +0000177 cur_len : int, width : int)
Greg Ward00935822002-06-07 21:43:37 +0000178
179 Handle a chunk of text (most likely a word, not whitespace) that
180 is too long to fit in any line.
181 """
Georg Brandlfceab5a2008-01-19 20:08:23 +0000182 # Figure out when indent is larger than the specified width, and make
183 # sure at least one character is stripped off on every pass
184 if width < 1:
185 space_left = 1
186 else:
187 space_left = width - cur_len
Greg Ward00935822002-06-07 21:43:37 +0000188
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:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000192 cur_line.append(reversed_chunks[-1][:space_left])
193 reversed_chunks[-1] = reversed_chunks[-1][space_left:]
Greg Ward00935822002-06-07 21:43:37 +0000194
195 # Otherwise, we have to preserve the long word intact. Only add
196 # it to the current line if there's nothing already there --
197 # that minimizes how much we violate the width constraint.
198 elif not cur_line:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000199 cur_line.append(reversed_chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000200
201 # If we're not allowed to break long words, and there's already
202 # text on the current line, do nothing. Next time through the
203 # main loop of _wrap_chunks(), we'll wind up here again, but
204 # cur_len will be zero, so the next line will be entirely
205 # devoted to the long word that we can't handle right now.
206
Greg Wardd34c9592002-06-10 20:26:02 +0000207 def _wrap_chunks(self, chunks):
208 """_wrap_chunks(chunks : [string]) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000209
210 Wrap a sequence of text chunks and return a list of lines of
Greg Wardd34c9592002-06-10 20:26:02 +0000211 length 'self.width' or less. (If 'break_long_words' is false,
212 some lines may be longer than this.) Chunks correspond roughly
213 to words and the whitespace between them: each chunk is
214 indivisible (modulo 'break_long_words'), but a line break can
215 come between any two chunks. Chunks should not have internal
216 whitespace; ie. a chunk is either all whitespace or a "word".
217 Whitespace chunks will be removed from the beginning and end of
218 lines, but apart from that whitespace is preserved.
Greg Ward00935822002-06-07 21:43:37 +0000219 """
220 lines = []
Greg Ward21820cd2003-05-07 00:55:35 +0000221 if self.width <= 0:
222 raise ValueError("invalid width %r (must be > 0)" % self.width)
Greg Ward00935822002-06-07 21:43:37 +0000223
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000224 # Arrange in reverse order so items can be efficiently popped
225 # from a stack of chucks.
226 chunks.reverse()
227
Greg Ward00935822002-06-07 21:43:37 +0000228 while chunks:
229
Greg Ward62080be2002-06-10 21:37:12 +0000230 # Start the list of chunks that will make up the current line.
231 # cur_len is just the length of all the chunks in cur_line.
232 cur_line = []
233 cur_len = 0
234
235 # Figure out which static string will prefix this line.
236 if lines:
237 indent = self.subsequent_indent
238 else:
239 indent = self.initial_indent
240
241 # Maximum width for this line.
242 width = self.width - len(indent)
Greg Ward00935822002-06-07 21:43:37 +0000243
Greg Wardab73d462002-12-09 16:26:05 +0000244 # First chunk on line is whitespace -- drop it, unless this
245 # is the very beginning of the text (ie. no lines started yet).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000247 del chunks[-1]
Greg Ward00935822002-06-07 21:43:37 +0000248
249 while chunks:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000250 l = len(chunks[-1])
Greg Ward00935822002-06-07 21:43:37 +0000251
252 # Can at least squeeze this chunk onto the current line.
253 if cur_len + l <= width:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000254 cur_line.append(chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000255 cur_len += l
256
257 # Nope, this line is full.
258 else:
259 break
260
261 # The current line is full, and the next chunk is too big to
Tim Petersc411dba2002-07-16 21:35:23 +0000262 # fit on *any* line (not just this one).
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000263 if chunks and len(chunks[-1]) > width:
Greg Ward62080be2002-06-10 21:37:12 +0000264 self._handle_long_word(chunks, cur_line, cur_len, width)
Greg Ward00935822002-06-07 21:43:37 +0000265
266 # If the last chunk on this line is all whitespace, drop it.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000267 if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
Greg Ward00935822002-06-07 21:43:37 +0000268 del cur_line[-1]
269
270 # Convert current line back to a string and store it in list
271 # of all lines (return value).
272 if cur_line:
Greg Ward62080be2002-06-10 21:37:12 +0000273 lines.append(indent + ''.join(cur_line))
Greg Ward00935822002-06-07 21:43:37 +0000274
275 return lines
276
277
278 # -- Public interface ----------------------------------------------
279
Greg Wardd34c9592002-06-10 20:26:02 +0000280 def wrap(self, text):
281 """wrap(text : string) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000282
Greg Warde807e572002-07-04 14:51:49 +0000283 Reformat the single paragraph in 'text' so it fits in lines of
284 no more than 'self.width' columns, and return a list of wrapped
285 lines. Tabs in 'text' are expanded with string.expandtabs(),
286 and all other whitespace characters (including newline) are
287 converted to space.
Greg Ward00935822002-06-07 21:43:37 +0000288 """
289 text = self._munge_whitespace(text)
Greg Ward00935822002-06-07 21:43:37 +0000290 chunks = self._split(text)
Greg Ward62e4f3b2002-06-07 21:56:16 +0000291 if self.fix_sentence_endings:
292 self._fix_sentence_endings(chunks)
Greg Wardd34c9592002-06-10 20:26:02 +0000293 return self._wrap_chunks(chunks)
Greg Ward00935822002-06-07 21:43:37 +0000294
Greg Ward62080be2002-06-10 21:37:12 +0000295 def fill(self, text):
296 """fill(text : string) -> string
Greg Ward00935822002-06-07 21:43:37 +0000297
Greg Warde807e572002-07-04 14:51:49 +0000298 Reformat the single paragraph in 'text' to fit in lines of no
299 more than 'self.width' columns, and return a new string
300 containing the entire wrapped paragraph.
Greg Ward00935822002-06-07 21:43:37 +0000301 """
Greg Ward62080be2002-06-10 21:37:12 +0000302 return "\n".join(self.wrap(text))
Greg Ward00935822002-06-07 21:43:37 +0000303
304
Greg Warde807e572002-07-04 14:51:49 +0000305# -- Convenience interface ---------------------------------------------
Greg Ward00935822002-06-07 21:43:37 +0000306
Greg Wardcf02ac62002-06-10 20:36:07 +0000307def wrap(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000308 """Wrap a single paragraph of text, returning a list of wrapped lines.
309
310 Reformat the single paragraph in 'text' so it fits in lines of no
311 more than 'width' columns, and return a list of wrapped lines. By
312 default, tabs in 'text' are expanded with string.expandtabs(), and
313 all other whitespace characters (including newline) are converted to
314 space. See TextWrapper class for available keyword args to customize
315 wrapping behaviour.
316 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000317 w = TextWrapper(width=width, **kwargs)
318 return w.wrap(text)
Greg Ward00935822002-06-07 21:43:37 +0000319
Greg Ward62080be2002-06-10 21:37:12 +0000320def fill(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000321 """Fill a single paragraph of text, returning a new string.
322
323 Reformat the single paragraph in 'text' to fit in lines of no more
324 than 'width' columns, and return a new string containing the entire
325 wrapped paragraph. As with wrap(), tabs are expanded and other
326 whitespace characters converted to space. See TextWrapper class for
327 available keyword args to customize wrapping behaviour.
328 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000329 w = TextWrapper(width=width, **kwargs)
Greg Ward62080be2002-06-10 21:37:12 +0000330 return w.fill(text)
Greg Ward478cd482003-05-08 01:58:05 +0000331
332
333# -- Loosely related functionality -------------------------------------
334
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000335_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
336_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
337
Greg Ward478cd482003-05-08 01:58:05 +0000338def dedent(text):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000339 """Remove any common leading whitespace from every line in `text`.
Greg Ward478cd482003-05-08 01:58:05 +0000340
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000341 This can be used to make triple-quoted strings line up with the left
342 edge of the display, while still presenting them in the source code
343 in indented form.
Greg Ward478cd482003-05-08 01:58:05 +0000344
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000345 Note that tabs and spaces are both treated as whitespace, but they
346 are not equal: the lines " hello" and "\thello" are
347 considered to have no common leading whitespace. (This behaviour is
348 new in Python 2.5; older versions of this module incorrectly
349 expanded tabs before searching for common leading whitespace.)
Greg Ward478cd482003-05-08 01:58:05 +0000350 """
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000351 # Look for the longest leading string of spaces and tabs common to
352 # all lines.
Greg Ward478cd482003-05-08 01:58:05 +0000353 margin = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000354 text = _whitespace_only_re.sub('', text)
355 indents = _leading_whitespace_re.findall(text)
356 for indent in indents:
Greg Ward478cd482003-05-08 01:58:05 +0000357 if margin is None:
358 margin = indent
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000359
360 # Current line more deeply indented than previous winner:
361 # no change (previous winner is still on top).
362 elif indent.startswith(margin):
363 pass
364
365 # Current line consistent with and no deeper than previous winner:
366 # it's the new winner.
367 elif margin.startswith(indent):
368 margin = indent
369
370 # Current line and previous winner have no common whitespace:
371 # there is no margin.
Greg Ward478cd482003-05-08 01:58:05 +0000372 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000373 margin = ""
374 break
Greg Ward478cd482003-05-08 01:58:05 +0000375
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000376 # sanity check (testing/debugging only)
377 if 0 and margin:
378 for line in text.split("\n"):
379 assert not line or line.startswith(margin), \
380 "line = %r, margin = %r" % (line, margin)
Greg Ward478cd482003-05-08 01:58:05 +0000381
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000382 if margin:
383 text = re.sub(r'(?m)^' + margin, '', text)
384 return text
385
386if __name__ == "__main__":
387 #print dedent("\tfoo\n\tbar")
388 #print dedent(" \thello there\n \t how are you?")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000389 print(dedent("Hello there.\n This is indented."))