0

我一直在玩 Python 的readline模块。我注意到的一件事是缺乏直接将键绑定到 Python 函数的支持。换句话说,readline 没有绑定rl_bind_key()

我的意图是根据按下的键有不同的完成逻辑。例如,除了传统的制表符补全之外,我想绑定类似的东西C-<space>并使用不同的函数执行补全。或者,另一个示例,模仿 Cisco shell 并将?密钥绑定到带有描述的命令列表。

只有一个完成者绑定,是否可以检索触发完成事件的键?

谢谢。

4

1 回答 1

0

在readline 6.2.4.1的基础上,我在readline.c中添加了一个新函数,将变量rl_completion_invoking_key的值传递给python,并生成了我自己的readline.so。然后我可以根据 complete() 函数中的调用键来决定不同的行为。

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()
于 2017-01-18T07:59:10.720 回答