Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strip paste-bracketing control characters #250

Merged
merged 2 commits into from
Aug 1, 2022
Merged
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
12 changes: 10 additions & 2 deletions metakernel/replwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def run_command(self, command, timeout=None, stream_handler=None,
for line in cmdlines[1:]:
if not self.prompt_emit_cmd:
self._expect_prompt(timeout=timeout)
res.append(self.child.before)
res.append(strip_bracketing(self.child.before))
self.sendline(line)

# Command was fully submitted, now wait for the next prompt
Expand All @@ -246,7 +246,7 @@ def run_command(self, command, timeout=None, stream_handler=None,

if self._stream_handler or self._line_handler:
return u''
return u''.join(res + [self.child.before])
return u''.join(res + [strip_bracketing(self.child.before)])

def interrupt(self, continuation=False):
"""Interrupt the process and wait for a prompt.
Expand Down Expand Up @@ -322,3 +322,11 @@ def bash(command="bash", prompt_regex=re.compile('[$#]')):
def powershell(command='powershell', prompt_regex='>'):
""""Start a powershell and return a :class:`REPLWrapper` object."""
return REPLWrapper(command, prompt_regex, 'Function prompt {{ "{0}" }}', echo=True)


def strip_bracketing(string, start='\x1b[?2004l', stop='\x1b[?2004h'):
"""Strip 'bracketed paste' control characters, if they are present"""
if string.startswith(start) and string.endswith(stop):
return string[len(start):-len(stop)]
else:
return string
9 changes: 9 additions & 0 deletions metakernel/tests/test_replwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@ def test_python(self):
res = p.run_command('for a in range(3): print(a)\n')
assert res.strip().splitlines() == ['0', '1', '2']

def test_bracketed_paste(self):
# Readline paste bracketing is easily toggled in bash, but can be harder elsewhere
# This tests that run_command() still works with it enabled (the default for readline,
# but overriden by bash and python)
bash = replwrap.bash()
bash.run_command("bind 'set enable-bracketed-paste on'")
res = bash.run_command("echo '1 2\n3 4'")
self.assertEqual(res.strip().splitlines(), ['1 2', '3 4'])


if __name__ == '__main__':
unittest.main()