Skip to content
Open
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
5 changes: 5 additions & 0 deletions Lib/_pyrepl/base_eventqueue.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,13 @@
from .console import Event
from .trace import trace

PASTE_KEYCODES = {
b'\033[200~': 'bracketed paste',
}

class BaseEventQueue:
def __init__(self, encoding: str, keymap_dict: dict[bytes, str]) -> None:
keymap_dict.update(PASTE_KEYCODES)
self.compiled_keymap = keymap.compile_keymap(keymap_dict)
self.keymap = self.compiled_keymap
trace("keymap {k!r}", k=self.keymap)
Expand Down
39 changes: 27 additions & 12 deletions Lib/_pyrepl/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

# types
lazy from .historical_reader import HistoricalReader
lazy from .reader import Reader


class Command:
Expand Down Expand Up @@ -500,17 +501,31 @@ def do(self) -> None:
self.reader.invalidate_prompt()


def read_bracketed_paste(reader: Reader) -> str:
"""Read a bracketed paste from the console and return its contents.

Input that arrives after the closing marker in the same read (for
example the Enter key) is pushed back into the console's input queue so
that it is processed as normal input instead of becoming part of the
pasted text.
"""
done = "\x1b[201~"
data = ""
start = time.time()
while done not in data:
ev = reader.console.getpending()
data += ev.data
trace(
"bracketed pasting of {l} chars done in {s:.2f}s",
l=len(data),
s=time.time() - start,
)
paste, _, trailing = data.partition(done)
if trailing:
reader.console.pushback(trailing)
return paste


class perform_bracketed_paste(Command):
def do(self) -> None:
done = "\x1b[201~"
data = ""
start = time.time()
while done not in data:
ev = self.reader.console.getpending()
data += ev.data
trace(
"bracketed pasting of {l} chars done in {s:.2f}s",
l=len(data),
s=time.time() - start,
)
self.reader.insert(data.replace(done, ""))
self.reader.insert(read_bracketed_paste(self.reader))
6 changes: 6 additions & 0 deletions Lib/_pyrepl/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ def push_char(self, char: int | bytes) -> None:
"""
...

@abstractmethod
def pushback(self, data: str) -> None:
"""Push characters back into the input queue so they are processed
as normal input."""
...

@abstractmethod
def beep(self) -> None: ...

Expand Down
12 changes: 12 additions & 0 deletions Lib/_pyrepl/historical_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
(r"\C-c", "isearch-cancel"),
(r"\C-g", "isearch-cancel"),
(r"\<backspace>", "isearch-backspace"),
(r"\<bracketed paste>", "isearch-bracketed-paste"),
]
)

Expand Down Expand Up @@ -207,6 +208,16 @@ def do(self) -> None:
r.invalidate_prompt()


class isearch_bracketed_paste(commands.Command):
Comment thread
tanloong marked this conversation as resolved.
Resolved
def do(self) -> None:
r = self.reader
b = r.buffer
r.isearch_term += commands.read_bracketed_paste(r)
r.invalidate_prompt()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be r.invalidate_prompt(). dirty is not used here, so the prompt can keep showing the previous search term.

@tanloong tanloong Jul 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

r.dirty is not read anywhere in _pyrepl, so this is a no-op and the search prompt won't refresh after the paste. We probably want r.invalidate_prompt() here, like isearch_add_character does.

if "".join(b[r.pos:r.pos+len(r.isearch_term)]) != r.isearch_term:
r.isearch_next()


@dataclass
class HistoricalReader(Reader):
"""Adds history support (with incremental history searching) to the
Expand Down Expand Up @@ -241,6 +252,7 @@ def __post_init__(self) -> None:
isearch_backspace,
isearch_forwards,
isearch_backwards,
isearch_bracketed_paste,
operate_and_get_next,
history_search_backward,
history_search_forward,
Expand Down
1 change: 1 addition & 0 deletions Lib/_pyrepl/keymap.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"space": " ",
"tab": "\t",
"up": "up",
"bracketed paste": "bracketed paste",
}


