How to get the invoking_key of complete function with readline?

124 Views Asked by At

I'm new in coding, and have been working on a cisco os style command line interface with auto-completion function. It seems python's builtin module readline would be my feasible choice. I intend to make the key-presses of 'TAB', 'space' and '?' to achieve completion with slight different behaviors, but only one complete function is supported to be bound to, and i'm not sure if there is a way to get which key has just invoked this function. Or should i look for other choice for this purpose? Any hint will be much appreciated!

1

There are 1 best solutions below

0
On

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 my 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()