Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 1 | """Text wrapping and filling. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 2 | """ |
| 3 | |
Greg Ward | 78cc051 | 2002-10-13 19:23:18 +0000 | [diff] [blame] | 4 | # Copyright (C) 1999-2001 Gregory P. Ward. |
Greg Ward | 523008c | 2003-06-15 15:37:18 +0000 | [diff] [blame] | 5 | # Copyright (C) 2002, 2003 Python Software Foundation. |
Greg Ward | 698d9f0 | 2002-06-07 22:40:23 +0000 | [diff] [blame] | 6 | # Written by Greg Ward <gward@python.net> |
| 7 | |
Benjamin Peterson | 274271d | 2011-06-28 10:25:04 -0500 | [diff] [blame] | 8 | import re |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 9 | |
Serhiy Storchaka | 3e4b528 | 2013-10-16 13:07:53 +0300 | [diff] [blame] | 10 | __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten'] |
Greg Ward | 4c6c9c4 | 2003-02-03 14:46:57 +0000 | [diff] [blame] | 11 | |
Greg Ward | afd44de | 2002-12-12 17:24:35 +0000 | [diff] [blame] | 12 | # 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 Ward | 4c6c9c4 | 2003-02-03 14:46:57 +0000 | [diff] [blame] | 20 | _whitespace = '\t\n\x0b\x0c\r ' |
Greg Ward | afd44de | 2002-12-12 17:24:35 +0000 | [diff] [blame] | 21 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 22 | class TextWrapper: |
| 23 | """ |
| 24 | Object for wrapping/filling text. The public interface consists of |
| 25 | the wrap() and fill() methods; the other methods are just there for |
| 26 | subclasses to override in order to tweak the default behaviour. |
| 27 | If you want to completely replace the main wrapping algorithm, |
| 28 | you'll probably have to override _wrap_chunks(). |
| 29 | |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 30 | Several instance attributes control various aspects of wrapping: |
| 31 | width (default: 70) |
| 32 | the maximum width of wrapped lines (unless break_long_words |
| 33 | is false) |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 34 | initial_indent (default: "") |
| 35 | string that will be prepended to the first line of wrapped |
| 36 | output. Counts towards the line's width. |
| 37 | subsequent_indent (default: "") |
| 38 | string that will be prepended to all lines save the first |
| 39 | of wrapped output; also counts towards each line's width. |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 40 | expand_tabs (default: true) |
| 41 | Expand tabs in input text to spaces before further processing. |
Hynek Schlawack | d527259 | 2012-05-19 13:33:11 +0200 | [diff] [blame] | 42 | Each tab will become 0 .. 'tabsize' spaces, depending on its position |
| 43 | in its line. If false, each tab is treated as a single character. |
| 44 | tabsize (default: 8) |
| 45 | Expand tabs in input text to 0 .. 'tabsize' spaces, unless |
| 46 | 'expand_tabs' is false. |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 47 | replace_whitespace (default: true) |
| 48 | Replace all whitespace characters in the input text by spaces |
| 49 | after tab expansion. Note that if expand_tabs is false and |
| 50 | replace_whitespace is true, every tab will be converted to a |
| 51 | single space! |
| 52 | fix_sentence_endings (default: false) |
| 53 | Ensure that sentence-ending punctuation is always followed |
Andrew M. Kuchling | a2ecabe | 2003-02-14 01:14:15 +0000 | [diff] [blame] | 54 | by two spaces. Off by default because the algorithm is |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 55 | (unavoidably) imperfect. |
| 56 | break_long_words (default: true) |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 57 | Break words longer than 'width'. If false, those words will not |
| 58 | be broken, and some lines might be longer than 'width'. |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 59 | break_on_hyphens (default: true) |
| 60 | Allow breaking hyphenated words. If true, wrapping will occur |
| 61 | preferably on whitespaces and right after hyphens part of |
| 62 | compound words. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 63 | drop_whitespace (default: true) |
| 64 | Drop leading and trailing whitespace from lines. |
Serhiy Storchaka | acc9f3f | 2013-10-15 21:22:54 +0300 | [diff] [blame] | 65 | max_lines (default: None) |
| 66 | Truncate wrapped lines. |
| 67 | placeholder (default: ' [...]') |
| 68 | Append to the last line of truncated text. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 69 | """ |
| 70 | |
Greg Ward | 2e74541 | 2002-12-09 16:23:08 +0000 | [diff] [blame] | 71 | unicode_whitespace_trans = {} |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 72 | uspace = ord(' ') |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 73 | for x in _whitespace: |
| 74 | unicode_whitespace_trans[ord(x)] = uspace |
Greg Ward | 2e74541 | 2002-12-09 16:23:08 +0000 | [diff] [blame] | 75 | |
Tim Peters | c411dba | 2002-07-16 21:35:23 +0000 | [diff] [blame] | 76 | # This funky little regex is just the trick for splitting |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 77 | # text up into word-wrappable chunks. E.g. |
| 78 | # "Hello there -- you goof-ball, use the -b option!" |
| 79 | # splits into |
| 80 | # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! |
| 81 | # (after stripping out empty strings). |
Serhiy Storchaka | 72bd327 | 2015-03-24 18:32:27 +0200 | [diff] [blame] | 82 | word_punct = r'[\w!"\'&.,?]' |
| 83 | letter = r'[^\d\W]' |
| 84 | wordsep_re = re.compile(r''' |
| 85 | ( # any whitespace |
| 86 | \s+ |
| 87 | | # em-dash between words |
| 88 | (?<=%(wp)s) -{2,} (?=\w) |
| 89 | | # word, possibly hyphenated |
| 90 | \S+? (?: |
| 91 | # hyphenated word |
| 92 | -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-)) |
| 93 | (?= %(lt)s -? %(lt)s) |
| 94 | | # end of word |
| 95 | (?=\s|\Z) |
| 96 | | # em-dash |
| 97 | (?<=%(wp)s) (?=-{2,}\w) |
| 98 | ) |
| 99 | )''' % {'wp': word_punct, 'lt': letter}, re.VERBOSE) |
| 100 | del word_punct, letter |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 101 | |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 102 | # This less funky little regex just split on recognized spaces. E.g. |
| 103 | # "Hello there -- you goof-ball, use the -b option!" |
| 104 | # splits into |
| 105 | # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ |
| 106 | wordsep_simple_re = re.compile(r'(\s+)') |
| 107 | |
| 108 | # XXX this is not locale- or charset-aware -- string.lowercase |
| 109 | # is US-ASCII only (and therefore English-only) |
Guido van Rossum | 9264ecd | 2007-08-11 16:40:13 +0000 | [diff] [blame] | 110 | sentence_end_re = re.compile(r'[a-z]' # lowercase letter |
Greg Ward | 9b4864e | 2002-06-07 22:04:15 +0000 | [diff] [blame] | 111 | r'[\.\!\?]' # sentence-ending punct. |
| 112 | r'[\"\']?' # optional end-of-quote |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 113 | r'\Z') # end of chunk |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 114 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 115 | |
Greg Ward | f0ba764 | 2004-05-13 01:53:10 +0000 | [diff] [blame] | 116 | def __init__(self, |
| 117 | width=70, |
| 118 | initial_indent="", |
| 119 | subsequent_indent="", |
| 120 | expand_tabs=True, |
| 121 | replace_whitespace=True, |
| 122 | fix_sentence_endings=False, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 123 | break_long_words=True, |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 124 | drop_whitespace=True, |
Hynek Schlawack | d527259 | 2012-05-19 13:33:11 +0200 | [diff] [blame] | 125 | break_on_hyphens=True, |
Serhiy Storchaka | acc9f3f | 2013-10-15 21:22:54 +0300 | [diff] [blame] | 126 | tabsize=8, |
| 127 | *, |
| 128 | max_lines=None, |
| 129 | placeholder=' [...]'): |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 130 | self.width = width |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 131 | self.initial_indent = initial_indent |
| 132 | self.subsequent_indent = subsequent_indent |
Greg Ward | 47df99d | 2002-06-09 00:22:07 +0000 | [diff] [blame] | 133 | self.expand_tabs = expand_tabs |
| 134 | self.replace_whitespace = replace_whitespace |
| 135 | self.fix_sentence_endings = fix_sentence_endings |
| 136 | self.break_long_words = break_long_words |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 137 | self.drop_whitespace = drop_whitespace |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 138 | self.break_on_hyphens = break_on_hyphens |
Hynek Schlawack | d527259 | 2012-05-19 13:33:11 +0200 | [diff] [blame] | 139 | self.tabsize = tabsize |
Serhiy Storchaka | acc9f3f | 2013-10-15 21:22:54 +0300 | [diff] [blame] | 140 | self.max_lines = max_lines |
| 141 | self.placeholder = placeholder |
Tim Peters | c411dba | 2002-07-16 21:35:23 +0000 | [diff] [blame] | 142 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 143 | |
| 144 | # -- Private methods ----------------------------------------------- |
| 145 | # (possibly useful for subclasses to override) |
| 146 | |
Greg Ward | cb320eb | 2002-06-07 22:32:15 +0000 | [diff] [blame] | 147 | def _munge_whitespace(self, text): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 148 | """_munge_whitespace(text : string) -> string |
| 149 | |
| 150 | Munge whitespace in text: expand tabs and convert all other |
Serhiy Storchaka | 9f8a891 | 2015-04-03 18:12:41 +0300 | [diff] [blame] | 151 | whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz" |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 152 | becomes " foo bar baz". |
| 153 | """ |
| 154 | if self.expand_tabs: |
Hynek Schlawack | d527259 | 2012-05-19 13:33:11 +0200 | [diff] [blame] | 155 | text = text.expandtabs(self.tabsize) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 156 | if self.replace_whitespace: |
Georg Brandl | 7f13e6b | 2007-08-31 10:37:15 +0000 | [diff] [blame] | 157 | text = text.translate(self.unicode_whitespace_trans) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 158 | return text |
| 159 | |
| 160 | |
Greg Ward | cb320eb | 2002-06-07 22:32:15 +0000 | [diff] [blame] | 161 | def _split(self, text): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 162 | """_split(text : string) -> [string] |
| 163 | |
| 164 | Split the text to wrap into indivisible chunks. Chunks are |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 165 | not quite the same as words; see _wrap_chunks() for full |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 166 | details. As an example, the text |
| 167 | Look, goof-ball -- use the -b option! |
| 168 | breaks into the following chunks: |
| 169 | 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', |
| 170 | 'use', ' ', 'the', ' ', '-b', ' ', 'option!' |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 171 | if break_on_hyphens is True, or in: |
| 172 | 'Look,', ' ', 'goof-ball', ' ', '--', ' ', |
| 173 | 'use', ' ', 'the', ' ', '-b', ' ', option!' |
| 174 | otherwise. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 175 | """ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 176 | if self.break_on_hyphens is True: |
| 177 | chunks = self.wordsep_re.split(text) |
| 178 | else: |
| 179 | chunks = self.wordsep_simple_re.split(text) |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 180 | chunks = [c for c in chunks if c] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 181 | return chunks |
| 182 | |
Greg Ward | cb320eb | 2002-06-07 22:32:15 +0000 | [diff] [blame] | 183 | def _fix_sentence_endings(self, chunks): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 184 | """_fix_sentence_endings(chunks : [string]) |
| 185 | |
| 186 | Correct for sentence endings buried in 'chunks'. Eg. when the |
Serhiy Storchaka | 9f8a891 | 2015-04-03 18:12:41 +0300 | [diff] [blame] | 187 | original text contains "... foo.\\nBar ...", munge_whitespace() |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 188 | and split() will convert that to [..., "foo.", " ", "Bar", ...] |
| 189 | which has one too few spaces; this method simply changes the one |
| 190 | space to two. |
| 191 | """ |
| 192 | i = 0 |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 193 | patsearch = self.sentence_end_re.search |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 194 | while i < len(chunks)-1: |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 195 | if chunks[i+1] == " " and patsearch(chunks[i]): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 196 | chunks[i+1] = " " |
| 197 | i += 2 |
| 198 | else: |
| 199 | i += 1 |
| 200 | |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 201 | def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 202 | """_handle_long_word(chunks : [string], |
| 203 | cur_line : [string], |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 204 | cur_len : int, width : int) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 205 | |
| 206 | Handle a chunk of text (most likely a word, not whitespace) that |
| 207 | is too long to fit in any line. |
| 208 | """ |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 209 | # Figure out when indent is larger than the specified width, and make |
| 210 | # sure at least one character is stripped off on every pass |
| 211 | if width < 1: |
| 212 | space_left = 1 |
| 213 | else: |
| 214 | space_left = width - cur_len |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 215 | |
| 216 | # If we're allowed to break long words, then do so: put as much |
| 217 | # of the next chunk onto the current line as will fit. |
| 218 | if self.break_long_words: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 219 | cur_line.append(reversed_chunks[-1][:space_left]) |
| 220 | reversed_chunks[-1] = reversed_chunks[-1][space_left:] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 221 | |
| 222 | # Otherwise, we have to preserve the long word intact. Only add |
| 223 | # it to the current line if there's nothing already there -- |
| 224 | # that minimizes how much we violate the width constraint. |
| 225 | elif not cur_line: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 226 | cur_line.append(reversed_chunks.pop()) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 227 | |
| 228 | # If we're not allowed to break long words, and there's already |
| 229 | # text on the current line, do nothing. Next time through the |
| 230 | # main loop of _wrap_chunks(), we'll wind up here again, but |
| 231 | # cur_len will be zero, so the next line will be entirely |
| 232 | # devoted to the long word that we can't handle right now. |
| 233 | |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 234 | def _wrap_chunks(self, chunks): |
| 235 | """_wrap_chunks(chunks : [string]) -> [string] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 236 | |
| 237 | Wrap a sequence of text chunks and return a list of lines of |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 238 | length 'self.width' or less. (If 'break_long_words' is false, |
| 239 | some lines may be longer than this.) Chunks correspond roughly |
| 240 | to words and the whitespace between them: each chunk is |
| 241 | indivisible (modulo 'break_long_words'), but a line break can |
| 242 | come between any two chunks. Chunks should not have internal |
| 243 | whitespace; ie. a chunk is either all whitespace or a "word". |
| 244 | Whitespace chunks will be removed from the beginning and end of |
| 245 | lines, but apart from that whitespace is preserved. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 246 | """ |
| 247 | lines = [] |
Greg Ward | 21820cd | 2003-05-07 00:55:35 +0000 | [diff] [blame] | 248 | if self.width <= 0: |
| 249 | raise ValueError("invalid width %r (must be > 0)" % self.width) |
Serhiy Storchaka | acc9f3f | 2013-10-15 21:22:54 +0300 | [diff] [blame] | 250 | if self.max_lines is not None: |
| 251 | if self.max_lines > 1: |
| 252 | indent = self.subsequent_indent |
| 253 | else: |
| 254 | indent = self.initial_indent |
| 255 | if len(indent) + len(self.placeholder.lstrip()) > self.width: |
| 256 | raise ValueError("placeholder too large for max width") |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 257 | |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 258 | # Arrange in reverse order so items can be efficiently popped |
| 259 | # from a stack of chucks. |
| 260 | chunks.reverse() |
| 261 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 262 | while chunks: |
| 263 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 264 | # Start the list of chunks that will make up the current line. |
| 265 | # cur_len is just the length of all the chunks in cur_line. |
| 266 | cur_line = [] |
| 267 | cur_len = 0 |
| 268 | |
| 269 | # Figure out which static string will prefix this line. |
| 270 | if lines: |
| 271 | indent = self.subsequent_indent |
| 272 | else: |
| 273 | indent = self.initial_indent |
| 274 | |
| 275 | # Maximum width for this line. |
| 276 | width = self.width - len(indent) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 277 | |
Greg Ward | ab73d46 | 2002-12-09 16:26:05 +0000 | [diff] [blame] | 278 | # First chunk on line is whitespace -- drop it, unless this |
| 279 | # is the very beginning of the text (ie. no lines started yet). |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 280 | if self.drop_whitespace and chunks[-1].strip() == '' and lines: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 281 | del chunks[-1] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 282 | |
| 283 | while chunks: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 284 | l = len(chunks[-1]) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 285 | |
| 286 | # Can at least squeeze this chunk onto the current line. |
| 287 | if cur_len + l <= width: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 288 | cur_line.append(chunks.pop()) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 289 | cur_len += l |
| 290 | |
| 291 | # Nope, this line is full. |
| 292 | else: |
| 293 | break |
| 294 | |
| 295 | # The current line is full, and the next chunk is too big to |
Tim Peters | c411dba | 2002-07-16 21:35:23 +0000 | [diff] [blame] | 296 | # fit on *any* line (not just this one). |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 297 | if chunks and len(chunks[-1]) > width: |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 298 | self._handle_long_word(chunks, cur_line, cur_len, width) |
Serhiy Storchaka | acc9f3f | 2013-10-15 21:22:54 +0300 | [diff] [blame] | 299 | cur_len = sum(map(len, cur_line)) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 300 | |
| 301 | # If the last chunk on this line is all whitespace, drop it. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 302 | if self.drop_whitespace and cur_line and cur_line[-1].strip() == '': |
Serhiy Storchaka | acc9f3f | 2013-10-15 21:22:54 +0300 | [diff] [blame] | 303 | cur_len -= len(cur_line[-1]) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 304 | del cur_line[-1] |
| 305 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 306 | if cur_line: |
Serhiy Storchaka | acc9f3f | 2013-10-15 21:22:54 +0300 | [diff] [blame] | 307 | if (self.max_lines is None or |
| 308 | len(lines) + 1 < self.max_lines or |
| 309 | (not chunks or |
| 310 | self.drop_whitespace and |
| 311 | len(chunks) == 1 and |
| 312 | not chunks[0].strip()) and cur_len <= width): |
| 313 | # Convert current line back to a string and store it in |
| 314 | # list of all lines (return value). |
| 315 | lines.append(indent + ''.join(cur_line)) |
| 316 | else: |
| 317 | while cur_line: |
| 318 | if (cur_line[-1].strip() and |
| 319 | cur_len + len(self.placeholder) <= width): |
| 320 | cur_line.append(self.placeholder) |
| 321 | lines.append(indent + ''.join(cur_line)) |
| 322 | break |
| 323 | cur_len -= len(cur_line[-1]) |
| 324 | del cur_line[-1] |
| 325 | else: |
| 326 | if lines: |
| 327 | prev_line = lines[-1].rstrip() |
| 328 | if (len(prev_line) + len(self.placeholder) <= |
| 329 | self.width): |
| 330 | lines[-1] = prev_line + self.placeholder |
| 331 | break |
| 332 | lines.append(indent + self.placeholder.lstrip()) |
| 333 | break |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 334 | |
| 335 | return lines |
| 336 | |
Antoine Pitrou | 389dec8 | 2013-08-12 22:39:09 +0200 | [diff] [blame] | 337 | def _split_chunks(self, text): |
| 338 | text = self._munge_whitespace(text) |
| 339 | return self._split(text) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 340 | |
| 341 | # -- Public interface ---------------------------------------------- |
| 342 | |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 343 | def wrap(self, text): |
| 344 | """wrap(text : string) -> [string] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 345 | |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 346 | Reformat the single paragraph in 'text' so it fits in lines of |
| 347 | no more than 'self.width' columns, and return a list of wrapped |
| 348 | lines. Tabs in 'text' are expanded with string.expandtabs(), |
| 349 | and all other whitespace characters (including newline) are |
| 350 | converted to space. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 351 | """ |
Antoine Pitrou | 389dec8 | 2013-08-12 22:39:09 +0200 | [diff] [blame] | 352 | chunks = self._split_chunks(text) |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 353 | if self.fix_sentence_endings: |
| 354 | self._fix_sentence_endings(chunks) |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 355 | return self._wrap_chunks(chunks) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 356 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 357 | def fill(self, text): |
| 358 | """fill(text : string) -> string |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 359 | |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 360 | Reformat the single paragraph in 'text' to fit in lines of no |
| 361 | more than 'self.width' columns, and return a new string |
| 362 | containing the entire wrapped paragraph. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 363 | """ |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 364 | return "\n".join(self.wrap(text)) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 365 | |
| 366 | |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 367 | # -- Convenience interface --------------------------------------------- |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 368 | |
Greg Ward | cf02ac6 | 2002-06-10 20:36:07 +0000 | [diff] [blame] | 369 | def wrap(text, width=70, **kwargs): |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 370 | """Wrap a single paragraph of text, returning a list of wrapped lines. |
| 371 | |
| 372 | Reformat the single paragraph in 'text' so it fits in lines of no |
| 373 | more than 'width' columns, and return a list of wrapped lines. By |
| 374 | default, tabs in 'text' are expanded with string.expandtabs(), and |
| 375 | all other whitespace characters (including newline) are converted to |
| 376 | space. See TextWrapper class for available keyword args to customize |
| 377 | wrapping behaviour. |
| 378 | """ |
Greg Ward | cf02ac6 | 2002-06-10 20:36:07 +0000 | [diff] [blame] | 379 | w = TextWrapper(width=width, **kwargs) |
| 380 | return w.wrap(text) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 381 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 382 | def fill(text, width=70, **kwargs): |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 383 | """Fill a single paragraph of text, returning a new string. |
| 384 | |
| 385 | Reformat the single paragraph in 'text' to fit in lines of no more |
| 386 | than 'width' columns, and return a new string containing the entire |
| 387 | wrapped paragraph. As with wrap(), tabs are expanded and other |
| 388 | whitespace characters converted to space. See TextWrapper class for |
| 389 | available keyword args to customize wrapping behaviour. |
| 390 | """ |
Greg Ward | cf02ac6 | 2002-06-10 20:36:07 +0000 | [diff] [blame] | 391 | w = TextWrapper(width=width, **kwargs) |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 392 | return w.fill(text) |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 393 | |
Serhiy Storchaka | acc9f3f | 2013-10-15 21:22:54 +0300 | [diff] [blame] | 394 | def shorten(text, width, **kwargs): |
Antoine Pitrou | 389dec8 | 2013-08-12 22:39:09 +0200 | [diff] [blame] | 395 | """Collapse and truncate the given text to fit in the given width. |
| 396 | |
| 397 | The text first has its whitespace collapsed. If it then fits in |
| 398 | the *width*, it is returned as is. Otherwise, as many words |
| 399 | as possible are joined and then the placeholder is appended:: |
| 400 | |
| 401 | >>> textwrap.shorten("Hello world!", width=12) |
| 402 | 'Hello world!' |
| 403 | >>> textwrap.shorten("Hello world!", width=11) |
Antoine Pitrou | c593056 | 2013-08-16 22:31:12 +0200 | [diff] [blame] | 404 | 'Hello [...]' |
Antoine Pitrou | 389dec8 | 2013-08-12 22:39:09 +0200 | [diff] [blame] | 405 | """ |
Serhiy Storchaka | acc9f3f | 2013-10-15 21:22:54 +0300 | [diff] [blame] | 406 | w = TextWrapper(width=width, max_lines=1, **kwargs) |
| 407 | return w.fill(' '.join(text.strip().split())) |
Antoine Pitrou | 389dec8 | 2013-08-12 22:39:09 +0200 | [diff] [blame] | 408 | |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 409 | |
| 410 | # -- Loosely related functionality ------------------------------------- |
| 411 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 412 | _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE) |
| 413 | _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) |
| 414 | |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 415 | def dedent(text): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 416 | """Remove any common leading whitespace from every line in `text`. |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 417 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 418 | This can be used to make triple-quoted strings line up with the left |
| 419 | edge of the display, while still presenting them in the source code |
| 420 | in indented form. |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 421 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 422 | Note that tabs and spaces are both treated as whitespace, but they |
Serhiy Storchaka | 9f8a891 | 2015-04-03 18:12:41 +0300 | [diff] [blame] | 423 | are not equal: the lines " hello" and "\\thello" are |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 424 | considered to have no common leading whitespace. (This behaviour is |
| 425 | new in Python 2.5; older versions of this module incorrectly |
| 426 | expanded tabs before searching for common leading whitespace.) |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 427 | """ |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 428 | # Look for the longest leading string of spaces and tabs common to |
| 429 | # all lines. |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 430 | margin = None |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 431 | text = _whitespace_only_re.sub('', text) |
| 432 | indents = _leading_whitespace_re.findall(text) |
| 433 | for indent in indents: |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 434 | if margin is None: |
| 435 | margin = indent |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 436 | |
| 437 | # Current line more deeply indented than previous winner: |
| 438 | # no change (previous winner is still on top). |
| 439 | elif indent.startswith(margin): |
| 440 | pass |
| 441 | |
| 442 | # Current line consistent with and no deeper than previous winner: |
| 443 | # it's the new winner. |
| 444 | elif margin.startswith(indent): |
| 445 | margin = indent |
| 446 | |
| 447 | # Current line and previous winner have no common whitespace: |
| 448 | # there is no margin. |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 449 | else: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 450 | margin = "" |
| 451 | break |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 452 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 453 | # sanity check (testing/debugging only) |
| 454 | if 0 and margin: |
| 455 | for line in text.split("\n"): |
| 456 | assert not line or line.startswith(margin), \ |
| 457 | "line = %r, margin = %r" % (line, margin) |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 458 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 459 | if margin: |
| 460 | text = re.sub(r'(?m)^' + margin, '', text) |
| 461 | return text |
| 462 | |
Nick Coghlan | 4fae8cd | 2012-06-11 23:07:51 +1000 | [diff] [blame] | 463 | |
| 464 | def indent(text, prefix, predicate=None): |
| 465 | """Adds 'prefix' to the beginning of selected lines in 'text'. |
| 466 | |
| 467 | If 'predicate' is provided, 'prefix' will only be added to the lines |
| 468 | where 'predicate(line)' is True. If 'predicate' is not provided, |
| 469 | it will default to adding 'prefix' to all non-empty lines that do not |
| 470 | consist solely of whitespace characters. |
| 471 | """ |
| 472 | if predicate is None: |
| 473 | def predicate(line): |
| 474 | return line.strip() |
| 475 | |
| 476 | def prefixed_lines(): |
| 477 | for line in text.splitlines(True): |
| 478 | yield (prefix + line if predicate(line) else line) |
| 479 | return ''.join(prefixed_lines()) |
| 480 | |
| 481 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 482 | if __name__ == "__main__": |
| 483 | #print dedent("\tfoo\n\tbar") |
| 484 | #print dedent(" \thello there\n \t how are you?") |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 485 | print(dedent("Hello there.\n This is indented.")) |