blob: 2c9592b6dea996b389eff714bafdff2edb01d28f [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 Ward698d9f02002-06-07 22:40:23 +00005# Copyright (C) 2002 Python Software Foundation.
6# Written by Greg Ward <gward@python.net>
7
Greg Ward4c486bc2002-10-22 18:31:50 +00008# XXX currently this module does not work very well with Unicode
9# strings. See http://www.python.org/sf/622831 for updates.
10
Greg Ward00935822002-06-07 21:43:37 +000011__revision__ = "$Id$"
12
13import string, re
14
Greg Ward00935822002-06-07 21:43:37 +000015class TextWrapper:
16 """
17 Object for wrapping/filling text. The public interface consists of
18 the wrap() and fill() methods; the other methods are just there for
19 subclasses to override in order to tweak the default behaviour.
20 If you want to completely replace the main wrapping algorithm,
21 you'll probably have to override _wrap_chunks().
22
Greg Wardd34c9592002-06-10 20:26:02 +000023 Several instance attributes control various aspects of wrapping:
24 width (default: 70)
25 the maximum width of wrapped lines (unless break_long_words
26 is false)
Greg Ward62080be2002-06-10 21:37:12 +000027 initial_indent (default: "")
28 string that will be prepended to the first line of wrapped
29 output. Counts towards the line's width.
30 subsequent_indent (default: "")
31 string that will be prepended to all lines save the first
32 of wrapped output; also counts towards each line's width.
Greg Ward62e4f3b2002-06-07 21:56:16 +000033 expand_tabs (default: true)
34 Expand tabs in input text to spaces before further processing.
35 Each tab will become 1 .. 8 spaces, depending on its position in
36 its line. If false, each tab is treated as a single character.
37 replace_whitespace (default: true)
38 Replace all whitespace characters in the input text by spaces
39 after tab expansion. Note that if expand_tabs is false and
40 replace_whitespace is true, every tab will be converted to a
41 single space!
42 fix_sentence_endings (default: false)
43 Ensure that sentence-ending punctuation is always followed
44 by two spaces. Off by default becaus the algorithm is
45 (unavoidably) imperfect.
46 break_long_words (default: true)
Greg Wardd34c9592002-06-10 20:26:02 +000047 Break words longer than 'width'. If false, those words will not
48 be broken, and some lines might be longer than 'width'.
Greg Ward00935822002-06-07 21:43:37 +000049 """
50
51 whitespace_trans = string.maketrans(string.whitespace,
52 ' ' * len(string.whitespace))
53
Tim Petersc411dba2002-07-16 21:35:23 +000054 # This funky little regex is just the trick for splitting
Greg Ward00935822002-06-07 21:43:37 +000055 # text up into word-wrappable chunks. E.g.
56 # "Hello there -- you goof-ball, use the -b option!"
57 # splits into
58 # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
59 # (after stripping out empty strings).
60 wordsep_re = re.compile(r'(\s+|' # any whitespace
Greg Wardcce4d672002-08-22 21:04:21 +000061 r'-*\w{2,}-(?=\w{2,})|' # hyphenated words
Greg Ward78cc0512002-10-13 19:23:18 +000062 r'(?<=\S)-{2,}(?=\w))') # em-dash
Greg Ward00935822002-06-07 21:43:37 +000063
Greg Ward9b4864e2002-06-07 22:04:15 +000064 # XXX will there be a locale-or-charset-aware version of
65 # string.lowercase in 2.3?
66 sentence_end_re = re.compile(r'[%s]' # lowercase letter
67 r'[\.\!\?]' # sentence-ending punct.
68 r'[\"\']?' # optional end-of-quote
69 % string.lowercase)
Greg Ward62e4f3b2002-06-07 21:56:16 +000070
Greg Ward00935822002-06-07 21:43:37 +000071
Greg Ward47df99d2002-06-09 00:22:07 +000072 def __init__ (self,
Greg Wardd34c9592002-06-10 20:26:02 +000073 width=70,
Greg Ward62080be2002-06-10 21:37:12 +000074 initial_indent="",
75 subsequent_indent="",
Greg Ward47df99d2002-06-09 00:22:07 +000076 expand_tabs=True,
77 replace_whitespace=True,
78 fix_sentence_endings=False,
79 break_long_words=True):
Greg Wardd34c9592002-06-10 20:26:02 +000080 self.width = width
Greg Ward62080be2002-06-10 21:37:12 +000081 self.initial_indent = initial_indent
82 self.subsequent_indent = subsequent_indent
Greg Ward47df99d2002-06-09 00:22:07 +000083 self.expand_tabs = expand_tabs
84 self.replace_whitespace = replace_whitespace
85 self.fix_sentence_endings = fix_sentence_endings
86 self.break_long_words = break_long_words
Tim Petersc411dba2002-07-16 21:35:23 +000087
Greg Ward00935822002-06-07 21:43:37 +000088
89 # -- Private methods -----------------------------------------------
90 # (possibly useful for subclasses to override)
91
Greg Wardcb320eb2002-06-07 22:32:15 +000092 def _munge_whitespace(self, text):
Greg Ward00935822002-06-07 21:43:37 +000093 """_munge_whitespace(text : string) -> string
94
95 Munge whitespace in text: expand tabs and convert all other
96 whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
97 becomes " foo bar baz".
98 """
99 if self.expand_tabs:
100 text = text.expandtabs()
101 if self.replace_whitespace:
102 text = text.translate(self.whitespace_trans)
103 return text
104
105
Greg Wardcb320eb2002-06-07 22:32:15 +0000106 def _split(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000107 """_split(text : string) -> [string]
108
109 Split the text to wrap into indivisible chunks. Chunks are
110 not quite the same as words; see wrap_chunks() for full
111 details. As an example, the text
112 Look, goof-ball -- use the -b option!
113 breaks into the following chunks:
114 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
115 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
116 """
117 chunks = self.wordsep_re.split(text)
118 chunks = filter(None, chunks)
119 return chunks
120
Greg Wardcb320eb2002-06-07 22:32:15 +0000121 def _fix_sentence_endings(self, chunks):
Greg Ward00935822002-06-07 21:43:37 +0000122 """_fix_sentence_endings(chunks : [string])
123
124 Correct for sentence endings buried in 'chunks'. Eg. when the
125 original text contains "... foo.\nBar ...", munge_whitespace()
126 and split() will convert that to [..., "foo.", " ", "Bar", ...]
127 which has one too few spaces; this method simply changes the one
128 space to two.
129 """
130 i = 0
Greg Ward9b4864e2002-06-07 22:04:15 +0000131 pat = self.sentence_end_re
Greg Ward00935822002-06-07 21:43:37 +0000132 while i < len(chunks)-1:
Greg Ward9b4864e2002-06-07 22:04:15 +0000133 if chunks[i+1] == " " and pat.search(chunks[i]):
Greg Ward00935822002-06-07 21:43:37 +0000134 chunks[i+1] = " "
135 i += 2
136 else:
137 i += 1
138
Greg Ward62080be2002-06-10 21:37:12 +0000139 def _handle_long_word(self, chunks, cur_line, cur_len, width):
Greg Ward00935822002-06-07 21:43:37 +0000140 """_handle_long_word(chunks : [string],
141 cur_line : [string],
Greg Ward62080be2002-06-10 21:37:12 +0000142 cur_len : int, width : int)
Greg Ward00935822002-06-07 21:43:37 +0000143
144 Handle a chunk of text (most likely a word, not whitespace) that
145 is too long to fit in any line.
146 """
Greg Ward62080be2002-06-10 21:37:12 +0000147 space_left = width - cur_len
Greg Ward00935822002-06-07 21:43:37 +0000148
149 # If we're allowed to break long words, then do so: put as much
150 # of the next chunk onto the current line as will fit.
151 if self.break_long_words:
152 cur_line.append(chunks[0][0:space_left])
153 chunks[0] = chunks[0][space_left:]
154
155 # Otherwise, we have to preserve the long word intact. Only add
156 # it to the current line if there's nothing already there --
157 # that minimizes how much we violate the width constraint.
158 elif not cur_line:
159 cur_line.append(chunks.pop(0))
160
161 # If we're not allowed to break long words, and there's already
162 # text on the current line, do nothing. Next time through the
163 # main loop of _wrap_chunks(), we'll wind up here again, but
164 # cur_len will be zero, so the next line will be entirely
165 # devoted to the long word that we can't handle right now.
166
Greg Wardd34c9592002-06-10 20:26:02 +0000167 def _wrap_chunks(self, chunks):
168 """_wrap_chunks(chunks : [string]) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000169
170 Wrap a sequence of text chunks and return a list of lines of
Greg Wardd34c9592002-06-10 20:26:02 +0000171 length 'self.width' or less. (If 'break_long_words' is false,
172 some lines may be longer than this.) Chunks correspond roughly
173 to words and the whitespace between them: each chunk is
174 indivisible (modulo 'break_long_words'), but a line break can
175 come between any two chunks. Chunks should not have internal
176 whitespace; ie. a chunk is either all whitespace or a "word".
177 Whitespace chunks will be removed from the beginning and end of
178 lines, but apart from that whitespace is preserved.
Greg Ward00935822002-06-07 21:43:37 +0000179 """
180 lines = []
181
182 while chunks:
183
Greg Ward62080be2002-06-10 21:37:12 +0000184 # Start the list of chunks that will make up the current line.
185 # cur_len is just the length of all the chunks in cur_line.
186 cur_line = []
187 cur_len = 0
188
189 # Figure out which static string will prefix this line.
190 if lines:
191 indent = self.subsequent_indent
192 else:
193 indent = self.initial_indent
194
195 # Maximum width for this line.
196 width = self.width - len(indent)
Greg Ward00935822002-06-07 21:43:37 +0000197
198 # First chunk on line is whitespace -- drop it.
199 if chunks[0].strip() == '':
200 del chunks[0]
201
202 while chunks:
203 l = len(chunks[0])
204
205 # Can at least squeeze this chunk onto the current line.
206 if cur_len + l <= width:
207 cur_line.append(chunks.pop(0))
208 cur_len += l
209
210 # Nope, this line is full.
211 else:
212 break
213
214 # The current line is full, and the next chunk is too big to
Tim Petersc411dba2002-07-16 21:35:23 +0000215 # fit on *any* line (not just this one).
Greg Ward00935822002-06-07 21:43:37 +0000216 if chunks and len(chunks[0]) > width:
Greg Ward62080be2002-06-10 21:37:12 +0000217 self._handle_long_word(chunks, cur_line, cur_len, width)
Greg Ward00935822002-06-07 21:43:37 +0000218
219 # If the last chunk on this line is all whitespace, drop it.
220 if cur_line and cur_line[-1].strip() == '':
221 del cur_line[-1]
222
223 # Convert current line back to a string and store it in list
224 # of all lines (return value).
225 if cur_line:
Greg Ward62080be2002-06-10 21:37:12 +0000226 lines.append(indent + ''.join(cur_line))
Greg Ward00935822002-06-07 21:43:37 +0000227
228 return lines
229
230
231 # -- Public interface ----------------------------------------------
232
Greg Wardd34c9592002-06-10 20:26:02 +0000233 def wrap(self, text):
234 """wrap(text : string) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000235
Greg Warde807e572002-07-04 14:51:49 +0000236 Reformat the single paragraph in 'text' so it fits in lines of
237 no more than 'self.width' columns, and return a list of wrapped
238 lines. Tabs in 'text' are expanded with string.expandtabs(),
239 and all other whitespace characters (including newline) are
240 converted to space.
Greg Ward00935822002-06-07 21:43:37 +0000241 """
242 text = self._munge_whitespace(text)
Guido van Rossumeb287a22002-10-02 15:47:32 +0000243 indent = self.initial_indent
244 if len(text) + len(indent) <= self.width:
245 return [indent + text]
Greg Ward00935822002-06-07 21:43:37 +0000246 chunks = self._split(text)
Greg Ward62e4f3b2002-06-07 21:56:16 +0000247 if self.fix_sentence_endings:
248 self._fix_sentence_endings(chunks)
Greg Wardd34c9592002-06-10 20:26:02 +0000249 return self._wrap_chunks(chunks)
Greg Ward00935822002-06-07 21:43:37 +0000250
Greg Ward62080be2002-06-10 21:37:12 +0000251 def fill(self, text):
252 """fill(text : string) -> string
Greg Ward00935822002-06-07 21:43:37 +0000253
Greg Warde807e572002-07-04 14:51:49 +0000254 Reformat the single paragraph in 'text' to fit in lines of no
255 more than 'self.width' columns, and return a new string
256 containing the entire wrapped paragraph.
Greg Ward00935822002-06-07 21:43:37 +0000257 """
Greg Ward62080be2002-06-10 21:37:12 +0000258 return "\n".join(self.wrap(text))
Greg Ward00935822002-06-07 21:43:37 +0000259
260
Greg Warde807e572002-07-04 14:51:49 +0000261# -- Convenience interface ---------------------------------------------
Greg Ward00935822002-06-07 21:43:37 +0000262
Greg Wardcf02ac62002-06-10 20:36:07 +0000263def wrap(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000264 """Wrap a single paragraph of text, returning a list of wrapped lines.
265
266 Reformat the single paragraph in 'text' so it fits in lines of no
267 more than 'width' columns, and return a list of wrapped lines. By
268 default, tabs in 'text' are expanded with string.expandtabs(), and
269 all other whitespace characters (including newline) are converted to
270 space. See TextWrapper class for available keyword args to customize
271 wrapping behaviour.
272 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000273 w = TextWrapper(width=width, **kwargs)
274 return w.wrap(text)
Greg Ward00935822002-06-07 21:43:37 +0000275
Greg Ward62080be2002-06-10 21:37:12 +0000276def fill(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000277 """Fill a single paragraph of text, returning a new string.
278
279 Reformat the single paragraph in 'text' to fit in lines of no more
280 than 'width' columns, and return a new string containing the entire
281 wrapped paragraph. As with wrap(), tabs are expanded and other
282 whitespace characters converted to space. See TextWrapper class for
283 available keyword args to customize wrapping behaviour.
284 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000285 w = TextWrapper(width=width, **kwargs)
Greg Ward62080be2002-06-10 21:37:12 +0000286 return w.fill(text)