0

I've been playing with Python's readline module. One of the things I noticed is the lack of support to directly bind a key to a Python function. In other words, there is no binding for readline's rl_bind_key().

My intention is to have different completion logics depending on the key pressed. For example, apart from the traditional tab completion, I would like to bind something like C-<space> and perform completion using a different function. Or, another example, to imitate Cisco shell and bind the ? key to a command listing with a description.

With only one completer bound, is it possible to retrieve the key that triggered the completion event?

Thanks.

C2H5OH
  • 5,452
  • 2
  • 27
  • 39
  • 1
    A slightly different answer: I don't know readline well enough, but there is a pure Python library that offers similar behavior, which you could tweak if needed: https://bitbucket.org/pypy/pyrepl – Armin Rigo Jul 24 '13 at 14:17
  • Looks interesting, I'll take a look, thanks :-) – C2H5OH Jul 24 '13 at 15:51

1 Answers1

0

Based on readline 6.2.4.1, I added a new function to pass the value of variable rl_completion_invoking_key to python in readline.c, and generated my own readline.so. Then I can decide different behaviors according to the invoking keys in the complete() function.

readline.c:
static PyObject *
get_completion_invoking_key(PyObject *self, PyObject *noarg)
{
    return PyInt_FromLong(rl_completion_invoking_key);
}

PyDoc_STRVAR(doc_get_completion_invoking_key,
"get_completion_invoking_key() -> int\n\
Get the invoking key of completion being attempted.");

static struct PyMethodDef readline_methods[] =
{
...
{"get_completion_invoking_key", get_completion_invoking_key,
 METH_NOARGS, doc_get_completion_invoking_key},
...
}

in your own code:
readline.parse_and_bind("tab: complete")    # invoking_key = 9
readline.parse_and_bind("space: complete")  # invoking_key = 32
readline.parse_and_bind("?: complete")      # invoking_key = 63

def complete(self, text, state):
    invoking_key = readline.get_completion_invoking_key()
C.Young
  • 1
  • 1