Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/prompt_toolkit/formatted_text/ansi.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,16 @@ def ansi_escape(text: object) -> str:
"""
Replace characters with a special meaning.
"""
return str(text).replace("\x1b", "?").replace("\b", "?")
# Besides ESC, the parser also treats \x9b as the start of a control
# sequence, and everything between \001 and \002 as raw output.
return (
str(text)
.replace("\x1b", "?")
.replace("\x9b", "?")
.replace("\x01", "?")
.replace("\x02", "?")
.replace("\b", "?")
)


class ANSIFormatter(Formatter):
Expand Down
1 change: 1 addition & 0 deletions src/prompt_toolkit/formatted_text/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ def html_escape(text: object) -> str:
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace('"', "&quot;")
.replace("'", "&#x27;")
)


Expand Down
27 changes: 27 additions & 0 deletions tests/test_formatted_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,26 @@ def test_ansi_interpolation():
("ansigreen bg:ansimagenta", "2"),
]

# 8-bit CSI (\x9b) and the \001..\002 raw escape markers can't be
# injected through interpolated values either.
value = ANSI("{}").format("\x9b31mhi")
assert to_formatted_text(value) == [
("", "?"),
("", "3"),
("", "1"),
("", "m"),
("", "h"),
("", "i"),
]

value = ANSI("%s") % "\x01x\x02y"
assert to_formatted_text(value) == [
("", "?"),
("", "x"),
("", "?"),
("", "y"),
]


def test_interpolation():
value = Template(" {} ").format(HTML("<b>hello</b>"))
Expand Down Expand Up @@ -251,6 +271,13 @@ def test_html_interpolation():
value = HTML("<b>{:02d}</b><u>{:.3f}</u>").format(3, 3.14159)
assert to_formatted_text(value) == [("class:b", "03"), ("class:u", "3.142")]

# Quotes inside attribute values.
value = HTML("<style fg='{}'>x</style>").format("a'bg='b")
assert to_formatted_text(value) == [("fg:a'bg='b", "x")]

value = HTML('<style fg="%s">x</style>') % 'a"bg="b'
assert to_formatted_text(value) == [('fg:a"bg="b', "x")]


def test_merge_formatted_text():
html1 = HTML("<u>hello</u>")
Expand Down