Skip to content

Commit dda9990

Browse files
committed
Added unit tests.
1 parent f78fa19 commit dda9990

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

cmd2/rich_utils.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,19 @@
3030
from .styles import DEFAULT_CMD2_STYLES
3131

3232
# A compiled regular expression to detect ANSI escape sequences.
33-
# The `[a-zA-Z]` at the end of the regex allows it to match all types of
34-
# escape sequences, including those for styling, cursor movement, etc.
35-
_ANSI_ESCAPE_SEQUENCE_RE = re.compile(r"\x1b\[[0-9;?]*[a-zA-Z]")
33+
_ANSI_ESCAPE_SEQUENCE_RE = re.compile(
34+
r"""
35+
\x1b # Match the Escape character (ESC)
36+
(?: # Start of non-capturing group for the different sequence types
37+
\[[0-9;?]*[a-zA-Z] # Match a CSI sequence (e.g., \x1b[31m)
38+
| # OR
39+
\].*?(?:\x07|\x1b\x5c) # Match an OSC sequence (e.g., \x1b]2;Hello\x07)
40+
| # OR
41+
\x37|\x38 # Match DEC cursor save/restore sequences
42+
) # End of non-capturing group
43+
""",
44+
re.VERBOSE,
45+
)
3646

3747

3848
class AllowStyle(Enum):

tests/test_rich_utils.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,23 @@ def test_set_theme() -> None:
139139

140140
assert ru.APP_THEME.styles[rich_style_key] != orig_rich_style
141141
assert ru.APP_THEME.styles[rich_style_key] == theme[rich_style_key]
142+
143+
144+
def test_ansi_escape_sequence_re() -> None:
145+
import cmd2.terminal_utils as tu
146+
147+
# Test a CSI sequence
148+
cursor_contol = tu.Cursor.UP(1)
149+
assert ru._ANSI_ESCAPE_SEQUENCE_RE.search(cursor_contol)
150+
151+
# Test an OSC sequence
152+
set_title = tu.set_title_str("Hello")
153+
assert ru._ANSI_ESCAPE_SEQUENCE_RE.search(set_title)
154+
155+
# Test DEC cursor save
156+
cursor_save = "\x1b\x37"
157+
assert ru._ANSI_ESCAPE_SEQUENCE_RE.search(cursor_save)
158+
159+
# Test DEC cursor restore
160+
cursor_restore = "\x1b\x38"
161+
assert ru._ANSI_ESCAPE_SEQUENCE_RE.search(cursor_restore)

0 commit comments

Comments
 (0)