@@ -188,18 +188,34 @@ def rich_text_to_string(text: Text) -> str:
188188def string_to_rich_text (text : str ) -> Text :
189189 r"""Create a Text object from a string which can contain ANSI escape codes.
190190
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") .
193193
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
195196
196197 :param text: a string to convert to a Text object.
197- :return: the string converted to a Text object
198+ :return: the converted string
198199 """
199200 result = Text .from_ansi (text )
200201
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.
203219 result .append ("\n " )
204220
205221 return result
0 commit comments