gh-134158: Fix PyREPL coloring of double braces in f/t-strings (gh-134159)

Co-authored-by: Loïc Simon <loic.simon@napta.io>
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
This commit is contained in:
Loïc Simon 2025-05-19 16:12:23 +02:00 committed by GitHub
parent b22460c44d
commit 71ea6a6798
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 39 additions and 1 deletions

View file

@ -41,9 +41,15 @@ class Span(NamedTuple):
@classmethod
def from_token(cls, token: TI, line_len: list[int]) -> Self:
end_offset = -1
if (token.type in {T.FSTRING_MIDDLE, T.TSTRING_MIDDLE}
and token.string.endswith(("{", "}"))):
# gh-134158: a visible trailing brace comes from a double brace in input
end_offset += 1
return cls(
line_len[token.start[0] - 1] + token.start[1],
line_len[token.end[0] - 1] + token.end[1] - 1,
line_len[token.end[0] - 1] + token.end[1] + end_offset,
)

View file

@ -517,6 +517,37 @@ class TestReaderInColor(ScreenEqualMixin, TestCase):
self.assert_screen_equal(reader, code, clean=True)
self.assert_screen_equal(reader, expected)
def test_syntax_highlighting_literal_brace_in_fstring_or_tstring(self):
code = dedent(
"""\
f"{{"
f"}}"
f"a{{b"
f"a}}b"
f"a{{b}}c"
t"a{{b}}c"
f"{{{0}}}"
f"{ {0} }"
"""
)
expected = dedent(
"""\
{s}f"{z}{s}<<{z}{s}"{z}
{s}f"{z}{s}>>{z}{s}"{z}
{s}f"{z}{s}a<<{z}{s}b{z}{s}"{z}
{s}f"{z}{s}a>>{z}{s}b{z}{s}"{z}
{s}f"{z}{s}a<<{z}{s}b>>{z}{s}c{z}{s}"{z}
{s}t"{z}{s}a<<{z}{s}b>>{z}{s}c{z}{s}"{z}
{s}f"{z}{s}<<{z}{o}<{z}{n}0{z}{o}>{z}{s}>>{z}{s}"{z}
{s}f"{z}{o}<{z} {o}<{z}{n}0{z}{o}>{z} {o}>{z}{s}"{z}
"""
).format(**colors).replace("<", "{").replace(">", "}")
events = code_to_events(code)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, code, clean=True)
self.maxDiff=None
self.assert_screen_equal(reader, expected)
def test_control_characters(self):
code = 'flag = "🏳️‍🌈"'
events = code_to_events(code)

View file

@ -0,0 +1 @@
Fix coloring of double braces in f-strings and t-strings in the :term:`REPL`.