Expand Down
2 changes: 1 addition & 1 deletion Lib/_pyrepl/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def make_default_commands() -> dict[CommandName, CommandClass]:
(r"\M-9", "digit-arg"),
(r"\M-\n", "accept"),
("\\\\", "self-insert"),
(r"\x1b[200~", "perform-bracketed-paste"),
(r"\<bracketed paste>", "perform-bracketed-paste"),
(r"\x03", "ctrl-c"),
]
+ [(c, "self-insert") for c in map(chr, range(32, 127)) if c != "\\"]
Expand Down
6 changes: 6 additions & 0 deletions Lib/_pyrepl/unix_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,12 @@ def push_char(self, char: int | bytes) -> None:
trace("push char {char!r}", char=char)
self.event_queue.push(char)

def pushback(self, data: str) -> None:
"""Push characters back into the input queue."""
for char in data:
for byte in char.encode(self.encoding, "replace"):
self.push_char(byte)

def get_event(self, block: bool = True) -> Event | None:
"""
Get an event from the console event queue.
Expand Down
5 changes: 5 additions & 0 deletions Lib/_pyrepl/windows_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,11 @@ def push_char(self, char: int | bytes) -> None:
"""
raise NotImplementedError("push_char not supported on Windows")

def pushback(self, data: str) -> None:
"""Push characters back into the input queue."""
for char in data:
self.event_queue.insert(Event("key", char))

def beep(self) -> None:
self.__write("\x07")

Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_pyrepl/support.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from code import InteractiveConsole
from collections import deque
from functools import partial
from typing import Iterable
from unittest.mock import MagicMock
Expand Down Expand Up @@ -132,8 +133,11 @@ def __init__(self, events, encoding="utf-8") -> None:
self.width = 80
self.posxy = (0, 0)
self._redraw_visual_cycle = 0
self._pushed_back: deque[Event] = deque()

def get_event(self, block: bool = True) -> Event | None:
if self._pushed_back:
return self._pushed_back.popleft()
return next(self.events)

def getpending(self) -> Event:
Expand All @@ -160,6 +164,12 @@ def set_cursor_vis(self, visible: bool) -> None:
def push_char(self, char: int | bytes) -> None:
pass

def pushback(self, data: str) -> None:
for char in data:
self._pushed_back.append(
Event("key", char, bytearray(char.encode(self.encoding, "replace")))
)

def beep(self) -> None:
pass

Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_pyrepl/test_eventqueue.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ def test_push_with_keymap_in_keymap_and_escape(self, mock_keymap):
self.assertEqual(eq.events[1].evt, "key")
self.assertEqual(eq.events[1].data, "b")

def test_push_bracketed_paste(self):
eq = self.make_eventqueue()
for byte in b"\x1b[200~":
eq.push(byte)
event = eq.get()
self.assertIsNotNone(event)
self.assertEqual(event.evt, "key")
self.assertEqual(event.data, "bracketed paste")
self.assertEqual(event.raw, b"\x1b[200~")

def test_push_special_key(self):
eq = self.make_eventqueue()
eq.keymap = {}
Expand Down
120 changes: 116 additions & 4 deletions Lib/test/test_pyrepl/test_pyrepl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2042,11 +2042,11 @@ def test_bracketed_paste(self):
)
# fmt: on

paste_start = "\x1b[200~"
paste_start = [Event(evt="key", data="bracketed paste", raw=bytearray(b"\x1b[200~"))]
paste_end = "\x1b[201~"

