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 | |
Nick Coghlan | 4fae8cd | 2012-06-11 23:07:51 +1000 | [diff] [blame] | 10 | __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent'] |
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. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 65 | """ |
| 66 | |
Greg Ward | 2e74541 | 2002-12-09 16:23:08 +0000 | [diff] [blame] | 67 | unicode_whitespace_trans = {} |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 68 | uspace = ord(' ') |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 69 | for x in _whitespace: |
| 70 | unicode_whitespace_trans[ord(x)] = uspace |
Greg Ward | 2e74541 | 2002-12-09 16:23:08 +0000 | [diff] [blame] | 71 | |
Tim Peters | c411dba | 2002-07-16 21:35:23 +0000 | [diff] [blame] | 72 | # This funky little regex is just the trick for splitting |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 73 | # text up into word-wrappable chunks. E.g. |
| 74 | # "Hello there -- you goof-ball, use the -b option!" |
| 75 | # splits into |
| 76 | # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! |
| 77 | # (after stripping out empty strings). |
Greg Ward | 4040794 | 2005-03-05 02:53:17 +0000 | [diff] [blame] | 78 | wordsep_re = re.compile( |
| 79 | r'(\s+|' # any whitespace |
Antoine Pitrou | 7c59bc6 | 2008-12-13 23:20:54 +0000 | [diff] [blame] | 80 | r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words |
Greg Ward | 4040794 | 2005-03-05 02:53:17 +0000 | [diff] [blame] | 81 | r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 82 | |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 83 | # This less funky little regex just split on recognized spaces. E.g. |
| 84 | # "Hello there -- you goof-ball, use the -b option!" |
| 85 | # splits into |
| 86 | # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ |
| 87 | wordsep_simple_re = re.compile(r'(\s+)') |
| 88 | |
| 89 | # XXX this is not locale- or charset-aware -- string.lowercase |
| 90 | # is US-ASCII only (and therefore English-only) |
Guido van Rossum | 9264ecd | 2007-08-11 16:40:13 +0000 | [diff] [blame] | 91 | sentence_end_re = re.compile(r'[a-z]' # lowercase letter |
Greg Ward | 9b4864e | 2002-06-07 22:04:15 +0000 | [diff] [blame] | 92 | r'[\.\!\?]' # sentence-ending punct. |
| 93 | r'[\"\']?' # optional end-of-quote |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 94 | r'\Z') # end of chunk |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 95 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 96 | |
Greg Ward | f0ba764 | 2004-05-13 01:53:10 +0000 | [diff] [blame] | 97 | def __init__(self, |
| 98 | width=70, |
| 99 | initial_indent="", |
| 100 | subsequent_indent="", |
| 101 | expand_tabs=True, |
| 102 | replace_whitespace=True, |
| 103 | fix_sentence_endings=False, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 104 | break_long_words=True, |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 105 | drop_whitespace=True, |
Hynek Schlawack | d527259 | 2012-05-19 13:33:11 +0200 | [diff] [blame] | 106 | break_on_hyphens=True, |
| 107 | tabsize=8): |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 108 | self.width = width |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 109 | self.initial_indent = initial_indent |
| 110 | self.subsequent_indent = subsequent_indent |
Greg Ward | 47df99d | 2002-06-09 00:22:07 +0000 | [diff] [blame] | 111 | self.expand_tabs = expand_tabs |
| 112 | self.replace_whitespace = replace_whitespace |
| 113 | self.fix_sentence_endings = fix_sentence_endings |
| 114 | self.break_long_words = break_long_words |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 115 | self.drop_whitespace = drop_whitespace |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 116 | self.break_on_hyphens = break_on_hyphens |
Hynek Schlawack | d527259 | 2012-05-19 13:33:11 +0200 | [diff] [blame] | 117 | self.tabsize = tabsize |
Tim Peters | c411dba | 2002-07-16 21:35:23 +0000 | [diff] [blame] | 118 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 119 | |
| 120 | # -- Private methods ----------------------------------------------- |
| 121 | # (possibly useful for subclasses to override) |
| 122 | |
Greg Ward | cb320eb | 2002-06-07 22:32:15 +0000 | [diff] [blame] | 123 | def _munge_whitespace(self, text): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 124 | """_munge_whitespace(text : string) -> string |
| 125 | |
| 126 | Munge whitespace in text: expand tabs and convert all other |
| 127 | whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" |
| 128 | becomes " foo bar baz". |
| 129 | """ |
| 130 | if self.expand_tabs: |
Hynek Schlawack | d527259 | 2012-05-19 13:33:11 +0200 | [diff] [blame] | 131 | text = text.expandtabs(self.tabsize) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 132 | if self.replace_whitespace: |
Georg Brandl | 7f13e6b | 2007-08-31 10:37:15 +0000 | [diff] [blame] | 133 | text = text.translate(self.unicode_whitespace_trans) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 134 | return text |
| 135 | |
| 136 | |
Greg Ward | cb320eb | 2002-06-07 22:32:15 +0000 | [diff] [blame] | 137 | def _split(self, text): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 138 | """_split(text : string) -> [string] |
| 139 | |
| 140 | Split the text to wrap into indivisible chunks. Chunks are |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 141 | not quite the same as words; see _wrap_chunks() for full |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 142 | details. As an example, the text |
| 143 | Look, goof-ball -- use the -b option! |
| 144 | breaks into the following chunks: |
| 145 | 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', |
| 146 | 'use', ' ', 'the', ' ', '-b', ' ', 'option!' |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 147 | if break_on_hyphens is True, or in: |
| 148 | 'Look,', ' ', 'goof-ball', ' ', '--', ' ', |
| 149 | 'use', ' ', 'the', ' ', '-b', ' ', option!' |
| 150 | otherwise. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 151 | """ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 152 | if self.break_on_hyphens is True: |
| 153 | chunks = self.wordsep_re.split(text) |
| 154 | else: |
| 155 | chunks = self.wordsep_simple_re.split(text) |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 156 | chunks = [c for c in chunks if c] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 157 | return chunks |
| 158 | |
Greg Ward | cb320eb | 2002-06-07 22:32:15 +0000 | [diff] [blame] | 159 | def _fix_sentence_endings(self, chunks): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 160 | """_fix_sentence_endings(chunks : [string]) |
| 161 | |
| 162 | Correct for sentence endings buried in 'chunks'. Eg. when the |
| 163 | original text contains "... foo.\nBar ...", munge_whitespace() |
| 164 | and split() will convert that to [..., "foo.", " ", "Bar", ...] |
| 165 | which has one too few spaces; this method simply changes the one |
| 166 | space to two. |
| 167 | """ |
| 168 | i = 0 |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 169 | patsearch = self.sentence_end_re.search |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 170 | while i < len(chunks)-1: |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 171 | if chunks[i+1] == " " and patsearch(chunks[i]): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 172 | chunks[i+1] = " " |
| 173 | i += 2 |
| 174 | else: |
| 175 | i += 1 |
| 176 | |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 177 | def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 178 | """_handle_long_word(chunks : [string], |
| 179 | cur_line : [string], |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 180 | cur_len : int, width : int) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 181 | |
| 182 | Handle a chunk of text (most likely a word, not whitespace) that |
| 183 | is too long to fit in any line. |
| 184 | """ |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 185 | # Figure out when indent is larger than the specified width, and make |
| 186 | # sure at least one character is stripped off on every pass |
| 187 | if width < 1: |
| 188 | space_left = 1 |
| 189 | else: |
| 190 | space_left = width - cur_len |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 191 | |
| 192 | # If we're allowed to break long words, then do so: put as much |
| 193 | # of the next chunk onto the current line as will fit. |
| 194 | if self.break_long_words: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 195 | cur_line.append(reversed_chunks[-1][:space_left]) |
| 196 | reversed_chunks[-1] = reversed_chunks[-1][space_left:] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 197 | |
| 198 | # Otherwise, we have to preserve the long word intact. Only add |
| 199 | # it to the current line if there's nothing already there -- |
| 200 | # that minimizes how much we violate the width constraint. |
| 201 | elif not cur_line: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 202 | cur_line.append(reversed_chunks.pop()) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 203 | |
| 204 | # If we're not allowed to break long words, and there's already |
| 205 | # text on the current line, do nothing. Next time through the |
| 206 | # main loop of _wrap_chunks(), we'll wind up here again, but |
| 207 | # cur_len will be zero, so the next line will be entirely |
| 208 | # devoted to the long word that we can't handle right now. |
| 209 | |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 210 | def _wrap_chunks(self, chunks): |
| 211 | """_wrap_chunks(chunks : [string]) -> [string] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 212 | |
| 213 | 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] | 214 | length 'self.width' or less. (If 'break_long_words' is false, |
| 215 | some lines may be longer than this.) Chunks correspond roughly |
| 216 | to words and the whitespace between them: each chunk is |
| 217 | indivisible (modulo 'break_long_words'), but a line break can |
| 218 | come between any two chunks. Chunks should not have internal |
| 219 | whitespace; ie. a chunk is either all whitespace or a "word". |
| 220 | Whitespace chunks will be removed from the beginning and end of |
| 221 | lines, but apart from that whitespace is preserved. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 222 | """ |
| 223 | lines = [] |
Greg Ward | 21820cd | 2003-05-07 00:55:35 +0000 | [diff] [blame] | 224 | if self.width <= 0: |
| 225 | raise ValueError("invalid width %r (must be > 0)" % self.width) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 226 | |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 227 | # Arrange in reverse order so items can be efficiently popped |
| 228 | # from a stack of chucks. |
| 229 | chunks.reverse() |
| 230 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 231 | while chunks: |
| 232 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 233 | # Start the list of chunks that will make up the current line. |
| 234 | # cur_len is just the length of all the chunks in cur_line. |
| 235 | cur_line = [] |
| 236 | cur_len = 0 |
| 237 | |
| 238 | # Figure out which static string will prefix this line. |
| 239 | if lines: |
| 240 | indent = self.subsequent_indent |
| 241 | else: |
| 242 | indent = self.initial_indent |
| 243 | |
| 244 | # Maximum width for this line. |
| 245 | width = self.width - len(indent) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 246 | |
Greg Ward | ab73d46 | 2002-12-09 16:26:05 +0000 | [diff] [blame] | 247 | # First chunk on line is whitespace -- drop it, unless this |
| 248 | # 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] | 249 | if self.drop_whitespace and chunks[-1].strip() == '' and lines: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 250 | del chunks[-1] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 251 | |
| 252 | while chunks: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 253 | l = len(chunks[-1]) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 254 | |
| 255 | # Can at least squeeze this chunk onto the current line. |
| 256 | if cur_len + l <= width: |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 257 | cur_line.append(chunks.pop()) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 258 | cur_len += l |
| 259 | |
| 260 | # Nope, this line is full. |
| 261 | else: |
| 262 | break |
| 263 | |
| 264 | # 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] | 265 | # fit on *any* line (not just this one). |
Raymond Hettinger | 8bfa893 | 2005-07-15 06:53:35 +0000 | [diff] [blame] | 266 | if chunks and len(chunks[-1]) > width: |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 267 | self._handle_long_word(chunks, cur_line, cur_len, width) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 268 | |
| 269 | # 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] | 270 | if self.drop_whitespace and cur_line and cur_line[-1].strip() == '': |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 271 | del cur_line[-1] |
| 272 | |
| 273 | # Convert current line back to a string and store it in list |
| 274 | # of all lines (return value). |
| 275 | if cur_line: |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 276 | lines.append(indent + ''.join(cur_line)) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 277 | |
| 278 | return lines |
| 279 | |
| 280 | |
| 281 | # -- Public interface ---------------------------------------------- |
| 282 | |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 283 | def wrap(self, text): |
| 284 | """wrap(text : string) -> [string] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 285 | |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 286 | Reformat the single paragraph in 'text' so it fits in lines of |
| 287 | no more than 'self.width' columns, and return a list of wrapped |
| 288 | lines. Tabs in 'text' are expanded with string.expandtabs(), |
| 289 | and all other whitespace characters (including newline) are |
| 290 | converted to space. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 291 | """ |
| 292 | text = self._munge_whitespace(text) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 293 | chunks = self._split(text) |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 294 | if self.fix_sentence_endings: |
| 295 | self._fix_sentence_endings(chunks) |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 296 | return self._wrap_chunks(chunks) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 297 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 298 | def fill(self, text): |
| 299 | """fill(text : string) -> string |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 300 | |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 301 | Reformat the single paragraph in 'text' to fit in lines of no |
| 302 | more than 'self.width' columns, and return a new string |
| 303 | containing the entire wrapped paragraph. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 304 | """ |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 305 | return "\n".join(self.wrap(text)) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 306 | |
| 307 | |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 308 | # -- Convenience interface --------------------------------------------- |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 309 | |
Greg Ward | cf02ac6 | 2002-06-10 20:36:07 +0000 | [diff] [blame] | 310 | def wrap(text, width=70, **kwargs): |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 311 | """Wrap a single paragraph of text, returning a list of wrapped lines. |
| 312 | |
| 313 | Reformat the single paragraph in 'text' so it fits in lines of no |
| 314 | more than 'width' columns, and return a list of wrapped lines. By |
| 315 | default, tabs in 'text' are expanded with string.expandtabs(), and |
| 316 | all other whitespace characters (including newline) are converted to |
| 317 | space. See TextWrapper class for available keyword args to customize |
| 318 | wrapping behaviour. |
| 319 | """ |
Greg Ward | cf02ac6 | 2002-06-10 20:36:07 +0000 | [diff] [blame] | 320 | w = TextWrapper(width=width, **kwargs) |
| 321 | return w.wrap(text) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 322 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 323 | def fill(text, width=70, **kwargs): |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 324 | """Fill a single paragraph of text, returning a new string. |
| 325 | |
| 326 | Reformat the single paragraph in 'text' to fit in lines of no more |
| 327 | than 'width' columns, and return a new string containing the entire |
| 328 | wrapped paragraph. As with wrap(), tabs are expanded and other |
| 329 | whitespace characters converted to space. See TextWrapper class for |
| 330 | available keyword args to customize wrapping behaviour. |
| 331 | """ |
Greg Ward | cf02ac6 | 2002-06-10 20:36:07 +0000 | [diff] [blame] | 332 | w = TextWrapper(width=width, **kwargs) |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 333 | return w.fill(text) |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 334 | |
| 335 | |
| 336 | # -- Loosely related functionality ------------------------------------- |
| 337 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 338 | _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE) |
| 339 | _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) |
| 340 | |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 341 | def dedent(text): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 342 | """Remove any common leading whitespace from every line in `text`. |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 343 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 344 | This can be used to make triple-quoted strings line up with the left |
| 345 | edge of the display, while still presenting them in the source code |
| 346 | in indented form. |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 347 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 348 | Note that tabs and spaces are both treated as whitespace, but they |
| 349 | are not equal: the lines " hello" and "\thello" are |
| 350 | considered to have no common leading whitespace. (This behaviour is |
| 351 | new in Python 2.5; older versions of this module incorrectly |
| 352 | expanded tabs before searching for common leading whitespace.) |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 353 | """ |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 354 | # Look for the longest leading string of spaces and tabs common to |
| 355 | # all lines. |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 356 | margin = None |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 357 | text = _whitespace_only_re.sub('', text) |
| 358 | indents = _leading_whitespace_re.findall(text) |
| 359 | for indent in indents: |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 360 | if margin is None: |
| 361 | margin = indent |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 362 | |
| 363 | # Current line more deeply indented than previous winner: |
| 364 | # no change (previous winner is still on top). |
| 365 | elif indent.startswith(margin): |
| 366 | pass |
| 367 | |
| 368 | # Current line consistent with and no deeper than previous winner: |
| 369 | # it's the new winner. |
| 370 | elif margin.startswith(indent): |
| 371 | margin = indent |
| 372 | |
| 373 | # Current line and previous winner have no common whitespace: |
| 374 | # there is no margin. |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 375 | else: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 376 | margin = "" |
| 377 | break |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 378 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 379 | # sanity check (testing/debugging only) |
| 380 | if 0 and margin: |
| 381 | for line in text.split("\n"): |
| 382 | assert not line or line.startswith(margin), \ |
| 383 | "line = %r, margin = %r" % (line, margin) |
Greg Ward | 478cd48 | 2003-05-08 01:58:05 +0000 | [diff] [blame] | 384 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 385 | if margin: |
| 386 | text = re.sub(r'(?m)^' + margin, '', text) |
| 387 | return text |
| 388 | |
Nick Coghlan | 4fae8cd | 2012-06-11 23:07:51 +1000 | [diff] [blame] | 389 | |
| 390 | def indent(text, prefix, predicate=None): |
| 391 | """Adds 'prefix' to the beginning of selected lines in 'text'. |
| 392 | |
| 393 | If 'predicate' is provided, 'prefix' will only be added to the lines |
| 394 | where 'predicate(line)' is True. If 'predicate' is not provided, |
| 395 | it will default to adding 'prefix' to all non-empty lines that do not |
| 396 | consist solely of whitespace characters. |
| 397 | """ |
| 398 | if predicate is None: |
| 399 | def predicate(line): |
| 400 | return line.strip() |
| 401 | |
| 402 | def prefixed_lines(): |
| 403 | for line in text.splitlines(True): |
| 404 | yield (prefix + line if predicate(line) else line) |
| 405 | return ''.join(prefixed_lines()) |
| 406 | |
| 407 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 408 | if __name__ == "__main__": |
| 409 | #print dedent("\tfoo\n\tbar") |
| 410 | #print dedent(" \thello there\n \t how are you?") |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 411 | print(dedent("Hello there.\n This is indented.")) |