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