blob: 03b4ea8273e2104f70b181ce577af87fe36908db [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 Ward523008c2003-06-15 15:37:18 +000012# Do the right thing with boolean values for all known Python versions
13# (so this module can be copied to projects that don't depend on Python
14# 2.3, e.g. Optik and Docutils).
15try:
16 True, False
17except NameError:
18 (True, False) = (1, 0)
19
Greg Ward4c6c9c42003-02-03 14:46:57 +000020__all__ = ['TextWrapper', 'wrap', 'fill']
21
Greg Wardafd44de2002-12-12 17:24:35 +000022# Hardcode the recognized whitespace characters to the US-ASCII
23# whitespace characters. The main reason for doing this is that in
24# ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales
25# that character winds up in string.whitespace. Respecting
26# string.whitespace in those cases would 1) make textwrap treat 0xa0 the
27# same as any other whitespace char, which is clearly wrong (it's a
28# *non-breaking* space), 2) possibly cause problems with Unicode,
29# since 0xa0 is not in range(128).
Greg Ward4c6c9c42003-02-03 14:46:57 +000030_whitespace = '\t\n\x0b\x0c\r '
Greg Wardafd44de2002-12-12 17:24:35 +000031
Greg Ward00935822002-06-07 21:43:37 +000032class TextWrapper:
33 """
34 Object for wrapping/filling text. The public interface consists of
35 the wrap() and fill() methods; the other methods are just there for
36 subclasses to override in order to tweak the default behaviour.
37 If you want to completely replace the main wrapping algorithm,
38 you'll probably have to override _wrap_chunks().
39
Greg Wardd34c9592002-06-10 20:26:02 +000040 Several instance attributes control various aspects of wrapping:
41 width (default: 70)
42 the maximum width of wrapped lines (unless break_long_words
43 is false)
Greg Ward62080be2002-06-10 21:37:12 +000044 initial_indent (default: "")
45 string that will be prepended to the first line of wrapped
46 output. Counts towards the line's width.
47 subsequent_indent (default: "")
48 string that will be prepended to all lines save the first
49 of wrapped output; also counts towards each line's width.
Greg Ward62e4f3b2002-06-07 21:56:16 +000050 expand_tabs (default: true)
51 Expand tabs in input text to spaces before further processing.
52 Each tab will become 1 .. 8 spaces, depending on its position in
53 its line. If false, each tab is treated as a single character.
54 replace_whitespace (default: true)
55 Replace all whitespace characters in the input text by spaces
56 after tab expansion. Note that if expand_tabs is false and
57 replace_whitespace is true, every tab will be converted to a
58 single space!
59 fix_sentence_endings (default: false)
60 Ensure that sentence-ending punctuation is always followed
Andrew M. Kuchlinga2ecabe2003-02-14 01:14:15 +000061 by two spaces. Off by default because the algorithm is
Greg Ward62e4f3b2002-06-07 21:56:16 +000062 (unavoidably) imperfect.
63 break_long_words (default: true)
Greg Wardd34c9592002-06-10 20:26:02 +000064 Break words longer than 'width'. If false, those words will not
65 be broken, and some lines might be longer than 'width'.
Guido van Rossumd8faa362007-04-27 19:54:29 +000066 drop_whitespace (default: true)
67 Drop leading and trailing whitespace from lines.
Greg Ward00935822002-06-07 21:43:37 +000068 """
69
Greg Ward4c6c9c42003-02-03 14:46:57 +000070 whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
Greg Ward00935822002-06-07 21:43:37 +000071
Greg Ward2e745412002-12-09 16:23:08 +000072 unicode_whitespace_trans = {}
Guido van Rossumef87d6e2007-05-02 19:09:54 +000073 uspace = ord(' ')
Greg Ward4c6c9c42003-02-03 14:46:57 +000074 for x in map(ord, _whitespace):
Greg Ward0e88c9f2002-12-11 13:54:20 +000075 unicode_whitespace_trans[x] = uspace
Greg Ward2e745412002-12-09 16:23:08 +000076
Tim Petersc411dba2002-07-16 21:35:23 +000077 # This funky little regex is just the trick for splitting
Greg Ward00935822002-06-07 21:43:37 +000078 # text up into word-wrappable chunks. E.g.
79 # "Hello there -- you goof-ball, use the -b option!"
80 # splits into
81 # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
82 # (after stripping out empty strings).
Greg Ward40407942005-03-05 02:53:17 +000083 wordsep_re = re.compile(
84 r'(\s+|' # any whitespace
85 r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words
86 r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
Greg Ward00935822002-06-07 21:43:37 +000087
Greg Ward61864102004-06-03 01:59:41 +000088 # XXX this is not locale- or charset-aware -- string.lowercase
89 # is US-ASCII only (and therefore English-only)
Greg Ward9b4864e2002-06-07 22:04:15 +000090 sentence_end_re = re.compile(r'[%s]' # lowercase letter
91 r'[\.\!\?]' # sentence-ending punct.
92 r'[\"\']?' # optional end-of-quote
93 % string.lowercase)
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,
104 drop_whitespace=True):
Greg Wardd34c9592002-06-10 20:26:02 +0000105 self.width = width
Greg Ward62080be2002-06-10 21:37:12 +0000106 self.initial_indent = initial_indent
107 self.subsequent_indent = subsequent_indent
Greg Ward47df99d2002-06-09 00:22:07 +0000108 self.expand_tabs = expand_tabs
109 self.replace_whitespace = replace_whitespace
110 self.fix_sentence_endings = fix_sentence_endings
111 self.break_long_words = break_long_words
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 self.drop_whitespace = drop_whitespace
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:
Greg Ward2e745412002-12-09 16:23:08 +0000128 if isinstance(text, str):
129 text = text.translate(self.whitespace_trans)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000130 elif isinstance(text, str):
Greg Ward2e745412002-12-09 16:23:08 +0000131 text = text.translate(self.unicode_whitespace_trans)
Greg Ward00935822002-06-07 21:43:37 +0000132 return text
133
134
Greg Wardcb320eb2002-06-07 22:32:15 +0000135 def _split(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000136 """_split(text : string) -> [string]
137
138 Split the text to wrap into indivisible chunks. Chunks are
139 not quite the same as words; see wrap_chunks() for full
140 details. As an example, the text
141 Look, goof-ball -- use the -b option!
142 breaks into the following chunks:
143 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
144 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
145 """
146 chunks = self.wordsep_re.split(text)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147 chunks = filter(None, chunks) # remove empty chunks
Greg Ward00935822002-06-07 21:43:37 +0000148 return chunks
149
Greg Wardcb320eb2002-06-07 22:32:15 +0000150 def _fix_sentence_endings(self, chunks):
Greg Ward00935822002-06-07 21:43:37 +0000151 """_fix_sentence_endings(chunks : [string])
152
153 Correct for sentence endings buried in 'chunks'. Eg. when the
154 original text contains "... foo.\nBar ...", munge_whitespace()
155 and split() will convert that to [..., "foo.", " ", "Bar", ...]
156 which has one too few spaces; this method simply changes the one
157 space to two.
158 """
159 i = 0
Greg Ward9b4864e2002-06-07 22:04:15 +0000160 pat = self.sentence_end_re
Greg Ward00935822002-06-07 21:43:37 +0000161 while i < len(chunks)-1:
Greg Ward9b4864e2002-06-07 22:04:15 +0000162 if chunks[i+1] == " " and pat.search(chunks[i]):
Greg Ward00935822002-06-07 21:43:37 +0000163 chunks[i+1] = " "
164 i += 2
165 else:
166 i += 1
167
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000168 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
Greg Ward00935822002-06-07 21:43:37 +0000169 """_handle_long_word(chunks : [string],
170 cur_line : [string],
Greg Ward62080be2002-06-10 21:37:12 +0000171 cur_len : int, width : int)
Greg Ward00935822002-06-07 21:43:37 +0000172
173 Handle a chunk of text (most likely a word, not whitespace) that
174 is too long to fit in any line.
175 """
Raymond Hettingerc11dbcd2003-08-30 14:43:55 +0000176 space_left = max(width - cur_len, 1)
Greg Ward00935822002-06-07 21:43:37 +0000177
178 # If we're allowed to break long words, then do so: put as much
179 # of the next chunk onto the current line as will fit.
180 if self.break_long_words:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000181 cur_line.append(reversed_chunks[-1][:space_left])
182 reversed_chunks[-1] = reversed_chunks[-1][space_left:]
Greg Ward00935822002-06-07 21:43:37 +0000183
184 # Otherwise, we have to preserve the long word intact. Only add
185 # it to the current line if there's nothing already there --
186 # that minimizes how much we violate the width constraint.
187 elif not cur_line:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000188 cur_line.append(reversed_chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000189
190 # If we're not allowed to break long words, and there's already
191 # text on the current line, do nothing. Next time through the
192 # main loop of _wrap_chunks(), we'll wind up here again, but
193 # cur_len will be zero, so the next line will be entirely
194 # devoted to the long word that we can't handle right now.
195
Greg Wardd34c9592002-06-10 20:26:02 +0000196 def _wrap_chunks(self, chunks):
197 """_wrap_chunks(chunks : [string]) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000198
199 Wrap a sequence of text chunks and return a list of lines of
Greg Wardd34c9592002-06-10 20:26:02 +0000200 length 'self.width' or less. (If 'break_long_words' is false,
201 some lines may be longer than this.) Chunks correspond roughly
202 to words and the whitespace between them: each chunk is
203 indivisible (modulo 'break_long_words'), but a line break can
204 come between any two chunks. Chunks should not have internal
205 whitespace; ie. a chunk is either all whitespace or a "word".
206 Whitespace chunks will be removed from the beginning and end of
207 lines, but apart from that whitespace is preserved.
Greg Ward00935822002-06-07 21:43:37 +0000208 """
209 lines = []
Greg Ward21820cd2003-05-07 00:55:35 +0000210 if self.width <= 0:
211 raise ValueError("invalid width %r (must be > 0)" % self.width)
Greg Ward00935822002-06-07 21:43:37 +0000212
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000213 # Arrange in reverse order so items can be efficiently popped
214 # from a stack of chucks.
215 chunks.reverse()
216
Greg Ward00935822002-06-07 21:43:37 +0000217 while chunks:
218
Greg Ward62080be2002-06-10 21:37:12 +0000219 # Start the list of chunks that will make up the current line.
220 # cur_len is just the length of all the chunks in cur_line.
221 cur_line = []
222 cur_len = 0
223
224 # Figure out which static string will prefix this line.
225 if lines:
226 indent = self.subsequent_indent
227 else:
228 indent = self.initial_indent
229
230 # Maximum width for this line.
231 width = self.width - len(indent)
Greg Ward00935822002-06-07 21:43:37 +0000232
Greg Wardab73d462002-12-09 16:26:05 +0000233 # First chunk on line is whitespace -- drop it, unless this
234 # is the very beginning of the text (ie. no lines started yet).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000236 del chunks[-1]
Greg Ward00935822002-06-07 21:43:37 +0000237
238 while chunks:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000239 l = len(chunks[-1])
Greg Ward00935822002-06-07 21:43:37 +0000240
241 # Can at least squeeze this chunk onto the current line.
242 if cur_len + l <= width:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000243 cur_line.append(chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000244 cur_len += l
245
246 # Nope, this line is full.
247 else:
248 break
249
250 # The current line is full, and the next chunk is too big to
Tim Petersc411dba2002-07-16 21:35:23 +0000251 # fit on *any* line (not just this one).
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000252 if chunks and len(chunks[-1]) > width:
Greg Ward62080be2002-06-10 21:37:12 +0000253 self._handle_long_word(chunks, cur_line, cur_len, width)
Greg Ward00935822002-06-07 21:43:37 +0000254
255 # If the last chunk on this line is all whitespace, drop it.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000256 if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
Greg Ward00935822002-06-07 21:43:37 +0000257 del cur_line[-1]
258
259 # Convert current line back to a string and store it in list
260 # of all lines (return value).
261 if cur_line:
Greg Ward62080be2002-06-10 21:37:12 +0000262 lines.append(indent + ''.join(cur_line))
Greg Ward00935822002-06-07 21:43:37 +0000263
264 return lines
265
266
267 # -- Public interface ----------------------------------------------
268
Greg Wardd34c9592002-06-10 20:26:02 +0000269 def wrap(self, text):
270 """wrap(text : string) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000271
Greg Warde807e572002-07-04 14:51:49 +0000272 Reformat the single paragraph in 'text' so it fits in lines of
273 no more than 'self.width' columns, and return a list of wrapped
274 lines. Tabs in 'text' are expanded with string.expandtabs(),
275 and all other whitespace characters (including newline) are
276 converted to space.
Greg Ward00935822002-06-07 21:43:37 +0000277 """
278 text = self._munge_whitespace(text)
Greg Ward00935822002-06-07 21:43:37 +0000279 chunks = self._split(text)
Greg Ward62e4f3b2002-06-07 21:56:16 +0000280 if self.fix_sentence_endings:
281 self._fix_sentence_endings(chunks)
Greg Wardd34c9592002-06-10 20:26:02 +0000282 return self._wrap_chunks(chunks)
Greg Ward00935822002-06-07 21:43:37 +0000283
Greg Ward62080be2002-06-10 21:37:12 +0000284 def fill(self, text):
285 """fill(text : string) -> string
Greg Ward00935822002-06-07 21:43:37 +0000286
Greg Warde807e572002-07-04 14:51:49 +0000287 Reformat the single paragraph in 'text' to fit in lines of no
288 more than 'self.width' columns, and return a new string
289 containing the entire wrapped paragraph.
Greg Ward00935822002-06-07 21:43:37 +0000290 """
Greg Ward62080be2002-06-10 21:37:12 +0000291 return "\n".join(self.wrap(text))
Greg Ward00935822002-06-07 21:43:37 +0000292
293
Greg Warde807e572002-07-04 14:51:49 +0000294# -- Convenience interface ---------------------------------------------
Greg Ward00935822002-06-07 21:43:37 +0000295
Greg Wardcf02ac62002-06-10 20:36:07 +0000296def wrap(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000297 """Wrap a single paragraph of text, returning a list of wrapped lines.
298
299 Reformat the single paragraph in 'text' so it fits in lines of no
300 more than 'width' columns, and return a list of wrapped lines. By
301 default, tabs in 'text' are expanded with string.expandtabs(), and
302 all other whitespace characters (including newline) are converted to
303 space. See TextWrapper class for available keyword args to customize
304 wrapping behaviour.
305 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000306 w = TextWrapper(width=width, **kwargs)
307 return w.wrap(text)
Greg Ward00935822002-06-07 21:43:37 +0000308
Greg Ward62080be2002-06-10 21:37:12 +0000309def fill(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000310 """Fill a single paragraph of text, returning a new string.
311
312 Reformat the single paragraph in 'text' to fit in lines of no more
313 than 'width' columns, and return a new string containing the entire
314 wrapped paragraph. As with wrap(), tabs are expanded and other
315 whitespace characters converted to space. See TextWrapper class for
316 available keyword args to customize wrapping behaviour.
317 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000318 w = TextWrapper(width=width, **kwargs)
Greg Ward62080be2002-06-10 21:37:12 +0000319 return w.fill(text)
Greg Ward478cd482003-05-08 01:58:05 +0000320
321
322# -- Loosely related functionality -------------------------------------
323
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000324_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
325_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
326
Greg Ward478cd482003-05-08 01:58:05 +0000327def dedent(text):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000328 """Remove any common leading whitespace from every line in `text`.
Greg Ward478cd482003-05-08 01:58:05 +0000329
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000330 This can be used to make triple-quoted strings line up with the left
331 edge of the display, while still presenting them in the source code
332 in indented form.
Greg Ward478cd482003-05-08 01:58:05 +0000333
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000334 Note that tabs and spaces are both treated as whitespace, but they
335 are not equal: the lines " hello" and "\thello" are
336 considered to have no common leading whitespace. (This behaviour is
337 new in Python 2.5; older versions of this module incorrectly
338 expanded tabs before searching for common leading whitespace.)
Greg Ward478cd482003-05-08 01:58:05 +0000339 """
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000340 # Look for the longest leading string of spaces and tabs common to
341 # all lines.
Greg Ward478cd482003-05-08 01:58:05 +0000342 margin = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000343 text = _whitespace_only_re.sub('', text)
344 indents = _leading_whitespace_re.findall(text)
345 for indent in indents:
Greg Ward478cd482003-05-08 01:58:05 +0000346 if margin is None:
347 margin = indent
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000348
349 # Current line more deeply indented than previous winner:
350 # no change (previous winner is still on top).
351 elif indent.startswith(margin):
352 pass
353
354 # Current line consistent with and no deeper than previous winner:
355 # it's the new winner.
356 elif margin.startswith(indent):
357 margin = indent
358
359 # Current line and previous winner have no common whitespace:
360 # there is no margin.
Greg Ward478cd482003-05-08 01:58:05 +0000361 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000362 margin = ""
363 break
Greg Ward478cd482003-05-08 01:58:05 +0000364
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000365 # sanity check (testing/debugging only)
366 if 0 and margin:
367 for line in text.split("\n"):
368 assert not line or line.startswith(margin), \
369 "line = %r, margin = %r" % (line, margin)
Greg Ward478cd482003-05-08 01:58:05 +0000370
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000371 if margin:
372 text = re.sub(r'(?m)^' + margin, '', text)
373 return text
374
375if __name__ == "__main__":
376 #print dedent("\tfoo\n\tbar")
377 #print dedent(" \thello there\n \t how are you?")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000378 print(dedent("Hello there.\n This is indented."))