blob: 0c18dc582e17aec7344d38cf3693c95c94564ca1 [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
Benjamin Peterson274271d2011-06-28 10:25:04 -05008import re
Greg Ward00935822002-06-07 21:43:37 +00009
Serhiy Storchaka3e4b5282013-10-16 13:07:53 +030010__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten']
Greg Ward4c6c9c42003-02-03 14:46:57 +000011
Greg Wardafd44de2002-12-12 17:24:35 +000012# Hardcode the recognized whitespace characters to the US-ASCII
Serhiy Storchakaf3ebc9f2016-10-25 14:44:54 +030013# whitespace characters. The main reason for doing this is that
14# some Unicode spaces (like \u00a0) are non-breaking whitespaces.
Greg Ward4c6c9c42003-02-03 14:46:57 +000015_whitespace = '\t\n\x0b\x0c\r '
Greg Wardafd44de2002-12-12 17:24:35 +000016
Greg Ward00935822002-06-07 21:43:37 +000017class TextWrapper:
18 """
19 Object for wrapping/filling text. The public interface consists of
20 the wrap() and fill() methods; the other methods are just there for
21 subclasses to override in order to tweak the default behaviour.
22 If you want to completely replace the main wrapping algorithm,
23 you'll probably have to override _wrap_chunks().
24
Greg Wardd34c9592002-06-10 20:26:02 +000025 Several instance attributes control various aspects of wrapping:
26 width (default: 70)
27 the maximum width of wrapped lines (unless break_long_words
28 is false)
Greg Ward62080be2002-06-10 21:37:12 +000029 initial_indent (default: "")
30 string that will be prepended to the first line of wrapped
31 output. Counts towards the line's width.
32 subsequent_indent (default: "")
33 string that will be prepended to all lines save the first
34 of wrapped output; also counts towards each line's width.
Greg Ward62e4f3b2002-06-07 21:56:16 +000035 expand_tabs (default: true)
36 Expand tabs in input text to spaces before further processing.
Hynek Schlawackd5272592012-05-19 13:33:11 +020037 Each tab will become 0 .. 'tabsize' spaces, depending on its position
38 in its line. If false, each tab is treated as a single character.
39 tabsize (default: 8)
40 Expand tabs in input text to 0 .. 'tabsize' spaces, unless
41 'expand_tabs' is false.
Greg Ward62e4f3b2002-06-07 21:56:16 +000042 replace_whitespace (default: true)
43 Replace all whitespace characters in the input text by spaces
44 after tab expansion. Note that if expand_tabs is false and
45 replace_whitespace is true, every tab will be converted to a
46 single space!
47 fix_sentence_endings (default: false)
48 Ensure that sentence-ending punctuation is always followed
Andrew M. Kuchlinga2ecabe2003-02-14 01:14:15 +000049 by two spaces. Off by default because the algorithm is
Greg Ward62e4f3b2002-06-07 21:56:16 +000050 (unavoidably) imperfect.
51 break_long_words (default: true)
Greg Wardd34c9592002-06-10 20:26:02 +000052 Break words longer than 'width'. If false, those words will not
53 be broken, and some lines might be longer than 'width'.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000054 break_on_hyphens (default: true)
55 Allow breaking hyphenated words. If true, wrapping will occur
56 preferably on whitespaces and right after hyphens part of
57 compound words.
Guido van Rossumd8faa362007-04-27 19:54:29 +000058 drop_whitespace (default: true)
59 Drop leading and trailing whitespace from lines.
Serhiy Storchakaacc9f3f2013-10-15 21:22:54 +030060 max_lines (default: None)
61 Truncate wrapped lines.
62 placeholder (default: ' [...]')
63 Append to the last line of truncated text.
Greg Ward00935822002-06-07 21:43:37 +000064 """
65
Greg Ward2e745412002-12-09 16:23:08 +000066 unicode_whitespace_trans = {}
Guido van Rossumef87d6e2007-05-02 19:09:54 +000067 uspace = ord(' ')
Guido van Rossumc1f779c2007-07-03 08:25:58 +000068 for x in _whitespace:
69 unicode_whitespace_trans[ord(x)] = uspace
Greg Ward2e745412002-12-09 16:23:08 +000070
Tim Petersc411dba2002-07-16 21:35:23 +000071 # This funky little regex is just the trick for splitting
Greg Ward00935822002-06-07 21:43:37 +000072 # text up into word-wrappable chunks. E.g.
73 # "Hello there -- you goof-ball, use the -b option!"
74 # splits into
75 # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
76 # (after stripping out empty strings).
Serhiy Storchaka72bd3272015-03-24 18:32:27 +020077 word_punct = r'[\w!"\'&.,?]'
78 letter = r'[^\d\W]'
Serhiy Storchakaf3ebc9f2016-10-25 14:44:54 +030079 whitespace = r'[%s]' % re.escape(_whitespace)
80 nowhitespace = '[^' + whitespace[1:]
Serhiy Storchaka72bd3272015-03-24 18:32:27 +020081 wordsep_re = re.compile(r'''
82 ( # any whitespace
Serhiy Storchakaf3ebc9f2016-10-25 14:44:54 +030083 %(ws)s+
Serhiy Storchaka72bd3272015-03-24 18:32:27 +020084 | # em-dash between words
85 (?<=%(wp)s) -{2,} (?=\w)
86 | # word, possibly hyphenated
Serhiy Storchakaf3ebc9f2016-10-25 14:44:54 +030087 %(nws)s+? (?:
Serhiy Storchaka72bd3272015-03-24 18:32:27 +020088 # hyphenated word
89 -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))
90 (?= %(lt)s -? %(lt)s)
91 | # end of word
Serhiy Storchakaf3ebc9f2016-10-25 14:44:54 +030092 (?=%(ws)s|\Z)
Serhiy Storchaka72bd3272015-03-24 18:32:27 +020093 | # em-dash
94 (?<=%(wp)s) (?=-{2,}\w)
95 )
Serhiy Storchakaf3ebc9f2016-10-25 14:44:54 +030096 )''' % {'wp': word_punct, 'lt': letter,
97 'ws': whitespace, 'nws': nowhitespace},
98 re.VERBOSE)
99 del word_punct, letter, nowhitespace
Greg Ward00935822002-06-07 21:43:37 +0000100
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000101 # This less funky little regex just split on recognized spaces. E.g.
102 # "Hello there -- you goof-ball, use the -b option!"
103 # splits into
104 # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
Serhiy Storchakaf3ebc9f2016-10-25 14:44:54 +0300105 wordsep_simple_re = re.compile(r'(%s+)' % whitespace)
106 del whitespace
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000107
108 # XXX this is not locale- or charset-aware -- string.lowercase
109 # is US-ASCII only (and therefore English-only)
Guido van Rossum9264ecd2007-08-11 16:40:13 +0000110 sentence_end_re = re.compile(r'[a-z]' # lowercase letter
Greg Ward9b4864e2002-06-07 22:04:15 +0000111 r'[\.\!\?]' # sentence-ending punct.
112 r'[\"\']?' # optional end-of-quote
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000113 r'\Z') # end of chunk
Greg Ward62e4f3b2002-06-07 21:56:16 +0000114
Greg Wardf0ba7642004-05-13 01:53:10 +0000115 def __init__(self,
116 width=70,
117 initial_indent="",
118 subsequent_indent="",
119 expand_tabs=True,
120 replace_whitespace=True,
121 fix_sentence_endings=False,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000122 break_long_words=True,
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000123 drop_whitespace=True,
Hynek Schlawackd5272592012-05-19 13:33:11 +0200124 break_on_hyphens=True,
Serhiy Storchakaacc9f3f2013-10-15 21:22:54 +0300125 tabsize=8,
126 *,
127 max_lines=None,
128 placeholder=' [...]'):
Greg Wardd34c9592002-06-10 20:26:02 +0000129 self.width = width
Greg Ward62080be2002-06-10 21:37:12 +0000130 self.initial_indent = initial_indent
131 self.subsequent_indent = subsequent_indent
Greg Ward47df99d2002-06-09 00:22:07 +0000132 self.expand_tabs = expand_tabs
133 self.replace_whitespace = replace_whitespace
134 self.fix_sentence_endings = fix_sentence_endings
135 self.break_long_words = break_long_words
Guido van Rossumd8faa362007-04-27 19:54:29 +0000136 self.drop_whitespace = drop_whitespace
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000137 self.break_on_hyphens = break_on_hyphens
Hynek Schlawackd5272592012-05-19 13:33:11 +0200138 self.tabsize = tabsize
Serhiy Storchakaacc9f3f2013-10-15 21:22:54 +0300139 self.max_lines = max_lines
140 self.placeholder = placeholder
Tim Petersc411dba2002-07-16 21:35:23 +0000141
Greg Ward00935822002-06-07 21:43:37 +0000142
143 # -- Private methods -----------------------------------------------
144 # (possibly useful for subclasses to override)
145
Greg Wardcb320eb2002-06-07 22:32:15 +0000146 def _munge_whitespace(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000147 """_munge_whitespace(text : string) -> string
148
149 Munge whitespace in text: expand tabs and convert all other
Serhiy Storchaka9f8a8912015-04-03 18:12:41 +0300150 whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
Greg Ward00935822002-06-07 21:43:37 +0000151 becomes " foo bar baz".
152 """
153 if self.expand_tabs:
Hynek Schlawackd5272592012-05-19 13:33:11 +0200154 text = text.expandtabs(self.tabsize)
Greg Ward00935822002-06-07 21:43:37 +0000155 if self.replace_whitespace:
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000156 text = text.translate(self.unicode_whitespace_trans)
Greg Ward00935822002-06-07 21:43:37 +0000157 return text
158
159
Greg Wardcb320eb2002-06-07 22:32:15 +0000160 def _split(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000161 """_split(text : string) -> [string]
162
163 Split the text to wrap into indivisible chunks. Chunks are
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000164 not quite the same as words; see _wrap_chunks() for full
Greg Ward00935822002-06-07 21:43:37 +0000165 details. As an example, the text
166 Look, goof-ball -- use the -b option!
167 breaks into the following chunks:
168 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
169 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000170 if break_on_hyphens is True, or in:
171 'Look,', ' ', 'goof-ball', ' ', '--', ' ',
172 'use', ' ', 'the', ' ', '-b', ' ', option!'
173 otherwise.
Greg Ward00935822002-06-07 21:43:37 +0000174 """
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000175 if self.break_on_hyphens is True:
176 chunks = self.wordsep_re.split(text)
177 else:
178 chunks = self.wordsep_simple_re.split(text)
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000179 chunks = [c for c in chunks if c]
Greg Ward00935822002-06-07 21:43:37 +0000180 return chunks
181
Greg Wardcb320eb2002-06-07 22:32:15 +0000182 def _fix_sentence_endings(self, chunks):
Greg Ward00935822002-06-07 21:43:37 +0000183 """_fix_sentence_endings(chunks : [string])
184
185 Correct for sentence endings buried in 'chunks'. Eg. when the
Serhiy Storchaka9f8a8912015-04-03 18:12:41 +0300186 original text contains "... foo.\\nBar ...", munge_whitespace()
Greg Ward00935822002-06-07 21:43:37 +0000187 and split() will convert that to [..., "foo.", " ", "Bar", ...]
188 which has one too few spaces; this method simply changes the one
189 space to two.
190 """
191 i = 0
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000192 patsearch = self.sentence_end_re.search
Greg Ward00935822002-06-07 21:43:37 +0000193 while i < len(chunks)-1:
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000194 if chunks[i+1] == " " and patsearch(chunks[i]):
Greg Ward00935822002-06-07 21:43:37 +0000195 chunks[i+1] = " "
196 i += 2
197 else:
198 i += 1
199
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000200 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
Greg Ward00935822002-06-07 21:43:37 +0000201 """_handle_long_word(chunks : [string],
202 cur_line : [string],
Greg Ward62080be2002-06-10 21:37:12 +0000203 cur_len : int, width : int)
Greg Ward00935822002-06-07 21:43:37 +0000204
205 Handle a chunk of text (most likely a word, not whitespace) that
206 is too long to fit in any line.
207 """
Georg Brandlfceab5a2008-01-19 20:08:23 +0000208 # Figure out when indent is larger than the specified width, and make
209 # sure at least one character is stripped off on every pass
210 if width < 1:
211 space_left = 1
212 else:
213 space_left = width - cur_len
Greg Ward00935822002-06-07 21:43:37 +0000214
215 # If we're allowed to break long words, then do so: put as much
216 # of the next chunk onto the current line as will fit.
217 if self.break_long_words:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000218 cur_line.append(reversed_chunks[-1][:space_left])
219 reversed_chunks[-1] = reversed_chunks[-1][space_left:]
Greg Ward00935822002-06-07 21:43:37 +0000220
221 # Otherwise, we have to preserve the long word intact. Only add
222 # it to the current line if there's nothing already there --
223 # that minimizes how much we violate the width constraint.
224 elif not cur_line:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000225 cur_line.append(reversed_chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000226
227 # If we're not allowed to break long words, and there's already
228 # text on the current line, do nothing. Next time through the
229 # main loop of _wrap_chunks(), we'll wind up here again, but
230 # cur_len will be zero, so the next line will be entirely
231 # devoted to the long word that we can't handle right now.
232
Greg Wardd34c9592002-06-10 20:26:02 +0000233 def _wrap_chunks(self, chunks):
234 """_wrap_chunks(chunks : [string]) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000235
236 Wrap a sequence of text chunks and return a list of lines of
Greg Wardd34c9592002-06-10 20:26:02 +0000237 length 'self.width' or less. (If 'break_long_words' is false,
238 some lines may be longer than this.) Chunks correspond roughly
239 to words and the whitespace between them: each chunk is
240 indivisible (modulo 'break_long_words'), but a line break can
241 come between any two chunks. Chunks should not have internal
242 whitespace; ie. a chunk is either all whitespace or a "word".
243 Whitespace chunks will be removed from the beginning and end of
244 lines, but apart from that whitespace is preserved.
Greg Ward00935822002-06-07 21:43:37 +0000245 """
246 lines = []
Greg Ward21820cd2003-05-07 00:55:35 +0000247 if self.width <= 0:
248 raise ValueError("invalid width %r (must be > 0)" % self.width)
Serhiy Storchakaacc9f3f2013-10-15 21:22:54 +0300249 if self.max_lines is not None:
250 if self.max_lines > 1:
251 indent = self.subsequent_indent
252 else:
253 indent = self.initial_indent
254 if len(indent) + len(self.placeholder.lstrip()) > self.width:
255 raise ValueError("placeholder too large for max width")
Greg Ward00935822002-06-07 21:43:37 +0000256
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000257 # Arrange in reverse order so items can be efficiently popped
258 # from a stack of chucks.
259 chunks.reverse()
260
Greg Ward00935822002-06-07 21:43:37 +0000261 while chunks:
262
Greg Ward62080be2002-06-10 21:37:12 +0000263 # Start the list of chunks that will make up the current line.
264 # cur_len is just the length of all the chunks in cur_line.
265 cur_line = []
266 cur_len = 0
267
268 # Figure out which static string will prefix this line.
269 if lines:
270 indent = self.subsequent_indent
271 else:
272 indent = self.initial_indent
273
274 # Maximum width for this line.
275 width = self.width - len(indent)
Greg Ward00935822002-06-07 21:43:37 +0000276
Greg Wardab73d462002-12-09 16:26:05 +0000277 # First chunk on line is whitespace -- drop it, unless this
278 # is the very beginning of the text (ie. no lines started yet).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000279 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000280 del chunks[-1]
Greg Ward00935822002-06-07 21:43:37 +0000281
282 while chunks:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000283 l = len(chunks[-1])
Greg Ward00935822002-06-07 21:43:37 +0000284
285 # Can at least squeeze this chunk onto the current line.
286 if cur_len + l <= width:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000287 cur_line.append(chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000288 cur_len += l
289
290 # Nope, this line is full.
291 else:
292 break
293
294 # The current line is full, and the next chunk is too big to
Tim Petersc411dba2002-07-16 21:35:23 +0000295 # fit on *any* line (not just this one).
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000296 if chunks and len(chunks[-1]) > width:
Greg Ward62080be2002-06-10 21:37:12 +0000297 self._handle_long_word(chunks, cur_line, cur_len, width)
Serhiy Storchakaacc9f3f2013-10-15 21:22:54 +0300298 cur_len = sum(map(len, cur_line))
Greg Ward00935822002-06-07 21:43:37 +0000299
300 # If the last chunk on this line is all whitespace, drop it.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000301 if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
Serhiy Storchakaacc9f3f2013-10-15 21:22:54 +0300302 cur_len -= len(cur_line[-1])
Greg Ward00935822002-06-07 21:43:37 +0000303 del cur_line[-1]
304
Greg Ward00935822002-06-07 21:43:37 +0000305 if cur_line:
Serhiy Storchakaacc9f3f2013-10-15 21:22:54 +0300306 if (self.max_lines is None or
307 len(lines) + 1 < self.max_lines or
308 (not chunks or
309 self.drop_whitespace and
310 len(chunks) == 1 and
311 not chunks[0].strip()) and cur_len <= width):
312 # Convert current line back to a string and store it in
313 # list of all lines (return value).
314 lines.append(indent + ''.join(cur_line))
315 else:
316 while cur_line:
317 if (cur_line[-1].strip() and
318 cur_len + len(self.placeholder) <= width):
319 cur_line.append(self.placeholder)
320 lines.append(indent + ''.join(cur_line))
321 break
322 cur_len -= len(cur_line[-1])
323 del cur_line[-1]
324 else:
325 if lines:
326 prev_line = lines[-1].rstrip()
327 if (len(prev_line) + len(self.placeholder) <=
328 self.width):
329 lines[-1] = prev_line + self.placeholder
330 break
331 lines.append(indent + self.placeholder.lstrip())
332 break
Greg Ward00935822002-06-07 21:43:37 +0000333
334 return lines
335
Antoine Pitrou389dec82013-08-12 22:39:09 +0200336 def _split_chunks(self, text):
337 text = self._munge_whitespace(text)
338 return self._split(text)
Greg Ward00935822002-06-07 21:43:37 +0000339
340 # -- Public interface ----------------------------------------------
341
Greg Wardd34c9592002-06-10 20:26:02 +0000342 def wrap(self, text):
343 """wrap(text : string) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000344
Greg Warde807e572002-07-04 14:51:49 +0000345 Reformat the single paragraph in 'text' so it fits in lines of
346 no more than 'self.width' columns, and return a list of wrapped
347 lines. Tabs in 'text' are expanded with string.expandtabs(),
348 and all other whitespace characters (including newline) are
349 converted to space.
Greg Ward00935822002-06-07 21:43:37 +0000350 """
Antoine Pitrou389dec82013-08-12 22:39:09 +0200351 chunks = self._split_chunks(text)
Greg Ward62e4f3b2002-06-07 21:56:16 +0000352 if self.fix_sentence_endings:
353 self._fix_sentence_endings(chunks)
Greg Wardd34c9592002-06-10 20:26:02 +0000354 return self._wrap_chunks(chunks)
Greg Ward00935822002-06-07 21:43:37 +0000355
Greg Ward62080be2002-06-10 21:37:12 +0000356 def fill(self, text):
357 """fill(text : string) -> string
Greg Ward00935822002-06-07 21:43:37 +0000358
Greg Warde807e572002-07-04 14:51:49 +0000359 Reformat the single paragraph in 'text' to fit in lines of no
360 more than 'self.width' columns, and return a new string
361 containing the entire wrapped paragraph.
Greg Ward00935822002-06-07 21:43:37 +0000362 """
Greg Ward62080be2002-06-10 21:37:12 +0000363 return "\n".join(self.wrap(text))
Greg Ward00935822002-06-07 21:43:37 +0000364
365
Greg Warde807e572002-07-04 14:51:49 +0000366# -- Convenience interface ---------------------------------------------
Greg Ward00935822002-06-07 21:43:37 +0000367
Greg Wardcf02ac62002-06-10 20:36:07 +0000368def wrap(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000369 """Wrap a single paragraph of text, returning a list of wrapped lines.
370
371 Reformat the single paragraph in 'text' so it fits in lines of no
372 more than 'width' columns, and return a list of wrapped lines. By
373 default, tabs in 'text' are expanded with string.expandtabs(), and
374 all other whitespace characters (including newline) are converted to
375 space. See TextWrapper class for available keyword args to customize
376 wrapping behaviour.
377 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000378 w = TextWrapper(width=width, **kwargs)
379 return w.wrap(text)
Greg Ward00935822002-06-07 21:43:37 +0000380
Greg Ward62080be2002-06-10 21:37:12 +0000381def fill(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000382 """Fill a single paragraph of text, returning a new string.
383
384 Reformat the single paragraph in 'text' to fit in lines of no more
385 than 'width' columns, and return a new string containing the entire
386 wrapped paragraph. As with wrap(), tabs are expanded and other
387 whitespace characters converted to space. See TextWrapper class for
388 available keyword args to customize wrapping behaviour.
389 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000390 w = TextWrapper(width=width, **kwargs)
Greg Ward62080be2002-06-10 21:37:12 +0000391 return w.fill(text)
Greg Ward478cd482003-05-08 01:58:05 +0000392
Serhiy Storchakaacc9f3f2013-10-15 21:22:54 +0300393def shorten(text, width, **kwargs):
Antoine Pitrou389dec82013-08-12 22:39:09 +0200394 """Collapse and truncate the given text to fit in the given width.
395
396 The text first has its whitespace collapsed. If it then fits in
397 the *width*, it is returned as is. Otherwise, as many words
398 as possible are joined and then the placeholder is appended::
399
400 >>> textwrap.shorten("Hello world!", width=12)
401 'Hello world!'
402 >>> textwrap.shorten("Hello world!", width=11)
Antoine Pitrouc5930562013-08-16 22:31:12 +0200403 'Hello [...]'
Antoine Pitrou389dec82013-08-12 22:39:09 +0200404 """
Serhiy Storchakaacc9f3f2013-10-15 21:22:54 +0300405 w = TextWrapper(width=width, max_lines=1, **kwargs)
406 return w.fill(' '.join(text.strip().split()))
Antoine Pitrou389dec82013-08-12 22:39:09 +0200407
Greg Ward478cd482003-05-08 01:58:05 +0000408
409# -- Loosely related functionality -------------------------------------
410
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000411_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
412_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
413
Greg Ward478cd482003-05-08 01:58:05 +0000414def dedent(text):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000415 """Remove any common leading whitespace from every line in `text`.
Greg Ward478cd482003-05-08 01:58:05 +0000416
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000417 This can be used to make triple-quoted strings line up with the left
418 edge of the display, while still presenting them in the source code
419 in indented form.
Greg Ward478cd482003-05-08 01:58:05 +0000420
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000421 Note that tabs and spaces are both treated as whitespace, but they
Serhiy Storchaka9f8a8912015-04-03 18:12:41 +0300422 are not equal: the lines " hello" and "\\thello" are
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000423 considered to have no common leading whitespace. (This behaviour is
424 new in Python 2.5; older versions of this module incorrectly
425 expanded tabs before searching for common leading whitespace.)
Greg Ward478cd482003-05-08 01:58:05 +0000426 """
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000427 # Look for the longest leading string of spaces and tabs common to
428 # all lines.
Greg Ward478cd482003-05-08 01:58:05 +0000429 margin = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000430 text = _whitespace_only_re.sub('', text)
431 indents = _leading_whitespace_re.findall(text)
432 for indent in indents:
Greg Ward478cd482003-05-08 01:58:05 +0000433 if margin is None:
434 margin = indent
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000435
436 # Current line more deeply indented than previous winner:
437 # no change (previous winner is still on top).
438 elif indent.startswith(margin):
439 pass
440
441 # Current line consistent with and no deeper than previous winner:
442 # it's the new winner.
443 elif margin.startswith(indent):
444 margin = indent
445
Serhiy Storchakaea4cb632015-10-28 21:39:36 +0200446 # Find the largest common whitespace between current line and previous
447 # winner.
Greg Ward478cd482003-05-08 01:58:05 +0000448 else:
Serhiy Storchakaea4cb632015-10-28 21:39:36 +0200449 for i, (x, y) in enumerate(zip(margin, indent)):
450 if x != y:
451 margin = margin[:i]
452 break
453 else:
454 margin = margin[:len(indent)]
Greg Ward478cd482003-05-08 01:58:05 +0000455
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000456 # sanity check (testing/debugging only)
457 if 0 and margin:
458 for line in text.split("\n"):
459 assert not line or line.startswith(margin), \
460 "line = %r, margin = %r" % (line, margin)
Greg Ward478cd482003-05-08 01:58:05 +0000461
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000462 if margin:
463 text = re.sub(r'(?m)^' + margin, '', text)
464 return text
465
Nick Coghlan4fae8cd2012-06-11 23:07:51 +1000466
467def indent(text, prefix, predicate=None):
468 """Adds 'prefix' to the beginning of selected lines in 'text'.
469
470 If 'predicate' is provided, 'prefix' will only be added to the lines
471 where 'predicate(line)' is True. If 'predicate' is not provided,
472 it will default to adding 'prefix' to all non-empty lines that do not
473 consist solely of whitespace characters.
474 """
475 if predicate is None:
476 def predicate(line):
477 return line.strip()
478
479 def prefixed_lines():
480 for line in text.splitlines(True):
481 yield (prefix + line if predicate(line) else line)
482 return ''.join(prefixed_lines())
483
484
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000485if __name__ == "__main__":
486 #print dedent("\tfoo\n\tbar")
487 #print dedent(" \thello there\n \t how are you?")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000488 print(dedent("Hello there.\n This is indented."))