Write 'text' word-wrapped at self.width characters.
(self, text: str, indent: int = 0)
| 168 | return dollar_count |
| 169 | |
| 170 | def _line(self, text: str, indent: int = 0) -> None: |
| 171 | """Write 'text' word-wrapped at self.width characters.""" |
| 172 | leading_space = " " * indent |
| 173 | while len(leading_space) + len(text) > self.width: |
| 174 | # The text is too wide; wrap if possible. |
| 175 | |
| 176 | # Find the rightmost space that would obey our width constraint and |
| 177 | # that's not an escaped space. |
| 178 | available_space = self.width - len(leading_space) - len(" $") |
| 179 | space = available_space |
| 180 | while True: |
| 181 | space = text.rfind(" ", 0, space) |
| 182 | if space < 0 or self._count_dollars_before_index(text, space) % 2 == 0: |
| 183 | break |
| 184 | |
| 185 | if space < 0: |
| 186 | # No such space; just use the first unescaped space we can find. |
| 187 | space = available_space - 1 |
| 188 | while True: |
| 189 | space = text.find(" ", space + 1) |
| 190 | if ( |
| 191 | space < 0 |
| 192 | or self._count_dollars_before_index(text, space) % 2 == 0 |
| 193 | ): |
| 194 | break |
| 195 | if space < 0: |
| 196 | # Give up on breaking. |
| 197 | break |
| 198 | |
| 199 | self.output.write(leading_space + text[0:space] + " $\n") |
| 200 | text = text[space + 1 :] |
| 201 | |
| 202 | # Subsequent lines are continuations, so indent them. |
| 203 | leading_space = " " * (indent + 2) |
| 204 | |
| 205 | self.output.write(leading_space + text + "\n") |
| 206 | |
| 207 | def close(self) -> None: |
| 208 | self.output.close() |