Question

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!)
Was it helpful?

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.

OTHER TIPS

Building on @mischa-arefiev's answer, I now have the following in my PYTHONSTARTUP file, which works for ipython2 and ipython3:

import readline
import subprocess
readline.parse_and_bind('"\\C-w": backward-kill-word')
subprocess.call(['stty', 'werase', 'undef'])

I use it on Linux, and I'm not sure if it also works on Mac.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top