blob: 3fc14f0c8c38a7c0c208a7ec7b5e1fe489b0ded5 [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
Greg Ward4c6c9c42003-02-03 14:46:57 +000012__all__ = ['TextWrapper', 'wrap', 'fill']
13
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'.
Guido van Rossumd8faa362007-04-27 19:54:29 +000058 drop_whitespace (default: true)
59 Drop leading and trailing whitespace from lines.
Greg Ward00935822002-06-07 21:43:37 +000060 """
61
Greg Ward4c6c9c42003-02-03 14:46:57 +000062 whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
Greg Ward00935822002-06-07 21:43:37 +000063
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
77 r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words
78 r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
Greg Ward00935822002-06-07 21:43:37 +000079
Guido van Rossum9264ecd2007-08-11 16:40:13 +000080 # XXX this is not locale-aware
81 sentence_end_re = re.compile(r'[a-z]' # lowercase letter
Greg Ward9b4864e2002-06-07 22:04:15 +000082 r'[\.\!\?]' # sentence-ending punct.
83 r'[\"\']?' # optional end-of-quote
Guido van Rossum9264ecd2007-08-11 16:40:13 +000084 )
Greg Ward62e4f3b2002-06-07 21:56:16 +000085
Greg Ward00935822002-06-07 21:43:37 +000086
Greg Wardf0ba7642004-05-13 01:53:10 +000087 def __init__(self,
88 width=70,
89 initial_indent="",
90 subsequent_indent="",
91 expand_tabs=True,
92 replace_whitespace=True,
93 fix_sentence_endings=False,
Guido van Rossumd8faa362007-04-27 19:54:29 +000094 break_long_words=True,
95 drop_whitespace=True):
Greg Wardd34c9592002-06-10 20:26:02 +000096 self.width = width
Greg Ward62080be2002-06-10 21:37:12 +000097 self.initial_indent = initial_indent
98 self.subsequent_indent = subsequent_indent
Greg Ward47df99d2002-06-09 00:22:07 +000099 self.expand_tabs = expand_tabs
100 self.replace_whitespace = replace_whitespace
101 self.fix_sentence_endings = fix_sentence_endings
102 self.break_long_words = break_long_words
Guido van Rossumd8faa362007-04-27 19:54:29 +0000103 self.drop_whitespace = drop_whitespace
Tim Petersc411dba2002-07-16 21:35:23 +0000104
Greg Ward00935822002-06-07 21:43:37 +0000105
106 # -- Private methods -----------------------------------------------
107 # (possibly useful for subclasses to override)
108
Greg Wardcb320eb2002-06-07 22:32:15 +0000109 def _munge_whitespace(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000110 """_munge_whitespace(text : string) -> string
111
112 Munge whitespace in text: expand tabs and convert all other
113 whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
114 becomes " foo bar baz".
115 """
116 if self.expand_tabs:
117 text = text.expandtabs()
118 if self.replace_whitespace:
Walter Dörwaldaef90f42007-05-12 13:13:55 +0000119 if isinstance(text, str8):
Greg Ward2e745412002-12-09 16:23:08 +0000120 text = text.translate(self.whitespace_trans)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000121 elif isinstance(text, str):
Greg Ward2e745412002-12-09 16:23:08 +0000122 text = text.translate(self.unicode_whitespace_trans)
Greg Ward00935822002-06-07 21:43:37 +0000123 return text
124
125
Greg Wardcb320eb2002-06-07 22:32:15 +0000126 def _split(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000127 """_split(text : string) -> [string]
128
129 Split the text to wrap into indivisible chunks. Chunks are
130 not quite the same as words; see wrap_chunks() for full
131 details. As an example, the text
132 Look, goof-ball -- use the -b option!
133 breaks into the following chunks:
134 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
135 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
136 """
137 chunks = self.wordsep_re.split(text)
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000138 chunks = [c for c in chunks if c]
Greg Ward00935822002-06-07 21:43:37 +0000139 return chunks
140
Greg Wardcb320eb2002-06-07 22:32:15 +0000141 def _fix_sentence_endings(self, chunks):
Greg Ward00935822002-06-07 21:43:37 +0000142 """_fix_sentence_endings(chunks : [string])
143
144 Correct for sentence endings buried in 'chunks'. Eg. when the
145 original text contains "... foo.\nBar ...", munge_whitespace()
146 and split() will convert that to [..., "foo.", " ", "Bar", ...]
147 which has one too few spaces; this method simply changes the one
148 space to two.
149 """
150 i = 0
Greg Ward9b4864e2002-06-07 22:04:15 +0000151 pat = self.sentence_end_re
Greg Ward00935822002-06-07 21:43:37 +0000152 while i < len(chunks)-1:
Greg Ward9b4864e2002-06-07 22:04:15 +0000153 if chunks[i+1] == " " and pat.search(chunks[i]):
Greg Ward00935822002-06-07 21:43:37 +0000154 chunks[i+1] = " "
155 i += 2
156 else:
157 i += 1
158
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000159 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
Greg Ward00935822002-06-07 21:43:37 +0000160 """_handle_long_word(chunks : [string],
161 cur_line : [string],
Greg Ward62080be2002-06-10 21:37:12 +0000162 cur_len : int, width : int)
Greg Ward00935822002-06-07 21:43:37 +0000163
164 Handle a chunk of text (most likely a word, not whitespace) that
165 is too long to fit in any line.
166 """
Raymond Hettingerc11dbcd2003-08-30 14:43:55 +0000167 space_left = max(width - cur_len, 1)
Greg Ward00935822002-06-07 21:43:37 +0000168
169 # If we're allowed to break long words, then do so: put as much
170 # of the next chunk onto the current line as will fit.
171 if self.break_long_words:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000172 cur_line.append(reversed_chunks[-1][:space_left])
173 reversed_chunks[-1] = reversed_chunks[-1][space_left:]
Greg Ward00935822002-06-07 21:43:37 +0000174
175 # Otherwise, we have to preserve the long word intact. Only add
176 # it to the current line if there's nothing already there --
177 # that minimizes how much we violate the width constraint.
178 elif not cur_line:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000179 cur_line.append(reversed_chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000180
181 # If we're not allowed to break long words, and there's already
182 # text on the current line, do nothing. Next time through the
183 # main loop of _wrap_chunks(), we'll wind up here again, but
184 # cur_len will be zero, so the next line will be entirely
185 # devoted to the long word that we can't handle right now.
186
Greg Wardd34c9592002-06-10 20:26:02 +0000187 def _wrap_chunks(self, chunks):
188 """_wrap_chunks(chunks : [string]) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000189
190 Wrap a sequence of text chunks and return a list of lines of
Greg Wardd34c9592002-06-10 20:26:02 +0000191 length 'self.width' or less. (If 'break_long_words' is false,
192 some lines may be longer than this.) Chunks correspond roughly
193 to words and the whitespace between them: each chunk is
194 indivisible (modulo 'break_long_words'), but a line break can
195 come between any two chunks. Chunks should not have internal
196 whitespace; ie. a chunk is either all whitespace or a "word".
197 Whitespace chunks will be removed from the beginning and end of
198 lines, but apart from that whitespace is preserved.
Greg Ward00935822002-06-07 21:43:37 +0000199 """
200 lines = []
Greg Ward21820cd2003-05-07 00:55:35 +0000201 if self.width <= 0:
202 raise ValueError("invalid width %r (must be > 0)" % self.width)
Greg Ward00935822002-06-07 21:43:37 +0000203
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000204 # Arrange in reverse order so items can be efficiently popped
205 # from a stack of chucks.
206 chunks.reverse()
207
Greg Ward00935822002-06-07 21:43:37 +0000208 while chunks:
209
Greg Ward62080be2002-06-10 21:37:12 +0000210 # Start the list of chunks that will make up the current line.
211 # cur_len is just the length of all the chunks in cur_line.
212 cur_line = []
213 cur_len = 0
214
215 # Figure out which static string will prefix this line.
216 if lines:
217 indent = self.subsequent_indent
218 else:
219 indent = self.initial_indent
220
221 # Maximum width for this line.
222 width = self.width - len(indent)
Greg Ward00935822002-06-07 21:43:37 +0000223
Greg Wardab73d462002-12-09 16:26:05 +0000224 # First chunk on line is whitespace -- drop it, unless this
225 # is the very beginning of the text (ie. no lines started yet).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000227 del chunks[-1]
Greg Ward00935822002-06-07 21:43:37 +0000228
229 while chunks:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000230 l = len(chunks[-1])
Greg Ward00935822002-06-07 21:43:37 +0000231
232 # Can at least squeeze this chunk onto the current line.
233 if cur_len + l <= width:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000234 cur_line.append(chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000235 cur_len += l
236
237 # Nope, this line is full.
238 else:
239 break
240
241 # The current line is full, and the next chunk is too big to
Tim Petersc411dba2002-07-16 21:35:23 +0000242 # fit on *any* line (not just this one).
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000243 if chunks and len(chunks[-1]) > width:
Greg Ward62080be2002-06-10 21:37:12 +0000244 self._handle_long_word(chunks, cur_line, cur_len, width)
Greg Ward00935822002-06-07 21:43:37 +0000245
246 # If the last chunk on this line is all whitespace, drop it.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247 if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
Greg Ward00935822002-06-07 21:43:37 +0000248 del cur_line[-1]
249
250 # Convert current line back to a string and store it in list
251 # of all lines (return value).
252 if cur_line:
Greg Ward62080be2002-06-10 21:37:12 +0000253 lines.append(indent + ''.join(cur_line))
Greg Ward00935822002-06-07 21:43:37 +0000254
255 return lines
256
257
258 # -- Public interface ----------------------------------------------
259
Greg Wardd34c9592002-06-10 20:26:02 +0000260 def wrap(self, text):
261 """wrap(text : string) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000262
Greg Warde807e572002-07-04 14:51:49 +0000263 Reformat the single paragraph in 'text' so it fits in lines of
264 no more than 'self.width' columns, and return a list of wrapped
265 lines. Tabs in 'text' are expanded with string.expandtabs(),
266 and all other whitespace characters (including newline) are
267 converted to space.
Greg Ward00935822002-06-07 21:43:37 +0000268 """
269 text = self._munge_whitespace(text)
Greg Ward00935822002-06-07 21:43:37 +0000270 chunks = self._split(text)
Greg Ward62e4f3b2002-06-07 21:56:16 +0000271 if self.fix_sentence_endings:
272 self._fix_sentence_endings(chunks)
Greg Wardd34c9592002-06-10 20:26:02 +0000273 return self._wrap_chunks(chunks)
Greg Ward00935822002-06-07 21:43:37 +0000274
Greg Ward62080be2002-06-10 21:37:12 +0000275 def fill(self, text):
276 """fill(text : string) -> string
Greg Ward00935822002-06-07 21:43:37 +0000277
Greg Warde807e572002-07-04 14:51:49 +0000278 Reformat the single paragraph in 'text' to fit in lines of no
279 more than 'self.width' columns, and return a new string
280 containing the entire wrapped paragraph.
Greg Ward00935822002-06-07 21:43:37 +0000281 """
Greg Ward62080be2002-06-10 21:37:12 +0000282 return "\n".join(self.wrap(text))
Greg Ward00935822002-06-07 21:43:37 +0000283
284
Greg Warde807e572002-07-04 14:51:49 +0000285# -- Convenience interface ---------------------------------------------
Greg Ward00935822002-06-07 21:43:37 +0000286
Greg Wardcf02ac62002-06-10 20:36:07 +0000287def wrap(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000288 """Wrap a single paragraph of text, returning a list of wrapped lines.
289
290 Reformat the single paragraph in 'text' so it fits in lines of no
291 more than 'width' columns, and return a list of wrapped lines. By
292 default, tabs in 'text' are expanded with string.expandtabs(), and
293 all other whitespace characters (including newline) are converted to
294 space. See TextWrapper class for available keyword args to customize
295 wrapping behaviour.
296 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000297 w = TextWrapper(width=width, **kwargs)
298 return w.wrap(text)
Greg Ward00935822002-06-07 21:43:37 +0000299
Greg Ward62080be2002-06-10 21:37:12 +0000300def fill(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000301 """Fill a single paragraph of text, returning a new string.
302
303 Reformat the single paragraph in 'text' to fit in lines of no more
304 than 'width' columns, and return a new string containing the entire
305 wrapped paragraph. As with wrap(), tabs are expanded and other
306 whitespace characters converted to space. See TextWrapper class for
307 available keyword args to customize wrapping behaviour.
308 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000309 w = TextWrapper(width=width, **kwargs)
Greg Ward62080be2002-06-10 21:37:12 +0000310 return w.fill(text)
Greg Ward478cd482003-05-08 01:58:05 +0000311
312
313# -- Loosely related functionality -------------------------------------
314
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000315_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
316_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
317
Greg Ward478cd482003-05-08 01:58:05 +0000318def dedent(text):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000319 """Remove any common leading whitespace from every line in `text`.
Greg Ward478cd482003-05-08 01:58:05 +0000320
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000321 This can be used to make triple-quoted strings line up with the left
322 edge of the display, while still presenting them in the source code
323 in indented form.
Greg Ward478cd482003-05-08 01:58:05 +0000324
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000325 Note that tabs and spaces are both treated as whitespace, but they
326 are not equal: the lines " hello" and "\thello" are
327 considered to have no common leading whitespace. (This behaviour is
328 new in Python 2.5; older versions of this module incorrectly
329 expanded tabs before searching for common leading whitespace.)
Greg Ward478cd482003-05-08 01:58:05 +0000330 """
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000331 # Look for the longest leading string of spaces and tabs common to
332 # all lines.
Greg Ward478cd482003-05-08 01:58:05 +0000333 margin = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000334 text = _whitespace_only_re.sub('', text)
335 indents = _leading_whitespace_re.findall(text)
336 for indent in indents:
Greg Ward478cd482003-05-08 01:58:05 +0000337 if margin is None:
338 margin = indent
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000339
340 # Current line more deeply indented than previous winner:
341 # no change (previous winner is still on top).
342 elif indent.startswith(margin):
343 pass
344
345 # Current line consistent with and no deeper than previous winner:
346 # it's the new winner.
347 elif margin.startswith(indent):
348 margin = indent
349
350 # Current line and previous winner have no common whitespace:
351 # there is no margin.
Greg Ward478cd482003-05-08 01:58:05 +0000352 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000353 margin = ""
354 break
Greg Ward478cd482003-05-08 01:58:05 +0000355
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000356 # sanity check (testing/debugging only)
357 if 0 and margin:
358 for line in text.split("\n"):
359 assert not line or line.startswith(margin), \
360 "line = %r, margin = %r" % (line, margin)
Greg Ward478cd482003-05-08 01:58:05 +0000361
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000362 if margin:
363 text = re.sub(r'(?m)^' + margin, '', text)
364 return text
365
366if __name__ == "__main__":
367 #print dedent("\tfoo\n\tbar")
368 #print dedent(" \thello there\n \t how are you?")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000369 print(dedent("Hello there.\n This is indented."))