【问题标题】:Multiple completion styles in PythonPython中的多种完成样式
【发布时间】:2013-07-24 10:16:23
【问题描述】:
我一直在玩 Python 的 readline 模块。我注意到的一件事是缺乏直接将键绑定到 Python 函数的支持。也就是说,readline 的rl_bind_key() 没有绑定。
我的意图是根据按下的键有不同的完成逻辑。例如,除了传统的制表符补全之外,我还想绑定 C-<space> 之类的东西并使用不同的函数执行补全。或者,另一个示例,模仿 Cisco shell 并将 ? 键绑定到带有描述的命令列表。
只有一个完成者绑定,是否可以检索触发完成事件的键?
谢谢。
【问题讨论】:
标签:
python
readline
tab-completion
【解决方案1】:
在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()