diff --git a/Lib/_pyrepl/commands.py b/Lib/_pyrepl/commands.py index a3b541525aee10..46e4f02a13a04c 100644 --- a/Lib/_pyrepl/commands.py +++ b/Lib/_pyrepl/commands.py @@ -502,15 +502,19 @@ def do(self) -> None: class perform_bracketed_paste(Command): def do(self) -> None: - done = "\x1b[201~" - data = "" + done = b"\x1b[201~" + data = b"" start = time.time() while done not in data: ev = self.reader.console.getpending() - data += ev.data + data += ev.raw trace( - "bracketed pasting of {l} chars done in {s:.2f}s", + "bracketed pasting of {l} bytes done in {s:.2f}s", l=len(data), s=time.time() - start, ) - self.reader.insert(data.replace(done, "")) + pasted, _, rest = data.partition(done) + self.reader.insert(pasted.decode(self.reader.console.encoding, "replace")) + + for byte in rest: + self.reader.console.push_char(byte) diff --git a/Lib/_pyrepl/windows_console.py b/Lib/_pyrepl/windows_console.py index 466a3e62d8cb9b..907ecb44fa6b55 100644 --- a/Lib/_pyrepl/windows_console.py +++ b/Lib/_pyrepl/windows_console.py @@ -626,7 +626,8 @@ def push_char(self, char: int | bytes) -> None: """ Push a character to the console event queue. """ - raise NotImplementedError("push_char not supported on Windows") + trace("push char {char!r}", char=char) + self.event_queue.push(char) def beep(self) -> None: self.__write("\x07") @@ -670,24 +671,41 @@ def getpending(self) -> Event: e2 = self.event_queue.get() if e2: e.data += e2.data - - recs, rec_count = self._read_input_bulk(1024) - for i in range(rec_count): - rec = recs[i] - # In case of a legacy console, we do not only receive a keydown - # event, but also a keyup event - and for uppercase letters - # an additional SHIFT_PRESSED event. - if rec and rec.EventType == KEY_EVENT: - key_event = rec.Event.KeyEvent - if not key_event.bKeyDown: - continue - ch = key_event.uChar.UnicodeChar - if ch == "\x00": - # ignore SHIFT_PRESSED and special keys - continue - if ch == "\r": - ch = "\n" - e.data += ch + e.raw += e2.raw + + # _read_input_bulk() blocks until the console has input, + # so return the queued input without reading. + if e.raw: + return e + + text = "" + while True: + recs, rec_count = self._read_input_bulk(1024) + for i in range(rec_count): + rec = recs[i] + # In case of a legacy console, we do not only receive a keydown + # event, but also a keyup event - and for uppercase letters + # an additional SHIFT_PRESSED event. + if rec and rec.EventType == KEY_EVENT: + key_event = rec.Event.KeyEvent + if not key_event.bKeyDown: + continue + ch = key_event.uChar.UnicodeChar + if ch == "\x00": + # ignore SHIFT_PRESSED and special keys + continue + if ch == "\r": + ch = "\n" + text += ch + # Read again while the text ends with a high surrogate. + if not "\ud800" <= text[-1:] <= "\udbff": + break + # Each record on Windows holds a UTF-16 code unit. + # A surrogate pair must be joined before encoding, + # an unpaired half becomes U+FFFD. + text = text.encode("utf-16-le", "surrogatepass").decode("utf-16-le", "replace") + e.data += text + e.raw += text.encode(self.event_queue.encoding, "replace") return e def wait_for_event(self, timeout: float | None) -> bool: diff --git a/Lib/test/test_pyrepl/test_pyrepl.py b/Lib/test/test_pyrepl/test_pyrepl.py index c11c759f559aff..05b68ab1ea5b63 100644 --- a/Lib/test/test_pyrepl/test_pyrepl.py +++ b/Lib/test/test_pyrepl/test_pyrepl.py @@ -2288,6 +2288,20 @@ def test_python_basic_repl(self): self.assertNotIn("Exception", output) self.assertNotIn("Traceback", output) + def test_bracketed_paste_newline_after_end_marker(self): + # A newline arriving in the same read as the closing marker must + # execute the pasted block instead of being inserted as text. + # See gh-156186. + env = os.environ.copy() + commands = ("\x1b[200~x = 1\nprint(f'^{x=}')\n\x1b[201~" + "\n" + "exit()\n") + output, exit_code = self.run_repl(commands, env=env, skip=True) + self.assertEqual(exit_code, 0) + self.assertIn("^x=1", output) + self.assertNotIn("Exception", output) + self.assertNotIn("Traceback", output) + @force_not_colorized def test_no_pyrepl_source_in_exc(self): # Avoid using _pyrepl/__main__.py in traceback reports diff --git a/Lib/test/test_pyrepl/test_windows_console.py b/Lib/test/test_pyrepl/test_windows_console.py index 784b33d9247c11..194a4406d0f2a6 100644 --- a/Lib/test/test_pyrepl/test_windows_console.py +++ b/Lib/test/test_pyrepl/test_windows_console.py @@ -436,6 +436,17 @@ def get_event(self, input_records, **kwargs) -> Console: event = self.console.get_event(block=False) return event + def get_pending(self, *reads) -> Event: + self.console = WindowsConsole(encoding='utf-8') + recs = [] + for read in reads: + rec = (len(read) * wc.INPUT_RECORD)(*read) + recs.append((rec, len(rec))) + self.mock = MagicMock(side_effect=recs) + self.console._read_input_bulk = self.mock + event = self.console.getpending() + return event + def get_input_record(self, unicode_char, vcode=0, control=0): return wc.INPUT_RECORD( wc.KEY_EVENT, @@ -648,6 +659,69 @@ def test_wait_not_empty(self): self.assertTrue(console.wait(0.0)) self.assertEqual(console.wait_for_event.call_count, 0) + def test_getpending_raw(self): + ir_list = [ + self.get_input_record("a"), + self.get_input_record("\ud83d"), + self.get_input_record("\ude00"), + self.get_input_record("\r") + ] + event = self.get_pending(ir_list) + self.assertEqual(event.data, "a😀\n") + self.assertEqual(event.raw, b"a\xf0\x9f\x98\x80\n") + + def test_getpending_split_surrogate_pair(self): + ir_list_one = [ + self.get_input_record("a"), + self.get_input_record("\ud83d"), + ] + ir_list_two = [ + self.get_input_record("\ude00"), + self.get_input_record("\r") + ] + event = self.get_pending(ir_list_one, ir_list_two) + self.assertEqual(event.data, "a😀\n") + self.assertEqual(event.raw, b"a\xf0\x9f\x98\x80\n") + self.assertEqual(self.mock.call_count, 2) + + def test_push_char(self): + self.console = WindowsConsole(encoding='utf-8') + self.console.push_char(ord("\n")) + event = self.console.get_event(block=False) + self.assertEqual(event.data, "\n") + + def test_bracketed_paste_two_pastes_in_one_read(self): + # Two complete pastes arrive in a single console read. The second + # one is already queued, so it must be submitted without another + # read, which would block on a real console. + # See gh-156186. + + self.console = WindowsConsole(encoding='utf-8') + self.console._WindowsConsole__vt_support = True + self.console._WindowsConsole__original_input_mode = 0 + self.console.wait = MagicMock(return_value=True) + self.console._hide_cursor = MagicMock() + self.console._show_cursor = MagicMock() + self.console.out = MagicMock() + self.console.getheightwidth = MagicMock(return_value=(25, 80)) + + # start marker + start_marker_records = [self.get_input_record(x) for x in "\x1b[200~"] + + # body 1, end marker \x1b[201~, \r, start marker \x1b[200~, body 2, end marker, \r + bulk_records = [self.get_input_record(x) for x in "a\x1b[201~\r\x1b[200~b\x1b[201~\r"] + bulk_array = (len(bulk_records) * wc.INPUT_RECORD)(*bulk_records) + bulk_reads = [(bulk_array, len(bulk_array))] + + self.console._read_input = MagicMock(side_effect=start_marker_records) + self.console._read_input_bulk = MagicMock(side_effect=bulk_reads) + + reader = default_prepare_reader(self.console, paste_mode=False) + with patch.object(wc._winapi, "SetConsoleMode"): + self.assertEqual(reader.readline(), "a") + self.assertEqual(reader.readline(), "b") + self.assertEqual(self.console._read_input_bulk.call_count, 1) + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Library/2026-09-10-09-43-11.gh-issue-156186.yeOh4o.rst b/Misc/NEWS.d/next/Library/2026-09-10-09-43-11.gh-issue-156186.yeOh4o.rst new file mode 100644 index 00000000000000..3df5568b444ee0 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-09-10-09-43-11.gh-issue-156186.yeOh4o.rst @@ -0,0 +1,2 @@ +Fix PyREPL so that a newline sent right after a pasted block runs the block, +instead of being added to the pasted text.