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 | 698d9f0 | 2002-06-07 22:40:23 +0000 | [diff] [blame] | 4 | # Copyright (C) 2001 Gregory P. Ward. |
| 5 | # Copyright (C) 2002 Python Software Foundation. |
| 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 | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 12 | class TextWrapper: |
| 13 | """ |
| 14 | Object for wrapping/filling text. The public interface consists of |
| 15 | the wrap() and fill() methods; the other methods are just there for |
| 16 | subclasses to override in order to tweak the default behaviour. |
| 17 | If you want to completely replace the main wrapping algorithm, |
| 18 | you'll probably have to override _wrap_chunks(). |
| 19 | |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 20 | Several instance attributes control various aspects of wrapping: |
| 21 | width (default: 70) |
| 22 | the maximum width of wrapped lines (unless break_long_words |
| 23 | is false) |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 24 | initial_indent (default: "") |
| 25 | string that will be prepended to the first line of wrapped |
| 26 | output. Counts towards the line's width. |
| 27 | subsequent_indent (default: "") |
| 28 | string that will be prepended to all lines save the first |
| 29 | of wrapped output; also counts towards each line's width. |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 30 | expand_tabs (default: true) |
| 31 | Expand tabs in input text to spaces before further processing. |
| 32 | Each tab will become 1 .. 8 spaces, depending on its position in |
| 33 | its line. If false, each tab is treated as a single character. |
| 34 | replace_whitespace (default: true) |
| 35 | Replace all whitespace characters in the input text by spaces |
| 36 | after tab expansion. Note that if expand_tabs is false and |
| 37 | replace_whitespace is true, every tab will be converted to a |
| 38 | single space! |
| 39 | fix_sentence_endings (default: false) |
| 40 | Ensure that sentence-ending punctuation is always followed |
| 41 | by two spaces. Off by default becaus the algorithm is |
| 42 | (unavoidably) imperfect. |
| 43 | break_long_words (default: true) |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 44 | Break words longer than 'width'. If false, those words will not |
| 45 | be broken, and some lines might be longer than 'width'. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 46 | """ |
| 47 | |
| 48 | whitespace_trans = string.maketrans(string.whitespace, |
| 49 | ' ' * len(string.whitespace)) |
| 50 | |
Tim Peters | c411dba | 2002-07-16 21:35:23 +0000 | [diff] [blame] | 51 | # This funky little regex is just the trick for splitting |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 52 | # text up into word-wrappable chunks. E.g. |
| 53 | # "Hello there -- you goof-ball, use the -b option!" |
| 54 | # splits into |
| 55 | # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! |
| 56 | # (after stripping out empty strings). |
| 57 | wordsep_re = re.compile(r'(\s+|' # any whitespace |
Greg Ward | cce4d67 | 2002-08-22 21:04:21 +0000 | [diff] [blame] | 58 | r'-*\w{2,}-(?=\w{2,})|' # hyphenated words |
Greg Ward | e3bd104 | 2002-08-22 21:28:00 +0000 | [diff] [blame] | 59 | r'(?<=\S)-{2,}(?=\S))') # em-dash |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 60 | |
Greg Ward | 9b4864e | 2002-06-07 22:04:15 +0000 | [diff] [blame] | 61 | # XXX will there be a locale-or-charset-aware version of |
| 62 | # string.lowercase in 2.3? |
| 63 | sentence_end_re = re.compile(r'[%s]' # lowercase letter |
| 64 | r'[\.\!\?]' # sentence-ending punct. |
| 65 | r'[\"\']?' # optional end-of-quote |
| 66 | % string.lowercase) |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 67 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 68 | |
Greg Ward | 47df99d | 2002-06-09 00:22:07 +0000 | [diff] [blame] | 69 | def __init__ (self, |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 70 | width=70, |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 71 | initial_indent="", |
| 72 | subsequent_indent="", |
Greg Ward | 47df99d | 2002-06-09 00:22:07 +0000 | [diff] [blame] | 73 | expand_tabs=True, |
| 74 | replace_whitespace=True, |
| 75 | fix_sentence_endings=False, |
| 76 | break_long_words=True): |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 77 | self.width = width |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 78 | self.initial_indent = initial_indent |
| 79 | self.subsequent_indent = subsequent_indent |
Greg Ward | 47df99d | 2002-06-09 00:22:07 +0000 | [diff] [blame] | 80 | self.expand_tabs = expand_tabs |
| 81 | self.replace_whitespace = replace_whitespace |
| 82 | self.fix_sentence_endings = fix_sentence_endings |
| 83 | self.break_long_words = break_long_words |
Tim Peters | c411dba | 2002-07-16 21:35:23 +0000 | [diff] [blame] | 84 | |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 85 | |
| 86 | # -- Private methods ----------------------------------------------- |
| 87 | # (possibly useful for subclasses to override) |
| 88 | |
Greg Ward | cb320eb | 2002-06-07 22:32:15 +0000 | [diff] [blame] | 89 | def _munge_whitespace(self, text): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 90 | """_munge_whitespace(text : string) -> string |
| 91 | |
| 92 | Munge whitespace in text: expand tabs and convert all other |
| 93 | whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" |
| 94 | becomes " foo bar baz". |
| 95 | """ |
| 96 | if self.expand_tabs: |
| 97 | text = text.expandtabs() |
| 98 | if self.replace_whitespace: |
| 99 | text = text.translate(self.whitespace_trans) |
| 100 | return text |
| 101 | |
| 102 | |
Greg Ward | cb320eb | 2002-06-07 22:32:15 +0000 | [diff] [blame] | 103 | def _split(self, text): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 104 | """_split(text : string) -> [string] |
| 105 | |
| 106 | Split the text to wrap into indivisible chunks. Chunks are |
| 107 | not quite the same as words; see wrap_chunks() for full |
| 108 | details. As an example, the text |
| 109 | Look, goof-ball -- use the -b option! |
| 110 | breaks into the following chunks: |
| 111 | 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', |
| 112 | 'use', ' ', 'the', ' ', '-b', ' ', 'option!' |
| 113 | """ |
| 114 | chunks = self.wordsep_re.split(text) |
| 115 | chunks = filter(None, chunks) |
| 116 | return chunks |
| 117 | |
Greg Ward | cb320eb | 2002-06-07 22:32:15 +0000 | [diff] [blame] | 118 | def _fix_sentence_endings(self, chunks): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 119 | """_fix_sentence_endings(chunks : [string]) |
| 120 | |
| 121 | Correct for sentence endings buried in 'chunks'. Eg. when the |
| 122 | original text contains "... foo.\nBar ...", munge_whitespace() |
| 123 | and split() will convert that to [..., "foo.", " ", "Bar", ...] |
| 124 | which has one too few spaces; this method simply changes the one |
| 125 | space to two. |
| 126 | """ |
| 127 | i = 0 |
Greg Ward | 9b4864e | 2002-06-07 22:04:15 +0000 | [diff] [blame] | 128 | pat = self.sentence_end_re |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 129 | while i < len(chunks)-1: |
Greg Ward | 9b4864e | 2002-06-07 22:04:15 +0000 | [diff] [blame] | 130 | if chunks[i+1] == " " and pat.search(chunks[i]): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 131 | chunks[i+1] = " " |
| 132 | i += 2 |
| 133 | else: |
| 134 | i += 1 |
| 135 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 136 | def _handle_long_word(self, chunks, cur_line, cur_len, width): |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 137 | """_handle_long_word(chunks : [string], |
| 138 | cur_line : [string], |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 139 | cur_len : int, width : int) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 140 | |
| 141 | Handle a chunk of text (most likely a word, not whitespace) that |
| 142 | is too long to fit in any line. |
| 143 | """ |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 144 | space_left = width - cur_len |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 145 | |
| 146 | # If we're allowed to break long words, then do so: put as much |
| 147 | # of the next chunk onto the current line as will fit. |
| 148 | if self.break_long_words: |
| 149 | cur_line.append(chunks[0][0:space_left]) |
| 150 | chunks[0] = chunks[0][space_left:] |
| 151 | |
| 152 | # Otherwise, we have to preserve the long word intact. Only add |
| 153 | # it to the current line if there's nothing already there -- |
| 154 | # that minimizes how much we violate the width constraint. |
| 155 | elif not cur_line: |
| 156 | cur_line.append(chunks.pop(0)) |
| 157 | |
| 158 | # If we're not allowed to break long words, and there's already |
| 159 | # text on the current line, do nothing. Next time through the |
| 160 | # main loop of _wrap_chunks(), we'll wind up here again, but |
| 161 | # cur_len will be zero, so the next line will be entirely |
| 162 | # devoted to the long word that we can't handle right now. |
| 163 | |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 164 | def _wrap_chunks(self, chunks): |
| 165 | """_wrap_chunks(chunks : [string]) -> [string] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 166 | |
| 167 | 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] | 168 | length 'self.width' or less. (If 'break_long_words' is false, |
| 169 | some lines may be longer than this.) Chunks correspond roughly |
| 170 | to words and the whitespace between them: each chunk is |
| 171 | indivisible (modulo 'break_long_words'), but a line break can |
| 172 | come between any two chunks. Chunks should not have internal |
| 173 | whitespace; ie. a chunk is either all whitespace or a "word". |
| 174 | Whitespace chunks will be removed from the beginning and end of |
| 175 | lines, but apart from that whitespace is preserved. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 176 | """ |
| 177 | lines = [] |
| 178 | |
| 179 | while chunks: |
| 180 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 181 | # Start the list of chunks that will make up the current line. |
| 182 | # cur_len is just the length of all the chunks in cur_line. |
| 183 | cur_line = [] |
| 184 | cur_len = 0 |
| 185 | |
| 186 | # Figure out which static string will prefix this line. |
| 187 | if lines: |
| 188 | indent = self.subsequent_indent |
| 189 | else: |
| 190 | indent = self.initial_indent |
| 191 | |
| 192 | # Maximum width for this line. |
| 193 | width = self.width - len(indent) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 194 | |
| 195 | # First chunk on line is whitespace -- drop it. |
| 196 | if chunks[0].strip() == '': |
| 197 | del chunks[0] |
| 198 | |
| 199 | while chunks: |
| 200 | l = len(chunks[0]) |
| 201 | |
| 202 | # Can at least squeeze this chunk onto the current line. |
| 203 | if cur_len + l <= width: |
| 204 | cur_line.append(chunks.pop(0)) |
| 205 | cur_len += l |
| 206 | |
| 207 | # Nope, this line is full. |
| 208 | else: |
| 209 | break |
| 210 | |
| 211 | # 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] | 212 | # fit on *any* line (not just this one). |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 213 | if chunks and len(chunks[0]) > width: |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 214 | self._handle_long_word(chunks, cur_line, cur_len, width) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 215 | |
| 216 | # If the last chunk on this line is all whitespace, drop it. |
| 217 | if cur_line and cur_line[-1].strip() == '': |
| 218 | del cur_line[-1] |
| 219 | |
| 220 | # Convert current line back to a string and store it in list |
| 221 | # of all lines (return value). |
| 222 | if cur_line: |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 223 | lines.append(indent + ''.join(cur_line)) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 224 | |
| 225 | return lines |
| 226 | |
| 227 | |
| 228 | # -- Public interface ---------------------------------------------- |
| 229 | |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 230 | def wrap(self, text): |
| 231 | """wrap(text : string) -> [string] |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 232 | |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 233 | Reformat the single paragraph in 'text' so it fits in lines of |
| 234 | no more than 'self.width' columns, and return a list of wrapped |
| 235 | lines. Tabs in 'text' are expanded with string.expandtabs(), |
| 236 | and all other whitespace characters (including newline) are |
| 237 | converted to space. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 238 | """ |
| 239 | text = self._munge_whitespace(text) |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 240 | if len(text) <= self.width: |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 241 | return [text] |
| 242 | chunks = self._split(text) |
Greg Ward | 62e4f3b | 2002-06-07 21:56:16 +0000 | [diff] [blame] | 243 | if self.fix_sentence_endings: |
| 244 | self._fix_sentence_endings(chunks) |
Greg Ward | d34c959 | 2002-06-10 20:26:02 +0000 | [diff] [blame] | 245 | return self._wrap_chunks(chunks) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 246 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 247 | def fill(self, text): |
| 248 | """fill(text : string) -> string |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 249 | |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 250 | Reformat the single paragraph in 'text' to fit in lines of no |
| 251 | more than 'self.width' columns, and return a new string |
| 252 | containing the entire wrapped paragraph. |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 253 | """ |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 254 | return "\n".join(self.wrap(text)) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 255 | |
| 256 | |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 257 | # -- Convenience interface --------------------------------------------- |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 258 | |
Greg Ward | cf02ac6 | 2002-06-10 20:36:07 +0000 | [diff] [blame] | 259 | def wrap(text, width=70, **kwargs): |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 260 | """Wrap a single paragraph of text, returning a list of wrapped lines. |
| 261 | |
| 262 | Reformat the single paragraph in 'text' so it fits in lines of no |
| 263 | more than 'width' columns, and return a list of wrapped lines. By |
| 264 | default, tabs in 'text' are expanded with string.expandtabs(), and |
| 265 | all other whitespace characters (including newline) are converted to |
| 266 | space. See TextWrapper class for available keyword args to customize |
| 267 | wrapping behaviour. |
| 268 | """ |
Greg Ward | cf02ac6 | 2002-06-10 20:36:07 +0000 | [diff] [blame] | 269 | w = TextWrapper(width=width, **kwargs) |
| 270 | return w.wrap(text) |
Greg Ward | 0093582 | 2002-06-07 21:43:37 +0000 | [diff] [blame] | 271 | |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 272 | def fill(text, width=70, **kwargs): |
Greg Ward | e807e57 | 2002-07-04 14:51:49 +0000 | [diff] [blame] | 273 | """Fill a single paragraph of text, returning a new string. |
| 274 | |
| 275 | Reformat the single paragraph in 'text' to fit in lines of no more |
| 276 | than 'width' columns, and return a new string containing the entire |
| 277 | wrapped paragraph. As with wrap(), tabs are expanded and other |
| 278 | whitespace characters converted to space. See TextWrapper class for |
| 279 | available keyword args to customize wrapping behaviour. |
| 280 | """ |
Greg Ward | cf02ac6 | 2002-06-10 20:36:07 +0000 | [diff] [blame] | 281 | w = TextWrapper(width=width, **kwargs) |
Greg Ward | 62080be | 2002-06-10 21:37:12 +0000 | [diff] [blame] | 282 | return w.fill(text) |