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