Python中的多种完成样式

时间:2013-07-24 10:16:23

标签: python readline tab-completion

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

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

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

感谢。

1 个答案:

答案 0 :(得分:0)

基于readline 6.2.4.1,我添加了一个新函数,用于将变量rl_completion_invoking_key的值传递给readline.c中的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()