ipython:更改 PageDown/PageUp 以在命令历史记录中移动 back/forward

ipython: change PageDown/PageUp to move back/forward through command history

在我的 shell (zsh) 或 python 中,我可以通过按 PageDown 向后浏览命令历史记录,然后我可以按 PageUp.

前进

但在 ipython 中,这些快捷方式是相反的。

这些为 ipython 定义的快捷方式在哪里,我怎样才能将它们反转回来,以便

PageDown历史倒退,PageUp历史前进?

我在 Debian 10 上使用 ipython3 版本 5.8.0

在IPython版本5.x中,文档中提到了这一点:Specific config details — IPython 5.11.0.dev documentation

要获取要绑定的函数,请参阅key_binding/bindings/basic.py:默认值为

handle("pageup", filter=~has_selection)(get_by_name("previous-history"))
handle("pagedown", filter=~has_selection)(get_by_name("next-history"))

所以,把这个代码放在 startup file:

from IPython import get_ipython
from prompt_toolkit.filters import HasSelection
from prompt_toolkit.keys import Keys
from prompt_toolkit.key_binding.bindings.named_commands import get_by_name

registry = get_ipython().pt_cli.application.key_bindings_registry
registry.add_binding(Keys.PageUp, filter=~HasSelection())(get_by_name("next-history"))
registry.add_binding(Keys.PageDown, filter=~HasSelection())(get_by_name("previous-history"))

在较新的 IPython 版本(例如 7.19.0)中,将 registry = ... 行替换为

registry = get_ipython().pt_app.key_bindings

参考:Specific config details — IPython 7.19.0 documentation

~/.ipython/profile_default/startup 目录中创建脚本,任何名称以扩展名 .py.ipy

结尾

例如我创建了 history_keybindings.py 并将其放入 ~/.ipython/profile_default/startup 目录

from IPython import get_ipython
from IPython.terminal.shortcuts import previous_history_or_previous_completion, next_history_or_next_completion
from prompt_toolkit.keys import Keys
from prompt_toolkit.filters import HasSelection

ip = get_ipython()

registry = None

if (getattr(ip, 'pt_app', None)):
   # for IPython versions 7.x
   registry = ip.pt_app.key_bindings
elif (getattr(ip, 'pt_cli', None)):
   # for IPython versions 5.x
   registry = ip.pt_cli.application.key_bindings_registry

if registry:
   registry.add_binding(Keys.PageUp, filter=(~HasSelection()))(previous_history_or_previous_completion)
   registry.add_binding(Keys.PageDown, filter=(~HasSelection()))(next_history_or_next_completion)

注意:更多信息请查看here