Skip to content

Commit ca855aa

Browse files
committed
Strip prompts and output from pasted REPL sessions
1 parent ee521e8 commit ca855aa

5 files changed

Lines changed: 202 additions & 1 deletion

File tree

‎Doc/tutorial/appendix.rst‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ details. Function keys provide some additional functionality.
2424
makes pasting larger blocks of code easier. Press :kbd:`F3` to return to
2525
the regular prompt.
2626

27+
In terminals that support bracketed paste, pasting an interactive session
28+
starting with ``>>>`` into an empty input buffer automatically removes the
29+
``>>>`` and ``...`` prompts and omits output lines. The pasted code can be
30+
edited before running it. Pasting into a nonempty input buffer leaves the
31+
text unchanged.
32+
2733
When using the new interactive shell, exit the shell by typing :kbd:`exit`
2834
or :kbd:`quit`. Adding call parentheses after those commands is not
2935
required.

‎Doc/whatsnew/3.16.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,16 @@ Summary --- release highlights
7070
New features
7171
============
7272

73+
Pasting interactive sessions
74+
---------------------------
75+
76+
The :ref:`interactive shell <tut-interac>` now recognizes pasted Python
77+
sessions starting with ``>>>``. When the input buffer is empty, it removes
78+
the ``>>>`` and ``...`` prompts and omits output lines, preserving indentation.
79+
The resulting code remains editable until you submit it. This requires a
80+
terminal that supports bracketed paste; pasting into existing input or an
81+
:func:`input` prompt leaves the text unchanged.
82+
(Contributed by Bartosz Sławecki in :gh:`157612`.)
7383

7484

7585
Other language changes

‎Lib/_pyrepl/commands.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
from __future__ import annotations
2323
import os
24+
import re
2425
import time
2526
from typing import TYPE_CHECKING
2627

@@ -518,4 +519,19 @@ def do(self) -> None:
518519
l=len(data),
519520
s=time.time() - start,
520521
)
521-
self.reader.insert(data.replace(done, ""))
522+
data = data.replace(done, "")
523+
if (
524+
not self.reader.buffer
525+
and getattr(self.reader, "more_lines", None) is not None
526+
and data[:3] == ">>>"
527+
and data[3:4] in ("", " ", "\r", "\n")
528+
):
529+
# A pasted interactive session contains prompts and output.
530+
lines = []
531+
for line in re.findall(r"[^\r\n]*(?:\r\n?|\n|$)", data):
532+
if line.startswith((">>> ", "... ")):
533+
lines.append(line[4:])
534+
elif line.rstrip("\r\n") in (">>>", "..."):
535+
lines.append(line[3:])
536+
data = "".join(lines)
537+
self.reader.insert(data)

‎Lib/test/test_pyrepl/test_pyrepl.py‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import subprocess
1212
import sys
1313
import tempfile
14+
import textwrap
1415
from functools import partial
1516
from pkgutil import ModuleInfo
1617
from unittest import TestCase, skipUnless, SkipTest
@@ -1985,6 +1986,169 @@ def test_bracketed_paste_single_line(self):
19851986
output = multiline_input(reader)
19861987
self.assertEqual(output, input_code)
19871988

