blob: fc93b9b0afddd782d42c51034fc521735fae854f [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
Greg Ward2e745412002-12-09 16:23:08 +000054 unicode_whitespace_trans = {}
55 for c in string.whitespace:
56 unicode_whitespace_trans[ord(unicode(c))] = ord(u' ')
57
Tim Petersc411dba2002-07-16 21:35:23 +000058 # This funky little regex is just the trick for splitting
Greg Ward00935822002-06-07 21:43:37 +000059 # text up into word-wrappable chunks. E.g.
60 # "Hello there -- you goof-ball, use the -b option!"
61 # splits into
62 # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
63 # (after stripping out empty strings).
64 wordsep_re = re.compile(r'(\s+|' # any whitespace
Greg Wardcce4d672002-08-22 21:04:21 +000065 r'-*\w{2,}-(?=\w{2,})|' # hyphenated words
Greg Ward78cc0512002-10-13 19:23:18 +000066 r'(?<=\S)-{2,}(?=\w))') # em-dash
Greg Ward00935822002-06-07 21:43:37 +000067
Greg Ward9b4864e2002-06-07 22:04:15 +000068 # XXX will there be a locale-or-charset-aware version of
69 # string.lowercase in 2.3?
70 sentence_end_re = re.compile(r'[%s]' # lowercase letter
71 r'[\.\!\?]' # sentence-ending punct.
72 r'[\"\']?' # optional end-of-quote
73 % string.lowercase)
Greg Ward62e4f3b2002-06-07 21:56:16 +000074
Greg Ward00935822002-06-07 21:43:37 +000075
Greg Ward47df99d2002-06-09 00:22:07 +000076 def __init__ (self,
Greg Wardd34c9592002-06-10 20:26:02 +000077 width=70,
Greg Ward62080be2002-06-10 21:37:12 +000078 initial_indent="",
79 subsequent_indent="",
Greg Ward47df99d2002-06-09 00:22:07 +000080 expand_tabs=True,
81 replace_whitespace=True,
82 fix_sentence_endings=False,
83 break_long_words=True):
Greg Wardd34c9592002-06-10 20:26:02 +000084 self.width = width
Greg Ward62080be2002-06-10 21:37:12 +000085 self.initial_indent = initial_indent
86 self.subsequent_indent = subsequent_indent
Greg Ward47df99d2002-06-09 00:22:07 +000087 self.expand_tabs = expand_tabs
88 self.replace_whitespace = replace_whitespace
89 self.fix_sentence_endings = fix_sentence_endings
90 self.break_long_words = break_long_words
Tim Petersc411dba2002-07-16 21:35:23 +000091
Greg Ward00935822002-06-07 21:43:37 +000092
93 # -- Private methods -----------------------------------------------
94 # (possibly useful for subclasses to override)
95
Greg Wardcb320eb2002-06-07 22:32:15 +000096 def _munge_whitespace(self, text):
Greg Ward00935822002-06-07 21:43:37 +000097 """_munge_whitespace(text : string) -> string
98
99 Munge whitespace in text: expand tabs and convert all other
100 whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
101 becomes " foo bar baz".
102 """
103 if self.expand_tabs:
104 text = text.expandtabs()
105 if self.replace_whitespace:
Greg Ward2e745412002-12-09 16:23:08 +0000106 if isinstance(text, str):
107 text = text.translate(self.whitespace_trans)
108 elif isinstance(text, unicode):
109 text = text.translate(self.unicode_whitespace_trans)
Greg Ward00935822002-06-07 21:43:37 +0000110 return text
111
112
Greg Wardcb320eb2002-06-07 22:32:15 +0000113 def _split(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000114 """_split(text : string) -> [string]
115
116 Split the text to wrap into indivisible chunks. Chunks are
117 not quite the same as words; see wrap_chunks() for full
118 details. As an example, the text
119 Look, goof-ball -- use the -b option!
120 breaks into the following chunks:
121 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
122 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
123 """
124 chunks = self.wordsep_re.split(text)
125 chunks = filter(None, chunks)
126 return chunks
127
Greg Wardcb320eb2002-06-07 22:32:15 +0000128 def _fix_sentence_endings(self, chunks):
Greg Ward00935822002-06-07 21:43:37 +0000129 """_fix_sentence_endings(chunks : [string])
130
131 Correct for sentence endings buried in 'chunks'. Eg. when the
132 original text contains "... foo.\nBar ...", munge_whitespace()
133 and split() will convert that to [..., "foo.", " ", "Bar", ...]
134 which has one too few spaces; this method simply changes the one
135 space to two.
136 """
137 i = 0
Greg Ward9b4864e2002-06-07 22:04:15 +0000138 pat = self.sentence_end_re
Greg Ward00935822002-06-07 21:43:37 +0000139 while i < len(chunks)-1:
Greg Ward9b4864e2002-06-07 22:04:15 +0000140 if chunks[i+1] == " " and pat.search(chunks[i]):
Greg Ward00935822002-06-07 21:43:37 +0000141 chunks[i+1] = " "
142 i += 2
143 else:
144 i += 1
145
Greg Ward62080be2002-06-10 21:37:12 +0000146 def _handle_long_word(self, chunks, cur_line, cur_len, width):
Greg Ward00935822002-06-07 21:43:37 +0000147 """_handle_long_word(chunks : [string],
148 cur_line : [string],
Greg Ward62080be2002-06-10 21:37:12 +0000149 cur_len : int, width : int)
Greg Ward00935822002-06-07 21:43:37 +0000150
151 Handle a chunk of text (most likely a word, not whitespace) that
152 is too long to fit in any line.
153 """
Greg Ward62080be2002-06-10 21:37:12 +0000154 space_left = width - cur_len
Greg Ward00935822002-06-07 21:43:37 +0000155
156 # If we're allowed to break long words, then do so: put as much
157 # of the next chunk onto the current line as will fit.
158 if self.break_long_words:
159 cur_line.append(chunks[0][0:space_left])
160 chunks[0] = chunks[0][space_left:]
161
162 # Otherwise, we have to preserve the long word intact. Only add
163 # it to the current line if there's nothing already there --
164 # that minimizes how much we violate the width constraint.
165 elif not cur_line:
166 cur_line.append(chunks.pop(0))
167
168 # If we're not allowed to break long words, and there's already
169 # text on the current line, do nothing. Next time through the
170 # main loop of _wrap_chunks(), we'll wind up here again, but
171 # cur_len will be zero, so the next line will be entirely
172 # devoted to the long word that we can't handle right now.
173
Greg Wardd34c9592002-06-10 20:26:02 +0000174 def _wrap_chunks(self, chunks):
175 """_wrap_chunks(chunks : [string]) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000176
177 Wrap a sequence of text chunks and return a list of lines of
Greg Wardd34c9592002-06-10 20:26:02 +0000178 length 'self.width' or less. (If 'break_long_words' is false,
179 some lines may be longer than this.) Chunks correspond roughly
180 to words and the whitespace between them: each chunk is
181 indivisible (modulo 'break_long_words'), but a line break can
182 come between any two chunks. Chunks should not have internal
183 whitespace; ie. a chunk is either all whitespace or a "word".
184 Whitespace chunks will be removed from the beginning and end of
185 lines, but apart from that whitespace is preserved.
Greg Ward00935822002-06-07 21:43:37 +0000186 """
187 lines = []
188
189 while chunks:
190
Greg Ward62080be2002-06-10 21:37:12 +0000191 # Start the list of chunks that will make up the current line.
192 # cur_len is just the length of all the chunks in cur_line.
193 cur_line = []
194 cur_len = 0
195
196 # Figure out which static string will prefix this line.
197 if lines:
198 indent = self.subsequent_indent
199 else:
200 indent = self.initial_indent
201
202 # Maximum width for this line.
203 width = self.width - len(indent)
Greg Ward00935822002-06-07 21:43:37 +0000204
205 # First chunk on line is whitespace -- drop it.
206 if chunks[0].strip() == '':
207 del chunks[0]
208
209 while chunks:
210 l = len(chunks[0])
211
212 # Can at least squeeze this chunk onto the current line.
213 if cur_len + l <= width:
214 cur_line.append(chunks.pop(0))
215 cur_len += l
216
217 # Nope, this line is full.
218 else:
219 break
220
221 # The current line is full, and the next chunk is too big to
Tim Petersc411dba2002-07-16 21:35:23 +0000222 # fit on *any* line (not just this one).
Greg Ward00935822002-06-07 21:43:37 +0000223 if chunks and len(chunks[0]) > width:
Greg Ward62080be2002-06-10 21:37:12 +0000224 self._handle_long_word(chunks, cur_line, cur_len, width)
Greg Ward00935822002-06-07 21:43:37 +0000225
226 # If the last chunk on this line is all whitespace, drop it.
227 if cur_line and cur_line[-1].strip() == '':
228 del cur_line[-1]
229
230 # Convert current line back to a string and store it in list
231 # of all lines (return value).
232 if cur_line:
Greg Ward62080be2002-06-10 21:37:12 +0000233 lines.append(indent + ''.join(cur_line))
Greg Ward00935822002-06-07 21:43:37 +0000234
235 return lines
236
237
238 # -- Public interface ----------------------------------------------
239
Greg Wardd34c9592002-06-10 20:26:02 +0000240 def wrap(self, text):
241 """wrap(text : string) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000242
Greg Warde807e572002-07-04 14:51:49 +0000243 Reformat the single paragraph in 'text' so it fits in lines of
244 no more than 'self.width' columns, and return a list of wrapped
245 lines. Tabs in 'text' are expanded with string.expandtabs(),
246 and all other whitespace characters (including newline) are
247 converted to space.
Greg Ward00935822002-06-07 21:43:37 +0000248 """
249 text = self._munge_whitespace(text)
Guido van Rossumeb287a22002-10-02 15:47:32 +0000250 indent = self.initial_indent
251 if len(text) + len(indent) <= self.width:
252 return [indent + text]
Greg Ward00935822002-06-07 21:43:37 +0000253 chunks = self._split(text)
Greg Ward62e4f3b2002-06-07 21:56:16 +0000254 if self.fix_sentence_endings:
255 self._fix_sentence_endings(chunks)
Greg Wardd34c9592002-06-10 20:26:02 +0000256 return self._wrap_chunks(chunks)
Greg Ward00935822002-06-07 21:43:37 +0000257
Greg Ward62080be2002-06-10 21:37:12 +0000258 def fill(self, text):
259 """fill(text : string) -> string
Greg Ward00935822002-06-07 21:43:37 +0000260
Greg Warde807e572002-07-04 14:51:49 +0000261 Reformat the single paragraph in 'text' to fit in lines of no
262 more than 'self.width' columns, and return a new string
263 containing the entire wrapped paragraph.
Greg Ward00935822002-06-07 21:43:37 +0000264 """
Greg Ward62080be2002-06-10 21:37:12 +0000265 return "\n".join(self.wrap(text))
Greg Ward00935822002-06-07 21:43:37 +0000266
267
Greg Warde807e572002-07-04 14:51:49 +0000268# -- Convenience interface ---------------------------------------------
Greg Ward00935822002-06-07 21:43:37 +0000269
Greg Wardcf02ac62002-06-10 20:36:07 +0000270def wrap(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000271 """Wrap a single paragraph of text, returning a list of wrapped lines.
272
273 Reformat the single paragraph in 'text' so it fits in lines of no
274 more than 'width' columns, and return a list of wrapped lines. By
275 default, tabs in 'text' are expanded with string.expandtabs(), and
276 all other whitespace characters (including newline) are converted to
277 space. See TextWrapper class for available keyword args to customize
278 wrapping behaviour.
279 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000280 w = TextWrapper(width=width, **kwargs)
281 return w.wrap(text)
Greg Ward00935822002-06-07 21:43:37 +0000282
Greg Ward62080be2002-06-10 21:37:12 +0000283def fill(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000284 """Fill a single paragraph of text, returning a new string.
285
286 Reformat the single paragraph in 'text' to fit in lines of no more
287 than 'width' columns, and return a new string containing the entire
288 wrapped paragraph. As with wrap(), tabs are expanded and other
289 whitespace characters converted to space. See TextWrapper class for
290 available keyword args to customize wrapping behaviour.
291 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000292 w = TextWrapper(width=width, **kwargs)
Greg Ward62080be2002-06-10 21:37:12 +0000293 return w.fill(text)