diff --git a/Lib/_pyrepl/utils.py b/Lib/_pyrepl/utils.py index 180e111873dbb3..12199dc12935ae 100644 --- a/Lib/_pyrepl/utils.py +++ b/Lib/_pyrepl/utils.py @@ -110,13 +110,21 @@ def str_width(c: str) -> int: def wlen(s: str) -> int: - if len(s) == 1 and s != "\x1a": + if len(s) == 1 and s not in ("\b", "\x1a"): return str_width(s) - length = sum(str_width(i) for i in s) - # remove lengths of any escape sequences - sequence = ANSI_ESCAPE_SEQUENCE.findall(s) - ctrl_z_cnt = s.count("\x1a") - return length - sum(len(i) for i in sequence) + ctrl_z_cnt + length = 0 + # Strip ANSI escapes first + plain = ANSI_ESCAPE_SEQUENCE.sub("", s) + for c in plain: + if c == "\b": + # Backspace decreases cursor position, and cannot move before column 0. + length = max(length - 1, 0) + elif c == "\x1a": + # Control-Z is treated as width 2 to account for the fact that it will be rendered as ^Z + length += 2 + else: + length += str_width(c) + return length def unbracket(s: str, including_content: bool = False) -> str: diff --git a/Lib/test/test_pyrepl/test_reader.py b/Lib/test/test_pyrepl/test_reader.py index fd9900d9a32b3d..92da03833e0d0b 100644 --- a/Lib/test/test_pyrepl/test_reader.py +++ b/Lib/test/test_pyrepl/test_reader.py @@ -385,6 +385,12 @@ def test_prompt_length(self): self.assertEqual(prompt, "\033[0;32m樂>\033[0m> ") self.assertEqual(l, 5) + # Handles backspace in prompt + ps1 = "Question? _\b" + prompt, l = Reader.process_prompt(ps1) + self.assertEqual(prompt, ps1) + self.assertEqual(l, 10) + def test_prepare_with_zero_width_does_not_crash(self): console = prepare_console([], width=0) reader = ReadlineAlikeReader(console=console, config=ReadlineConfig()) diff --git a/Lib/test/test_pyrepl/test_utils.py b/Lib/test/test_pyrepl/test_utils.py index 5c60770c511c07..4c0cbe84d7222a 100644 --- a/Lib/test/test_pyrepl/test_utils.py +++ b/Lib/test/test_pyrepl/test_utils.py @@ -47,6 +47,13 @@ def test_wlen(self): self.assertEqual(wlen('e\N{COMBINING ACUTE ACCENT}'), 1) self.assertEqual(wlen('a\N{ZERO WIDTH JOINER}b'), 2) + # Backspace decreases cursor position, and cannot move before column 0. + self.assertEqual(wlen('\b'), 0) + self.assertEqual(wlen('Question? _\b'), 10) + self.assertEqual(wlen('ab\b'), 1) + self.assertEqual(wlen('ab\b\b'), 0) + self.assertEqual(wlen('\babc'), 3) + self.assertEqual(wlen('樂\b'), 1) def test_wlen_with_osc_sequence(self): prompt = ">>> " self.assertEqual(wlen("\x1b]633;A\x07" + prompt), len(prompt)) diff --git a/Misc/NEWS.d/next/Library/2026-05-26-23-38-25.gh-issue-150462.az-a_o.rst b/Misc/NEWS.d/next/Library/2026-05-26-23-38-25.gh-issue-150462.az-a_o.rst new file mode 100644 index 00000000000000..0c06bc0c82da40 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-05-26-23-38-25.gh-issue-150462.az-a_o.rst @@ -0,0 +1 @@ +Fixes ``input`` prompt length miscalculation when dealing with ``\b`` character that caused the cursor to be placed in an incorrect position.