@@ -188,18 +188,34 @@ def rich_text_to_string(text: Text) -> str:
188
188
def string_to_rich_text (text : str ) -> Text :
189
189
r"""Create a Text object from a string which can contain ANSI escape codes.
190
190
191
- This function is a workaround for a bug where rich.Text.from_ansi() incorrectly
192
- removes a trailing newline. The official fix is pending .
191
+ This wraps rich.Text.from_ansi() to handle an issue where it removes the
192
+ trailing line break from a string (e.g. "Hello\n" becomes "Hello") .
193
193
194
- See: https://github.com/Textualize/rich/pull/3793
194
+ There is currently a pull request to fix this.
195
+ https://github.com/Textualize/rich/pull/3793
195
196
196
197
:param text: a string to convert to a Text object.
197
- :return: the string converted to a Text object
198
+ :return: the converted string
198
199
"""
199
200
result = Text .from_ansi (text )
200
201
201
- # Handle case where Text.from_ansi() removed the trailing newline.
202
- if text .endswith ("\n " ):
202
+ # If 'text' ends with a line break character, restore the missing newline to 'result'.
203
+ # Note: '\r\n' is handled since its last character is '\n'.
204
+ # Source: https://docs.python.org/3/library/stdtypes.html#str.splitlines
205
+ line_break_chars = {
206
+ "\n " , # Line Feed
207
+ "\r " , # Carriage Return
208
+ "\v " , # Vertical Tab
209
+ "\f " , # Form Feed
210
+ "\x1c " , # File Separator
211
+ "\x1d " , # Group Separator
212
+ "\x1e " , # Record Separator
213
+ "\x85 " , # Next Line (NEL)
214
+ "\u2028 " , # Line Separator
215
+ "\u2029 " , # Paragraph Separator
216
+ }
217
+ if text and text [- 1 ] in line_break_chars :
218
+ # We use "\n" because Text.from_ansi() converts all line breaks chars into newlines.
203
219
result .append ("\n " )
204
220
205
221
return result
0 commit comments