1989+
def test_bracketed_paste_repl_session(self):
1990+
cases = [
1991+
(">>> 1 + 1", "1 + 1"),
1992+
(
1993+
"""\
1994+
>>> 1 + 1
1995+
2
1996+
>>> """,
1997+
"1 + 1\n",
1998+
),
1999+
(
2000+
"""\
2001+
>>> def double(value):
2002+
... return value * 2
2003+
...
2004+
>>> result = double(3)
2005+
>>> print(result)
2006+
6
2007+
""",
2008+
"""\
2009+
def double(value):
2010+
return value * 2
2011+
2012+
result = double(3)
2013+
print(result)
2014+
""",
2015+
),
2016+
(
2017+
"""\
2018+
>>> 1 / 0
2019+
Traceback (most recent call last):
2020+
File "<stdin>", line 1, in <module>
2021+
ZeroDivisionError: division by zero
2022+
>>> print('hello')
2023+
hello
2024+
""",
2025+
"""\
2026+
1 / 0
2027+
print('hello')
2028+
""",
2029+
),
2030+
(
2031+
"""\
2032+
>>> if True:
2033+
... print('hello')
2034+
...
2035+
hello
2036+
>>>""",
2037+
"""\
2038+
if True:
2039+
print('hello')
2040+
2041+
""",
2042+
),
2043+
(
2044+
'''\
2045+
>>> text = """hello
2046+
... >>> world
2047+
... ...
2048+
... """
2049+
''',
2050+
'''\
2051+
text = """hello
2052+
>>> world
2053+
...
2054+
"""
2055+
''',
2056+
),
2057+
(">>> print('caf\u00e9')\n", "print('caf\u00e9')\n"),
2058+
(
2059+
'>>> text = "\v\f\x85\u2028\u2029"\n',
2060+
'text = "\v\f\x85\u2028\u2029"\n',
2061+
),
2062+
(">>>", ""),
2063+
]
2064+
for source, expected in cases:
2065+
source = textwrap.dedent(source)
2066+
expected = textwrap.dedent(expected)
2067+
for newline in ("\n", "\r\n", "\r"):
2068+
with self.subTest(source=source, newline=newline):
2069+
events = code_to_events(
2070+
"\x1b[200~" + source.replace("\n", newline)
2071+
+ "\x1b[201~"
2072+
)
2073+
reader, _ = handle_all_events(
2074+
events,
2075+
prepare_console=FakeConsole,
2076+
prepare_reader=partial(
2077+
ReadlineAlikeReader,
2078+
config=ReadlineConfig(readline_completer=None),
2079+
more_lines=more_lines,
2080+
),
2081+
)
2082+
self.assertEqual(
2083+
reader.get_unicode(), expected.replace("\n", newline)
2084+
)
2085+
self.assertEqual(reader.pos, len(reader.buffer))
2086+
self.assertFalse(reader.finished)
2087+
2088+
def test_bracketed_paste_preserves_non_session(self):
2089+
for source in (
2090+
"print('hello')\n",
2091+
"...",
2092+
"... value\n",
2093+
">>>> value\n",
2094+
">>>value\n",
2095+
textwrap.dedent('''\
2096+
text = """
2097+
>>> example
2098+
... example
2099+
"""
2100+
'''),
2101+
):
2102+
with self.subTest(source=source):
2103+
events = code_to_events(
2104+
"\x1b[200~" + source + "\x1b[201~"
2105+
)
2106+
reader, _ = handle_all_events(
2107+
events, prepare_console=FakeConsole
2108+
)
2109+
self.assertEqual(reader.get_unicode(), source)
2110+
2111+
def test_bracketed_paste_preserves_session_in_nonempty_buffer(self):
2112+
source = textwrap.dedent("""\
2113+
>>> print('hello')
2114+
hello
2115+
""")
2116+
for initial in (" ", "value = ", 'text = """\n'):
2117+
for pos in (0, len(initial)):
2118+
with self.subTest(initial=initial, pos=pos):
2119+
def prepare_reader(console):
2120+
reader = ReadlineAlikeReader(
2121+
console,
2122+
config=ReadlineConfig(readline_completer=None),
2123+
more_lines=more_lines,
2124+
)
2125+
reader.insert(initial)
2126+
reader.pos = pos
2127+
return reader
2128+
2129+
events = code_to_events(
2130+
"\x1b[200~" + source + "\x1b[201~"
2131+
)
2132+
reader, _ = handle_all_events(
2133+
events,
2134+
prepare_console=FakeConsole,
2135+
prepare_reader=prepare_reader,
2136+
)
2137+
self.assertEqual(
2138+
reader.get_unicode(), initial[:pos] + source + initial[pos:]
2139+
)
2140+
2141+
def test_bracketed_paste_preserves_prompts_in_input(self):
2142+
source = ">>> not a REPL session"
2143+
events = code_to_events("\x1b[200~" + source + "\x1b[201~\n")
2144+
reader = self.prepare_reader(events)
2145+
self.assertEqual(reader.readline(), source)
2146+
2147+
def test_bracketed_paste_repl_session_edit_and_run(self):
2148+
events = code_to_events("\x1b[200~>>> 1 + 1\x1b[201~\b2\n")
2149+
reader = self.prepare_reader(events)
2150+
self.assertEqual(multiline_input(reader), "1 + 2")
2151+
19882152

19892153
@skipUnless(pty, "requires pty")
19902154
class TestDumbTerminal(ReplTestCase):
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
The new interactive shell now strips ``>>>`` and ``...`` prompts and omits
2+
output when an interactive session is pasted into an empty input buffer using
3+
bracketed paste. The code remains editable before execution, and pastes into
4+
existing input or an :func:`input` prompt are unchanged.
5+
Patch by Bartosz Sławecki.

0 commit comments

Comments
 (0)