prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.1k stars 717 forks source link

Confusing mapping 127→Backspace on Windows #1796

Open MadameMinty opened 8 months ago

MadameMinty commented 8 months ago

On Windows 10, using Windows Terminal as well as the integrated conhost, I tried using ptpython as well as ipython REPLs, both using prompt-toolkit==3.0.39. I encountered an issue: Ctrl+Backspace worked like a regular Backspace.

I looked around, checked configs of the REPLs, and nothing worked until I decided to dig into prompt-toolkit. There, in file input\win32.py i.e. https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/input/win32.py, is a line mapping an input sequence to a key:

        b"\x7f": Keys.Backspace,  # (127) Backspace   (ASCII Delete.)

however, when using this handy code:

import msvcrt
while True:
    key = msvcrt.getch()
    if key == b'\x1b':  break # 'ESC'
    print(f"ASCII: {ord(key)} = {hex(ord(key))}")

I see that inside REPLs, Ctrl+Backspace is 127 = 0x7f, Backspace and Meta+Backspace is 8 = 0x8.

For my purposes, I fixed the problem for the time being by replacing this mapping with:

        b"\x7f": Keys.ControlW,

and now Ctrl+Backspace works as expected (backward_kill_word is called) everywhere. Also, I'm a little confused what's going on, and why this mapping was like this. How Meta+Backspace seemingly sends Backspace sequence, yet also calls backward_kill_word, while Backspace just backspaces, is a cherry on top.

It looks like a bug—but maybe my config is somehow a strange outlier?