hon*_*a_p 5 python autocomplete prompt-toolkit
我正在为我的项目创建一个 REPL 工具,该工具(为了清楚起见而进行了简化)直接执行输入的命令,或者(如果输入命令“.x some/path/to/file”)从文件读取并执行它们。我的问题与自动完成用户输入(使用prompt_toolkit)有关。
我有类似的东西(最小可执行示例):
import prompt_toolkit
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.document import Document
from prompt_toolkit.contrib.completers import PathCompleter
class CommandCompleter(Completer):
def __init__(self):
self.path_completer = PathCompleter()
self.commands = [".x", "command1", "command2"]
def get_completions(self, document, complete_event):
if document.text.startswith(".x "):
sub_doc = Document(document.text[3:])
yield from (Completion(cmd.text, -document.cursor_position)
# ???????? ?????????????????????????
for cmd
in self.path_completer.get_completions(sub_doc, complete_event))
# ???????
else:
yield from (Completion(cmd, -document.cursor_position)
for cmd in self.commands
if cmd.startswith(document.text))
if __name__ == "__main__":
while True:
other_args = {}
input = prompt_toolkit.prompt(">>> ", completer=CommandCompleter(), **other_args)
# Do something with input (omitted)
Run Code Online (Sandbox Code Playgroud)
第二个 if 分支(用于命令)工作正常,但我不知道如何正确调用该方法并根据第一个分支中的结果(??? 所在的位置)PathCompleter.get_completions()重建对象。Completion诀窍在于,我仅对输入的一部分使用补全,而各种子字符串、位置计算等(尚未)导致令人满意的行为(即提供路径并构建正确的输入行)。
我肯定会继续搜索,但如果有人知道如何重写它,那将非常有用。
注意:yield from self.path_completer.get_completions(document, complete_event)如果整个输入只是路径(并且这可以正常工作),则将使用它。
可能以下内容应该修复它:
sub_doc = Document(document.text[3:])
yield from (Completion(completion.text, completion.start_position, display=completion.display)
for completion
in self.path_completer.get_completions(sub_doc, complete_event))
Run Code Online (Sandbox Code Playgroud)
completion.text包含要插入的文本;completion.start_position包含相对于光标位置要插入文本的位置(在这个特定示例中,我们可以从嵌套完成器中获取值)。completion.display是弹出菜单中显示的值。(在这种情况下,是整个文件名,而不仅仅是插入的字符串。如果您还有其他问题,请随时打开 GitHub 问题。