访问 Jupyter notebook 菜单栏的快捷键/组合键

Shortcut / key combination to access Jupyter notebook menu bar

与使用 trackpad/mouse 相比,我更喜欢键盘的便利性和速度。有没有办法用键盘访问 Jupyter 菜单栏。例如 Edit 菜单:

在 Linux 上,我们可以访问顶级项目作为 Alt-E | D for Edit | Delete cells。在 macos 上很头疼,但仍有可能:<Access Menubar shortcut>| E | D.

有什么方法可以在 Jupyter 上实现吗?

所以你想绑定自定义键盘快捷键...

The documentation tell you to use the JavaScript API, where the documentation is in the source code.

所以你最终会在 custom.js 中得到这样的结果(所有菜单的第一个字符都不同很方便)

for(let id of ["filelink", "editlink", "viewlink", "insertlink", "celllink", "kernellink"]) {
    const element=document.getElementById(id)
    const actionName=Jupyter.notebook.keyboard_manager.actions.register(function (env) { element.click() },
        `open-menu-${id[0]}`, "custom")
    const shortcut='alt-'+id[0]
    Jupyter.keyboard_manager.command_shortcuts.add_shortcut(shortcut, actionName)
    Jupyter.keyboard_manager.edit_shortcuts.add_shortcut(shortcut, actionName)
}

此代码将 Alt+E 绑定到单击编辑菜单。

它相当依赖于版本(因为它取决于菜单上链接的 ID)——这是在 Jupyter notebook 版本 6.1.6 上测试的。

如果您使用 for 循环生成快捷方式(如上面的代码),请务必手动注册操作(并为它们指定不同的名称)而不是 add_shortcut(shortcut, handler),否则处理程序generate the action name from the string representation of the handler, and that would be all the same. No JavaScript closure 能帮到你吗

如果您还想使用 Enter 键进入 select 菜单,您需要多做一点——因为默认情况下它会进入编辑模式:

{
    Jupyter.keyboard_manager.command_shortcuts.add_shortcut("enter", function(env){
        const element=document.activeElement
        if(element.getAttribute("role")==="menuitem")
            element.click()
        else{
            env.notebook.edit_mode();
            // alternatively:
            //env.notebook.keyboard_manager.actions.call("jupyter-notebook:enter-edit-mode")
        }
    })
}

如果您想为其他 2 个菜单添加快捷方式,请稍微修改一下,因为它们没有方便的 ID。