blob: fb8d3b841d438e92678375b52a0143211f2b70e1 [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 Ward698d9f02002-06-07 22:40:23 +00004# Copyright (C) 2001 Gregory P. Ward.
5# Copyright (C) 2002 Python Software Foundation.
6# Written by Greg Ward <gward@python.net>
7
Greg Ward00935822002-06-07 21:43:37 +00008__revision__ = "$Id$"
9
10import string, re
11
Greg Ward00935822002-06-07 21:43:37 +000012class TextWrapper:
13 """
14 Object for wrapping/filling text. The public interface consists of
15 the wrap() and fill() methods; the other methods are just there for
16 subclasses to override in order to tweak the default behaviour.
17 If you want to completely replace the main wrapping algorithm,
18 you'll probably have to override _wrap_chunks().
19
Greg Wardd34c9592002-06-10 20:26:02 +000020 Several instance attributes control various aspects of wrapping:
21 width (default: 70)
22 the maximum width of wrapped lines (unless break_long_words
23 is false)
Greg Ward62080be2002-06-10 21:37:12 +000024 initial_indent (default: "")
25 string that will be prepended to the first line of wrapped
26 output. Counts towards the line's width.
27 subsequent_indent (default: "")
28 string that will be prepended to all lines save the first
29 of wrapped output; also counts towards each line's width.
Greg Ward62e4f3b2002-06-07 21:56:16 +000030 expand_tabs (default: true)
31 Expand tabs in input text to spaces before further processing.
32 Each tab will become 1 .. 8 spaces, depending on its position in
33 its line. If false, each tab is treated as a single character.
34 replace_whitespace (default: true)
35 Replace all whitespace characters in the input text by spaces
36 after tab expansion. Note that if expand_tabs is false and
37 replace_whitespace is true, every tab will be converted to a
38 single space!
39 fix_sentence_endings (default: false)
40 Ensure that sentence-ending punctuation is always followed
41 by two spaces. Off by default becaus the algorithm is
42 (unavoidably) imperfect.
43 break_long_words (default: true)
Greg Wardd34c9592002-06-10 20:26:02 +000044 Break words longer than 'width'. If false, those words will not
45 be broken, and some lines might be longer than 'width'.
Greg Ward00935822002-06-07 21:43:37 +000046 """
47
48 whitespace_trans = string.maketrans(string.whitespace,
49 ' ' * len(string.whitespace))
50
Tim Petersc411dba2002-07-16 21:35:23 +000051 # This funky little regex is just the trick for splitting
Greg Ward00935822002-06-07 21:43:37 +000052 # text up into word-wrappable chunks. E.g.
53 # "Hello there -- you goof-ball, use the -b option!"
54 # splits into
55 # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
56 # (after stripping out empty strings).
57 wordsep_re = re.compile(r'(\s+|' # any whitespace
58 r'\w{2,}-(?=\w{2,})|' # hyphenated words
59 r'(?<=\w)-{2,}(?=\w))') # em-dash
60
Greg Ward9b4864e2002-06-07 22:04:15 +000061 # XXX will there be a locale-or-charset-aware version of
62 # string.lowercase in 2.3?
63 sentence_end_re = re.compile(r'[%s]' # lowercase letter
64 r'[\.\!\?]' # sentence-ending punct.
65 r'[\"\']?' # optional end-of-quote
66 % string.lowercase)
Greg Ward62e4f3b2002-06-07 21:56:16 +000067
Greg Ward00935822002-06-07 21:43:37 +000068
Greg Ward47df99d2002-06-09 00:22:07 +000069 def __init__ (self,
Greg Wardd34c9592002-06-10 20:26:02 +000070 width=70,
Greg Ward62080be2002-06-10 21:37:12 +000071 initial_indent="",
72 subsequent_indent="",
Greg Ward47df99d2002-06-09 00:22:07 +000073 expand_tabs=True,
74 replace_whitespace=True,
75 fix_sentence_endings=False,
76 break_long_words=True):
Greg Wardd34c9592002-06-10 20:26:02 +000077 self.width = width
Greg Ward62080be2002-06-10 21:37:12 +000078 self.initial_indent = initial_indent
79 self.subsequent_indent = subsequent_indent
Greg Ward47df99d2002-06-09 00:22:07 +000080 self.expand_tabs = expand_tabs
81 self.replace_whitespace = replace_whitespace
82 self.fix_sentence_endings = fix_sentence_endings
83 self.break_long_words = break_long_words
Tim Petersc411dba2002-07-16 21:35:23 +000084
Greg Ward00935822002-06-07 21:43:37 +000085
86 # -- Private methods -----------------------------------------------
87 # (possibly useful for subclasses to override)
88
Greg Wardcb320eb2002-06-07 22:32:15 +000089 def _munge_whitespace(self, text):
Greg Ward00935822002-06-07 21:43:37 +000090 """_munge_whitespace(text : string) -> string
91
92 Munge whitespace in text: expand tabs and convert all other
93 whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
94 becomes " foo bar baz".
95 """
96 if self.expand_tabs:
97 text = text.expandtabs()
98 if self.replace_whitespace:
99 text = text.translate(self.whitespace_trans)
100 return text
101
102
Greg Wardcb320eb2002-06-07 22:32:15 +0000103 def _split(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000104 """_split(text : string) -> [string]
105
106 Split the text to wrap into indivisible chunks. Chunks are
107 not quite the same as words; see wrap_chunks() for full
108 details. As an example, the text
109 Look, goof-ball -- use the -b option!
110 breaks into the following chunks:
111 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
112 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
113 """
114 chunks = self.wordsep_re.split(text)
115 chunks = filter(None, chunks)
116 return chunks
117
Greg Wardcb320eb2002-06-07 22:32:15 +0000118 def _fix_sentence_endings(self, chunks):
Greg Ward00935822002-06-07 21:43:37 +0000119 """_fix_sentence_endings(chunks : [string])
120
121 Correct for sentence endings buried in 'chunks'. Eg. when the
122 original text contains "... foo.\nBar ...", munge_whitespace()
123 and split() will convert that to [..., "foo.", " ", "Bar", ...]
124 which has one too few spaces; this method simply changes the one
125 space to two.
126 """
127 i = 0
Greg Ward9b4864e2002-06-07 22:04:15 +0000128 pat = self.sentence_end_re
Greg Ward00935822002-06-07 21:43:37 +0000129 while i < len(chunks)-1:
Greg Ward9b4864e2002-06-07 22:04:15 +0000130 if chunks[i+1] == " " and pat.search(chunks[i]):
Greg Ward00935822002-06-07 21:43:37 +0000131 chunks[i+1] = " "
132 i += 2
133 else:
134 i += 1
135
Greg Ward62080be2002-06-10 21:37:12 +0000136 def _handle_long_word(self, chunks, cur_line, cur_len, width):
Greg Ward00935822002-06-07 21:43:37 +0000137 """_handle_long_word(chunks : [string],
138 cur_line : [string],
Greg Ward62080be2002-06-10 21:37:12 +0000139 cur_len : int, width : int)
Greg Ward00935822002-06-07 21:43:37 +0000140
141 Handle a chunk of text (most likely a word, not whitespace) that
142 is too long to fit in any line.
143 """
Greg Ward62080be2002-06-10 21:37:12 +0000144 space_left = width - cur_len
Greg Ward00935822002-06-07 21:43:37 +0000145
146 # If we're allowed to break long words, then do so: put as much
147 # of the next chunk onto the current line as will fit.
148 if self.break_long_words:
149 cur_line.append(chunks[0][0:space_left])
150 chunks[0] = chunks[0][space_left:]
151
152 # Otherwise, we have to preserve the long word intact. Only add
153 # it to the current line if there's nothing already there --
154 # that minimizes how much we violate the width constraint.
155 elif not cur_line:
156 cur_line.append(chunks.pop(0))
157
158 # If we're not allowed to break long words, and there's already
159 # text on the current line, do nothing. Next time through the
160 # main loop of _wrap_chunks(), we'll wind up here again, but
161 # cur_len will be zero, so the next line will be entirely
162 # devoted to the long word that we can't handle right now.
163
Greg Wardd34c9592002-06-10 20:26:02 +0000164 def _wrap_chunks(self, chunks):
165 """_wrap_chunks(chunks : [string]) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000166
167 Wrap a sequence of text chunks and return a list of lines of
Greg Wardd34c9592002-06-10 20:26:02 +0000168 length 'self.width' or less. (If 'break_long_words' is false,
169 some lines may be longer than this.) Chunks correspond roughly
170 to words and the whitespace between them: each chunk is
171 indivisible (modulo 'break_long_words'), but a line break can
172 come between any two chunks. Chunks should not have internal
173 whitespace; ie. a chunk is either all whitespace or a "word".
174 Whitespace chunks will be removed from the beginning and end of
175 lines, but apart from that whitespace is preserved.
Greg Ward00935822002-06-07 21:43:37 +0000176 """
177 lines = []
178
179 while chunks:
180
Greg Ward62080be2002-06-10 21:37:12 +0000181 # Start the list of chunks that will make up the current line.
182 # cur_len is just the length of all the chunks in cur_line.
183 cur_line = []
184 cur_len = 0
185
186 # Figure out which static string will prefix this line.
187 if lines:
188 indent = self.subsequent_indent
189 else:
190 indent = self.initial_indent
191
192 # Maximum width for this line.
193 width = self.width - len(indent)
Greg Ward00935822002-06-07 21:43:37 +0000194
195 # First chunk on line is whitespace -- drop it.
196 if chunks[0].strip() == '':
197 del chunks[0]
198
199 while chunks:
200 l = len(chunks[0])
201
202 # Can at least squeeze this chunk onto the current line.
203 if cur_len + l <= width:
204 cur_line.append(chunks.pop(0))
205 cur_len += l
206
207 # Nope, this line is full.
208 else:
209 break
210
211 # The current line is full, and the next chunk is too big to
Tim Petersc411dba2002-07-16 21:35:23 +0000212 # fit on *any* line (not just this one).
Greg Ward00935822002-06-07 21:43:37 +0000213 if chunks and len(chunks[0]) > width:
Greg Ward62080be2002-06-10 21:37:12 +0000214 self._handle_long_word(chunks, cur_line, cur_len, width)
Greg Ward00935822002-06-07 21:43:37 +0000215
216 # If the last chunk on this line is all whitespace, drop it.
217 if cur_line and cur_line[-1].strip() == '':
218 del cur_line[-1]
219
220 # Convert current line back to a string and store it in list
221 # of all lines (return value).
222 if cur_line:
Greg Ward62080be2002-06-10 21:37:12 +0000223 lines.append(indent + ''.join(cur_line))
Greg Ward00935822002-06-07 21:43:37 +0000224
225 return lines
226
227
228 # -- Public interface ----------------------------------------------
229
Greg Wardd34c9592002-06-10 20:26:02 +0000230 def wrap(self, text):
231 """wrap(text : string) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000232
Greg Warde807e572002-07-04 14:51:49 +0000233 Reformat the single paragraph in 'text' so it fits in lines of
234 no more than 'self.width' columns, and return a list of wrapped
235 lines. Tabs in 'text' are expanded with string.expandtabs(),
236 and all other whitespace characters (including newline) are
237 converted to space.
Greg Ward00935822002-06-07 21:43:37 +0000238 """
239 text = self._munge_whitespace(text)
Greg Wardd34c9592002-06-10 20:26:02 +0000240 if len(text) <= self.width:
Greg Ward00935822002-06-07 21:43:37 +0000241 return [text]
242 chunks = self._split(text)
Greg Ward62e4f3b2002-06-07 21:56:16 +0000243 if self.fix_sentence_endings:
244 self._fix_sentence_endings(chunks)
Greg Wardd34c9592002-06-10 20:26:02 +0000245 return self._wrap_chunks(chunks)
Greg Ward00935822002-06-07 21:43:37 +0000246
Greg Ward62080be2002-06-10 21:37:12 +0000247 def fill(self, text):
248 """fill(text : string) -> string
Greg Ward00935822002-06-07 21:43:37 +0000249
Greg Warde807e572002-07-04 14:51:49 +0000250 Reformat the single paragraph in 'text' to fit in lines of no
251 more than 'self.width' columns, and return a new string
252 containing the entire wrapped paragraph.
Greg Ward00935822002-06-07 21:43:37 +0000253 """
Greg Ward62080be2002-06-10 21:37:12 +0000254 return "\n".join(self.wrap(text))
Greg Ward00935822002-06-07 21:43:37 +0000255
256
Greg Warde807e572002-07-04 14:51:49 +0000257# -- Convenience interface ---------------------------------------------
Greg Ward00935822002-06-07 21:43:37 +0000258
Greg Wardcf02ac62002-06-10 20:36:07 +0000259def wrap(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000260 """Wrap a single paragraph of text, returning a list of wrapped lines.
261
262 Reformat the single paragraph in 'text' so it fits in lines of no
263 more than 'width' columns, and return a list of wrapped lines. By
264 default, tabs in 'text' are expanded with string.expandtabs(), and
265 all other whitespace characters (including newline) are converted to
266 space. See TextWrapper class for available keyword args to customize
267 wrapping behaviour.
268 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000269 w = TextWrapper(width=width, **kwargs)
270 return w.wrap(text)
Greg Ward00935822002-06-07 21:43:37 +0000271
Greg Ward62080be2002-06-10 21:37:12 +0000272def fill(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000273 """Fill a single paragraph of text, returning a new string.
274
275 Reformat the single paragraph in 'text' to fit in lines of no more
276 than 'width' columns, and return a new string containing the entire
277 wrapped paragraph. As with wrap(), tabs are expanded and other
278 whitespace characters converted to space. See TextWrapper class for
279 available keyword args to customize wrapping behaviour.
280 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000281 w = TextWrapper(width=width, **kwargs)
Greg Ward62080be2002-06-10 21:37:12 +0000282 return w.fill(text)