events = itertools.chain(
code_to_events(paste_start),
paste_start,
code_to_events(input_code),
code_to_events(paste_end),
code_to_events("\n"),
Expand All @@ -2058,11 +2058,11 @@ def test_bracketed_paste(self):
def test_bracketed_paste_single_line(self):
input_code = "oneline"

paste_start = "\x1b[200~"
paste_start = [Event(evt="key", data="bracketed paste", raw=bytearray(b"\x1b[200~"))]
paste_end = "\x1b[201~"

events = itertools.chain(
code_to_events(paste_start),
paste_start,
code_to_events(input_code),
code_to_events(paste_end),
code_to_events("\n"),
Expand All @@ -2071,6 +2071,118 @@ def test_bracketed_paste_single_line(self):
output = multiline_input(reader)
self.assertEqual(output, input_code)

def test_read_bracketed_paste_pushes_back_trailing_input(self):
# Bytes that follow the closing marker in the same read must be
# returned to the input queue rather than added to the pasted text.
from _pyrepl.commands import read_bracketed_paste

console = Mock(encoding="utf-8")
console.getpending.return_value = Event(
evt="key",
data="hello\x1b[201~\n",
raw=bytearray(b"hello\x1b[201~\n"),
)
reader = Mock(console=console)

self.assertEqual(read_bracketed_paste(reader), "hello")
console.pushback.assert_called_once_with("\n")

def test_bracketed_paste_with_trailing_input(self):
# In regular (non-isearch) mode, the Enter that follows the closing
# marker in the same read must still accept the pasted line.
paste_start = [Event(evt="key", data="bracketed paste", raw=bytearray(b"\x1b[200~"))]
events = itertools.chain(
paste_start,
[Event(evt="key", data="\n", raw=bytearray(b"\n"))],
)
reader = self.prepare_reader(events)
console = reader.console
original_getpending = console.getpending
aggregated = [
Event("key", "hello\x1b[201~\n", bytearray(b"hello\x1b[201~\n")),
]

def getpending():
if aggregated:
return aggregated.pop(0)
return original_getpending()

console.getpending = getpending

output = multiline_input(reader)
self.assertEqual(output, "hello")

def test_bracketed_paste_in_isearch_with_trailing_input(self):
# Simulate the Enter key arriving in the same read as the closing
# bracketed-paste marker. It must end the incremental search instead
# of becoming part of the search term.
paste_start = [Event(evt="key", data="bracketed paste", raw=bytearray(b"\x1b[200~"))]
events = itertools.chain(
code_to_events("print('hello')\n"),
[Event(evt="key", data="\x12", raw=bytearray(b"\x12"))],
paste_start,
[Event(evt="key", data="\n", raw=bytearray(b"\n"))],
)
reader = self.prepare_reader(events)
console = reader.console
original_getpending = console.getpending
aggregated = [
Event("key", "hello\x1b[201~\n", bytearray(b"hello\x1b[201~\n")),
]

def getpending():
if aggregated:
return aggregated.pop(0)
return original_getpending()

console.getpending = getpending

multiline_input(reader)
output = multiline_input(reader)
self.assertEqual(output, "print('hello')")

def test_bracketed_paste_in_isearch(self):
# The bracketed-paste *start* marker is translated into a synthetic
# ``bracketed paste`` event by the real event queue; the fake console
# used here does not run that translation, so we feed the
# ``bracketed paste`` event directly.
paste_start = [Event(evt="key", data="bracketed paste", raw=bytearray(b"\x1b[200~"))]
paste_end = "\x1b[201~"

events = itertools.chain(
# Add some history
code_to_events("print('hello')\n"),
# Search for 'hello'
[
Event(evt="key", data="\x12", raw=bytearray(b"\x12")),
],
paste_start,
code_to_events("hello"),
code_to_events(paste_end),
[
Event(evt="key", data="\n", raw=bytearray(b"\n")),
Event(evt="key", data="\n", raw=bytearray(b"\n")),
],
[
Event(evt="key", data="\x12", raw=bytearray(b"\x12")),
],
# Search for 'world', which should not be found
paste_start,
code_to_events("world"),
code_to_events(paste_end),
[
Event(evt="key", data="\n", raw=bytearray(b"\n")),
Event(evt="key", data="\n", raw=bytearray(b"\n")),
],
)

reader = self.prepare_reader(events)
multiline_input(reader)
output = multiline_input(reader)
self.assertEqual(output, "print('hello')")
output = multiline_input(reader)
self.assertEqual(output, "")


@skipUnless(pty, "requires pty")
class TestDumbTerminal(ReplTestCase):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Handle bracketed paste in :mod:`!_pyrepl` isearch mode.
Loading