CPython interactive readline — better backwards deletion of words

configuration, python, readline

Solution

Answering my own question because I have found the answer here:

https://superuser.com/questions/212446/binding-backward-kill-word-to-ctrlw

Short answer is: in addition to adding

import readline
readline.parse_and_bind('"\\C-w": backward-kill-word')

to `~/.pythonrc.py`, execute this:

stty werase undef

sometime before running Python in the same terminal. This will get control over `C-w` from the terminal.

Not deleting the question in case someone stumbles into the issue in Python interactive context.

Problem

Is it possible to change word boundaries for `readline` in CPython 2.7 or 3.3? I want `backward-kill-word` (bound to comfortable `C-w`) and `backward-word` have exactly the same word boundaries as `forward-word` and `forward-kill-word`. Currently `C-w` erases half the line disregarding syntax, dots etc, and stretching out for `M-DEL` for more sensible backwards deletion is too much of a hassle. I also do not want to use IPython for now. Simply reconfiguring `C-w` to act like `M-DEL` would be nice (setting it to `backward-kill-word` does not do anything because `M-DEL` function is probably called something else.) Update: it gets stranger! ``` >>> import readline >>> readline.parse_and_bind('"C-k": backward-kill-word') (press up, press C-k a lot, witness it working) >>> readline.parse_and_bind('"\\C-w": backward-kill-word') (press up, press C-w, and see that its function did not change, it wasn't re-bound!) ```

Original source