blob: 27ebc16e16cc79d666b98011155d76b3c27c983f [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
Nick Coghlan4fae8cd2012-06-11 23:07:51 +100010__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent']
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
13# whitespace characters. The main reason for doing this is that in
14# ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales
15# that character winds up in string.whitespace. Respecting
16# string.whitespace in those cases would 1) make textwrap treat 0xa0 the
17# same as any other whitespace char, which is clearly wrong (it's a
18# *non-breaking* space), 2) possibly cause problems with Unicode,
19# since 0xa0 is not in range(128).
Greg Ward4c6c9c42003-02-03 14:46:57 +000020_whitespace = '\t\n\x0b\x0c\r '
Greg Wardafd44de2002-12-12 17:24:35 +000021
Antoine Pitrouc5930562013-08-16 22:31:12 +020022_default_placeholder = ' [...]'
Antoine Pitrou389dec82013-08-12 22:39:09 +020023
Greg Ward00935822002-06-07 21:43:37 +000024class TextWrapper:
25 """
26 Object for wrapping/filling text. The public interface consists of
27 the wrap() and fill() methods; the other methods are just there for
28 subclasses to override in order to tweak the default behaviour.
29 If you want to completely replace the main wrapping algorithm,
30 you'll probably have to override _wrap_chunks().
31
Greg Wardd34c9592002-06-10 20:26:02 +000032 Several instance attributes control various aspects of wrapping:
33 width (default: 70)
34 the maximum width of wrapped lines (unless break_long_words
35 is false)
Greg Ward62080be2002-06-10 21:37:12 +000036 initial_indent (default: "")
37 string that will be prepended to the first line of wrapped
38 output. Counts towards the line's width.
39 subsequent_indent (default: "")
40 string that will be prepended to all lines save the first
41 of wrapped output; also counts towards each line's width.
Greg Ward62e4f3b2002-06-07 21:56:16 +000042 expand_tabs (default: true)
43 Expand tabs in input text to spaces before further processing.
Hynek Schlawackd5272592012-05-19 13:33:11 +020044 Each tab will become 0 .. 'tabsize' spaces, depending on its position
45 in its line. If false, each tab is treated as a single character.
46 tabsize (default: 8)
47 Expand tabs in input text to 0 .. 'tabsize' spaces, unless
48 'expand_tabs' is false.
Greg Ward62e4f3b2002-06-07 21:56:16 +000049 replace_whitespace (default: true)
50 Replace all whitespace characters in the input text by spaces
51 after tab expansion. Note that if expand_tabs is false and
52 replace_whitespace is true, every tab will be converted to a
53 single space!
54 fix_sentence_endings (default: false)
55 Ensure that sentence-ending punctuation is always followed
Andrew M. Kuchlinga2ecabe2003-02-14 01:14:15 +000056 by two spaces. Off by default because the algorithm is
Greg Ward62e4f3b2002-06-07 21:56:16 +000057 (unavoidably) imperfect.
58 break_long_words (default: true)
Greg Wardd34c9592002-06-10 20:26:02 +000059 Break words longer than 'width'. If false, those words will not
60 be broken, and some lines might be longer than 'width'.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000061 break_on_hyphens (default: true)
62 Allow breaking hyphenated words. If true, wrapping will occur
63 preferably on whitespaces and right after hyphens part of
64 compound words.
Guido van Rossumd8faa362007-04-27 19:54:29 +000065 drop_whitespace (default: true)
66 Drop leading and trailing whitespace from lines.
Greg Ward00935822002-06-07 21:43:37 +000067 """
68
Greg Ward2e745412002-12-09 16:23:08 +000069 unicode_whitespace_trans = {}
Guido van Rossumef87d6e2007-05-02 19:09:54 +000070 uspace = ord(' ')
Guido van Rossumc1f779c2007-07-03 08:25:58 +000071 for x in _whitespace:
72 unicode_whitespace_trans[ord(x)] = uspace
Greg Ward2e745412002-12-09 16:23:08 +000073
Tim Petersc411dba2002-07-16 21:35:23 +000074 # This funky little regex is just the trick for splitting
Greg Ward00935822002-06-07 21:43:37 +000075 # text up into word-wrappable chunks. E.g.
76 # "Hello there -- you goof-ball, use the -b option!"
77 # splits into
78 # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
79 # (after stripping out empty strings).
Greg Ward40407942005-03-05 02:53:17 +000080 wordsep_re = re.compile(
81 r'(\s+|' # any whitespace
Antoine Pitrou7c59bc62008-12-13 23:20:54 +000082 r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words
Greg Ward40407942005-03-05 02:53:17 +000083 r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
Greg Ward00935822002-06-07 21:43:37 +000084
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000085 # This less funky little regex just split on recognized spaces. E.g.
86 # "Hello there -- you goof-ball, use the -b option!"
87 # splits into
88 # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
89 wordsep_simple_re = re.compile(r'(\s+)')
90
91 # XXX this is not locale- or charset-aware -- string.lowercase
92 # is US-ASCII only (and therefore English-only)
Guido van Rossum9264ecd2007-08-11 16:40:13 +000093 sentence_end_re = re.compile(r'[a-z]' # lowercase letter
Greg Ward9b4864e2002-06-07 22:04:15 +000094 r'[\.\!\?]' # sentence-ending punct.
95 r'[\"\']?' # optional end-of-quote
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000096 r'\Z') # end of chunk
Greg Ward62e4f3b2002-06-07 21:56:16 +000097
Greg Ward00935822002-06-07 21:43:37 +000098
Greg Wardf0ba7642004-05-13 01:53:10 +000099 def __init__(self,
100 width=70,
101 initial_indent="",
102 subsequent_indent="",
103 expand_tabs=True,
104 replace_whitespace=True,
105 fix_sentence_endings=False,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000106 break_long_words=True,
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000107 drop_whitespace=True,
Hynek Schlawackd5272592012-05-19 13:33:11 +0200108 break_on_hyphens=True,
109 tabsize=8):
Greg Wardd34c9592002-06-10 20:26:02 +0000110 self.width = width
Greg Ward62080be2002-06-10 21:37:12 +0000111 self.initial_indent = initial_indent
112 self.subsequent_indent = subsequent_indent
Greg Ward47df99d2002-06-09 00:22:07 +0000113 self.expand_tabs = expand_tabs
114 self.replace_whitespace = replace_whitespace
115 self.fix_sentence_endings = fix_sentence_endings
116 self.break_long_words = break_long_words
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117 self.drop_whitespace = drop_whitespace
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000118 self.break_on_hyphens = break_on_hyphens
Hynek Schlawackd5272592012-05-19 13:33:11 +0200119 self.tabsize = tabsize
Tim Petersc411dba2002-07-16 21:35:23 +0000120
Greg Ward00935822002-06-07 21:43:37 +0000121
122 # -- Private methods -----------------------------------------------
123 # (possibly useful for subclasses to override)
124
Greg Wardcb320eb2002-06-07 22:32:15 +0000125 def _munge_whitespace(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000126 """_munge_whitespace(text : string) -> string
127
128 Munge whitespace in text: expand tabs and convert all other
129 whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
130 becomes " foo bar baz".
131 """
132 if self.expand_tabs:
Hynek Schlawackd5272592012-05-19 13:33:11 +0200133 text = text.expandtabs(self.tabsize)
Greg Ward00935822002-06-07 21:43:37 +0000134 if self.replace_whitespace:
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000135 text = text.translate(self.unicode_whitespace_trans)
Greg Ward00935822002-06-07 21:43:37 +0000136 return text
137
138
Greg Wardcb320eb2002-06-07 22:32:15 +0000139 def _split(self, text):
Greg Ward00935822002-06-07 21:43:37 +0000140 """_split(text : string) -> [string]
141
142 Split the text to wrap into indivisible chunks. Chunks are
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000143 not quite the same as words; see _wrap_chunks() for full
Greg Ward00935822002-06-07 21:43:37 +0000144 details. As an example, the text
145 Look, goof-ball -- use the -b option!
146 breaks into the following chunks:
147 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
148 'use', ' ', 'the', ' ', '-b', ' ', 'option!'
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000149 if break_on_hyphens is True, or in:
150 'Look,', ' ', 'goof-ball', ' ', '--', ' ',
151 'use', ' ', 'the', ' ', '-b', ' ', option!'
152 otherwise.
Greg Ward00935822002-06-07 21:43:37 +0000153 """
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000154 if self.break_on_hyphens is True:
155 chunks = self.wordsep_re.split(text)
156 else:
157 chunks = self.wordsep_simple_re.split(text)
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000158 chunks = [c for c in chunks if c]
Greg Ward00935822002-06-07 21:43:37 +0000159 return chunks
160
Greg Wardcb320eb2002-06-07 22:32:15 +0000161 def _fix_sentence_endings(self, chunks):
Greg Ward00935822002-06-07 21:43:37 +0000162 """_fix_sentence_endings(chunks : [string])
163
164 Correct for sentence endings buried in 'chunks'. Eg. when the
165 original text contains "... foo.\nBar ...", munge_whitespace()
166 and split() will convert that to [..., "foo.", " ", "Bar", ...]
167 which has one too few spaces; this method simply changes the one
168 space to two.
169 """
170 i = 0
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000171 patsearch = self.sentence_end_re.search
Greg Ward00935822002-06-07 21:43:37 +0000172 while i < len(chunks)-1:
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000173 if chunks[i+1] == " " and patsearch(chunks[i]):
Greg Ward00935822002-06-07 21:43:37 +0000174 chunks[i+1] = " "
175 i += 2
176 else:
177 i += 1
178
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000179 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
Greg Ward00935822002-06-07 21:43:37 +0000180 """_handle_long_word(chunks : [string],
181 cur_line : [string],
Greg Ward62080be2002-06-10 21:37:12 +0000182 cur_len : int, width : int)
Greg Ward00935822002-06-07 21:43:37 +0000183
184 Handle a chunk of text (most likely a word, not whitespace) that
185 is too long to fit in any line.
186 """
Georg Brandlfceab5a2008-01-19 20:08:23 +0000187 # Figure out when indent is larger than the specified width, and make
188 # sure at least one character is stripped off on every pass
189 if width < 1:
190 space_left = 1
191 else:
192 space_left = width - cur_len
Greg Ward00935822002-06-07 21:43:37 +0000193
194 # If we're allowed to break long words, then do so: put as much
195 # of the next chunk onto the current line as will fit.
196 if self.break_long_words:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000197 cur_line.append(reversed_chunks[-1][:space_left])
198 reversed_chunks[-1] = reversed_chunks[-1][space_left:]
Greg Ward00935822002-06-07 21:43:37 +0000199
200 # Otherwise, we have to preserve the long word intact. Only add
201 # it to the current line if there's nothing already there --
202 # that minimizes how much we violate the width constraint.
203 elif not cur_line:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000204 cur_line.append(reversed_chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000205
206 # If we're not allowed to break long words, and there's already
207 # text on the current line, do nothing. Next time through the
208 # main loop of _wrap_chunks(), we'll wind up here again, but
209 # cur_len will be zero, so the next line will be entirely
210 # devoted to the long word that we can't handle right now.
211
Greg Wardd34c9592002-06-10 20:26:02 +0000212 def _wrap_chunks(self, chunks):
213 """_wrap_chunks(chunks : [string]) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000214
215 Wrap a sequence of text chunks and return a list of lines of
Greg Wardd34c9592002-06-10 20:26:02 +0000216 length 'self.width' or less. (If 'break_long_words' is false,
217 some lines may be longer than this.) Chunks correspond roughly
218 to words and the whitespace between them: each chunk is
219 indivisible (modulo 'break_long_words'), but a line break can
220 come between any two chunks. Chunks should not have internal
221 whitespace; ie. a chunk is either all whitespace or a "word".
222 Whitespace chunks will be removed from the beginning and end of
223 lines, but apart from that whitespace is preserved.
Greg Ward00935822002-06-07 21:43:37 +0000224 """
225 lines = []
Greg Ward21820cd2003-05-07 00:55:35 +0000226 if self.width <= 0:
227 raise ValueError("invalid width %r (must be > 0)" % self.width)
Greg Ward00935822002-06-07 21:43:37 +0000228
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000229 # Arrange in reverse order so items can be efficiently popped
230 # from a stack of chucks.
231 chunks.reverse()
232
Greg Ward00935822002-06-07 21:43:37 +0000233 while chunks:
234
Greg Ward62080be2002-06-10 21:37:12 +0000235 # Start the list of chunks that will make up the current line.
236 # cur_len is just the length of all the chunks in cur_line.
237 cur_line = []
238 cur_len = 0
239
240 # Figure out which static string will prefix this line.
241 if lines:
242 indent = self.subsequent_indent
243 else:
244 indent = self.initial_indent
245
246 # Maximum width for this line.
247 width = self.width - len(indent)
Greg Ward00935822002-06-07 21:43:37 +0000248
Greg Wardab73d462002-12-09 16:26:05 +0000249 # First chunk on line is whitespace -- drop it, unless this
250 # is the very beginning of the text (ie. no lines started yet).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000251 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000252 del chunks[-1]
Greg Ward00935822002-06-07 21:43:37 +0000253
254 while chunks:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000255 l = len(chunks[-1])
Greg Ward00935822002-06-07 21:43:37 +0000256
257 # Can at least squeeze this chunk onto the current line.
258 if cur_len + l <= width:
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000259 cur_line.append(chunks.pop())
Greg Ward00935822002-06-07 21:43:37 +0000260 cur_len += l
261
262 # Nope, this line is full.
263 else:
264 break
265
266 # The current line is full, and the next chunk is too big to
Tim Petersc411dba2002-07-16 21:35:23 +0000267 # fit on *any* line (not just this one).
Raymond Hettinger8bfa8932005-07-15 06:53:35 +0000268 if chunks and len(chunks[-1]) > width:
Greg Ward62080be2002-06-10 21:37:12 +0000269 self._handle_long_word(chunks, cur_line, cur_len, width)
Greg Ward00935822002-06-07 21:43:37 +0000270
271 # If the last chunk on this line is all whitespace, drop it.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000272 if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
Greg Ward00935822002-06-07 21:43:37 +0000273 del cur_line[-1]
274
275 # Convert current line back to a string and store it in list
276 # of all lines (return value).
277 if cur_line:
Greg Ward62080be2002-06-10 21:37:12 +0000278 lines.append(indent + ''.join(cur_line))
Greg Ward00935822002-06-07 21:43:37 +0000279
280 return lines
281
Antoine Pitrou389dec82013-08-12 22:39:09 +0200282 def _split_chunks(self, text):
283 text = self._munge_whitespace(text)
284 return self._split(text)
Greg Ward00935822002-06-07 21:43:37 +0000285
286 # -- Public interface ----------------------------------------------
287
Greg Wardd34c9592002-06-10 20:26:02 +0000288 def wrap(self, text):
289 """wrap(text : string) -> [string]
Greg Ward00935822002-06-07 21:43:37 +0000290
Greg Warde807e572002-07-04 14:51:49 +0000291 Reformat the single paragraph in 'text' so it fits in lines of
292 no more than 'self.width' columns, and return a list of wrapped
293 lines. Tabs in 'text' are expanded with string.expandtabs(),
294 and all other whitespace characters (including newline) are
295 converted to space.
Greg Ward00935822002-06-07 21:43:37 +0000296 """
Antoine Pitrou389dec82013-08-12 22:39:09 +0200297 chunks = self._split_chunks(text)
Greg Ward62e4f3b2002-06-07 21:56:16 +0000298 if self.fix_sentence_endings:
299 self._fix_sentence_endings(chunks)
Greg Wardd34c9592002-06-10 20:26:02 +0000300 return self._wrap_chunks(chunks)
Greg Ward00935822002-06-07 21:43:37 +0000301
Greg Ward62080be2002-06-10 21:37:12 +0000302 def fill(self, text):
303 """fill(text : string) -> string
Greg Ward00935822002-06-07 21:43:37 +0000304
Greg Warde807e572002-07-04 14:51:49 +0000305 Reformat the single paragraph in 'text' to fit in lines of no
306 more than 'self.width' columns, and return a new string
307 containing the entire wrapped paragraph.
Greg Ward00935822002-06-07 21:43:37 +0000308 """
Greg Ward62080be2002-06-10 21:37:12 +0000309 return "\n".join(self.wrap(text))
Greg Ward00935822002-06-07 21:43:37 +0000310
Antoine Pitrou389dec82013-08-12 22:39:09 +0200311 def shorten(self, text, *, placeholder=_default_placeholder):
312 """shorten(text: str) -> str
313
314 Collapse and truncate the given text to fit in 'self.width' columns.
315 """
316 max_length = self.width
317 if max_length < len(placeholder.strip()):
318 raise ValueError("placeholder too large for max width")
319 sep = ' '
320 sep_len = len(sep)
321 parts = []
322 cur_len = 0
323 chunks = self._split_chunks(text)
324 for chunk in chunks:
325 if not chunk.strip():
326 continue
327 chunk_len = len(chunk) + sep_len if parts else len(chunk)
328 if cur_len + chunk_len > max_length:
329 break
330 parts.append(chunk)
331 cur_len += chunk_len
332 else:
333 # No truncation necessary
334 return sep.join(parts)
335 max_truncated_length = max_length - len(placeholder)
336 while parts and cur_len > max_truncated_length:
337 last = parts.pop()
338 cur_len -= len(last) + sep_len
339 return (sep.join(parts) + placeholder).strip()
340
Greg Ward00935822002-06-07 21:43:37 +0000341
Greg Warde807e572002-07-04 14:51:49 +0000342# -- Convenience interface ---------------------------------------------
Greg Ward00935822002-06-07 21:43:37 +0000343
Greg Wardcf02ac62002-06-10 20:36:07 +0000344def wrap(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000345 """Wrap a single paragraph of text, returning a list of wrapped lines.
346
347 Reformat the single paragraph in 'text' so it fits in lines of no
348 more than 'width' columns, and return a list of wrapped lines. By
349 default, tabs in 'text' are expanded with string.expandtabs(), and
350 all other whitespace characters (including newline) are converted to
351 space. See TextWrapper class for available keyword args to customize
352 wrapping behaviour.
353 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000354 w = TextWrapper(width=width, **kwargs)
355 return w.wrap(text)
Greg Ward00935822002-06-07 21:43:37 +0000356
Greg Ward62080be2002-06-10 21:37:12 +0000357def fill(text, width=70, **kwargs):
Greg Warde807e572002-07-04 14:51:49 +0000358 """Fill a single paragraph of text, returning a new string.
359
360 Reformat the single paragraph in 'text' to fit in lines of no more
361 than 'width' columns, and return a new string containing the entire
362 wrapped paragraph. As with wrap(), tabs are expanded and other
363 whitespace characters converted to space. See TextWrapper class for
364 available keyword args to customize wrapping behaviour.
365 """
Greg Wardcf02ac62002-06-10 20:36:07 +0000366 w = TextWrapper(width=width, **kwargs)
Greg Ward62080be2002-06-10 21:37:12 +0000367 return w.fill(text)
Greg Ward478cd482003-05-08 01:58:05 +0000368
Antoine Pitrou389dec82013-08-12 22:39:09 +0200369def shorten(text, width, *, placeholder=_default_placeholder, **kwargs):
370 """Collapse and truncate the given text to fit in the given width.
371
372 The text first has its whitespace collapsed. If it then fits in
373 the *width*, it is returned as is. Otherwise, as many words
374 as possible are joined and then the placeholder is appended::
375
376 >>> textwrap.shorten("Hello world!", width=12)
377 'Hello world!'
378 >>> textwrap.shorten("Hello world!", width=11)
Antoine Pitrouc5930562013-08-16 22:31:12 +0200379 'Hello [...]'
Antoine Pitrou389dec82013-08-12 22:39:09 +0200380 """
381 w = TextWrapper(width=width, **kwargs)
382 return w.shorten(text, placeholder=placeholder)
383
Greg Ward478cd482003-05-08 01:58:05 +0000384
385# -- Loosely related functionality -------------------------------------
386
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000387_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
388_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
389
Greg Ward478cd482003-05-08 01:58:05 +0000390def dedent(text):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000391 """Remove any common leading whitespace from every line in `text`.
Greg Ward478cd482003-05-08 01:58:05 +0000392
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000393 This can be used to make triple-quoted strings line up with the left
394 edge of the display, while still presenting them in the source code
395 in indented form.
Greg Ward478cd482003-05-08 01:58:05 +0000396
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000397 Note that tabs and spaces are both treated as whitespace, but they
398 are not equal: the lines " hello" and "\thello" are
399 considered to have no common leading whitespace. (This behaviour is
400 new in Python 2.5; older versions of this module incorrectly
401 expanded tabs before searching for common leading whitespace.)
Greg Ward478cd482003-05-08 01:58:05 +0000402 """
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000403 # Look for the longest leading string of spaces and tabs common to
404 # all lines.
Greg Ward478cd482003-05-08 01:58:05 +0000405 margin = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000406 text = _whitespace_only_re.sub('', text)
407 indents = _leading_whitespace_re.findall(text)
408 for indent in indents:
Greg Ward478cd482003-05-08 01:58:05 +0000409 if margin is None:
410 margin = indent
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000411
412 # Current line more deeply indented than previous winner:
413 # no change (previous winner is still on top).
414 elif indent.startswith(margin):
415 pass
416
417 # Current line consistent with and no deeper than previous winner:
418 # it's the new winner.
419 elif margin.startswith(indent):
420 margin = indent
421
422 # Current line and previous winner have no common whitespace:
423 # there is no margin.
Greg Ward478cd482003-05-08 01:58:05 +0000424 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000425 margin = ""
426 break
Greg Ward478cd482003-05-08 01:58:05 +0000427
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000428 # sanity check (testing/debugging only)
429 if 0 and margin:
430 for line in text.split("\n"):
431 assert not line or line.startswith(margin), \
432 "line = %r, margin = %r" % (line, margin)
Greg Ward478cd482003-05-08 01:58:05 +0000433
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000434 if margin:
435 text = re.sub(r'(?m)^' + margin, '', text)
436 return text
437
Nick Coghlan4fae8cd2012-06-11 23:07:51 +1000438
439def indent(text, prefix, predicate=None):
440 """Adds 'prefix' to the beginning of selected lines in 'text'.
441
442 If 'predicate' is provided, 'prefix' will only be added to the lines
443 where 'predicate(line)' is True. If 'predicate' is not provided,
444 it will default to adding 'prefix' to all non-empty lines that do not
445 consist solely of whitespace characters.
446 """
447 if predicate is None:
448 def predicate(line):
449 return line.strip()
450
451 def prefixed_lines():
452 for line in text.splitlines(True):
453 yield (prefix + line if predicate(line) else line)
454 return ''.join(prefixed_lines())
455
456
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000457if __name__ == "__main__":
458 #print dedent("\tfoo\n\tbar")
459 #print dedent(" \thello there\n \t how are you?")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000460 print(dedent("Hello there.\n This is indented."))