Skip to content

Commit

Permalink
Strip paste-bracketing control characters (#250)
Browse files Browse the repository at this point in the history
Co-authored-by: Jan Petykiewicz <[email protected]>
  • Loading branch information
anewusername and anewusername authored Aug 1, 2022
1 parent 80d504e commit 68b0da7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
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()

0 comments on commit 68b0da7

Please sign in to comment.