Skip to content

Commit ea752be

Browse files
committed
Simplied string_to_rich_text().
1 parent c8a8935 commit ea752be

File tree

1 file changed

+6
-24
lines changed

1 file changed

+6
-24
lines changed

cmd2/rich_utils.py

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -188,36 +188,18 @@ def rich_text_to_string(text: Text) -> str:
188188
def 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 wraps rich.Text.from_ansi() to handle a discarded newline issue.
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.
192193
193-
Text.from_ansi() currently removes the ending line break from string.
194-
e.g. "Hello\n" becomes "Hello"
195-
196-
There is currently a pull request to fix this.
197-
https://github.com/Textualize/rich/pull/3793
194+
See: https://github.com/Textualize/rich/pull/3793
198195
199196
:param text: a string to convert to a Text object.
200-
:return: the converted string
197+
:return: the string converted to a Text object
201198
"""
202199
result = Text.from_ansi(text)
203200

204-
# If 'text' ends with a line break character, restore the missing newline to 'result'.
205-
# Note: '\r\n' is handled as its last character is '\n'.
206-
# Source: https://docs.python.org/3/library/stdtypes.html#str.splitlines
207-
line_break_chars = {
208-
"\n", # Line Feed
209-
"\r", # Carriage Return
210-
"\v", # Vertical Tab
211-
"\f", # Form Feed
212-
"\x1c", # File Separator
213-
"\x1d", # Group Separator
214-
"\x1e", # Record Separator
215-
"\x85", # Next Line (NEL)
216-
"\u2028", # Line Separator
217-
"\u2029", # Paragraph Separator
218-
}
219-
if text and text[-1] in line_break_chars:
220-
# We use "\n" because Text.from_ansi() converts all line breaks chars into newlines.
201+
# Handle case where Text.from_ansi() removed the trailing newline.
202+
if text.endswith("\n"):
221203
result.append("\n")
222204

223205
return result

0 commit comments

Comments
 (0)