我知道因为Ipython 5.0.0使用了一个新的输入库(prompt_toolkit),所以不再默认使用.inputrc(* nix)中指定的编辑器模式。此选项必须在Ipython配置文件中设置(请参阅https://dev59.com/i2kv5IYBdhLWcg3wvDJF#38329940)。我的问题是:在配置文件中设置vi-mode后,如何指定特定的按键绑定?例如,我喜欢使用“jk”来代替Esc键。
from IPython import get_ipython
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasFocus, ViInsertMode
from prompt_toolkit.key_binding.vi_state import InputMode
ip = get_ipython()
def switch_to_navigation_mode(event):
vi_state = event.cli.vi_state
vi_state.reset(InputMode.NAVIGATION)
if getattr(ip, 'pt_cli'):
registry = ip.pt_cli.application.key_bindings_registry
registry.add_binding(u'j',u'k',
filter=(HasFocus(DEFAULT_BUFFER)
& ViInsertMode()))(switch_to_navigation_mode)
prompt_toolkit源代码可以帮助您根据需要实现其他快捷方式。
这是一篇旧帖子,但它帮助我找到了答案,所以我想分享一下如何在IPython中添加几个绑定。我在~/.ipython/profile_default/startup/00-keybindings.py中添加了以下代码,以在vi导航模式下绑定K和J。
"""Improve history access so I can skip over functions"""
from IPython import get_ipython
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasFocus, ViNavigationMode
from prompt_toolkit.key_binding.bindings.named_commands import get_by_name
ip = get_ipython()
registry = ip.pt_app.key_bindings
ph = get_by_name('previous-history')
nh = get_by_name('next-history')
registry.add_binding('K',
filter=(HasFocus(DEFAULT_BUFFER) &
ViNavigationMode()))(ph)
registry.add_binding('J',
filter=(HasFocus(DEFAULT_BUFFER) &
ViNavigationMode()))(nh)
keybindings.py
在 IPython 5.1.0 和 7.0.1 之间的某个时间停止工作,出现错误信息'TerminalInteractiveShell' object has no attribute 'pt_cli'
。请参见 https://github.com/ipython/ipython/pull/11426/commits/e08dc1b4dd30e8d2b607134693f226e8a22100ec#diff-d47c339db04f28c44a59c6662dbd53eaR228 获取一个修复方案。 - Aaron Feldman.ipython/profile_default/startup/
目录下运行代码至关重要。我曾尝试在ipython_config.py
中实现,但失败了...所以,多年后:这仍然适用于IPython 7.12.0,也没有更好的替代方案(我进行过彻底搜索,发现这个解决方案现在已成为官方IPython文档的一部分)。 - freeo