I prefer the convenience and speed of the keyboard over using the trackpad/mouse whenever possible. Is there a means to access the Jupyter
menu bar with the keyboard. For example the Edit
menu:
On Linux we could access a top-level item as Alt-E | D
for Edit | Delete cells
. On macos
it is a headache but still possible: <Access Menubar shortcut>| E | D
.
Is there any way to achieve that on Jupyter
?
So you want to bind custom keyboard shortcuts...
The documentation tell you to use the JavaScript API, where the documentation is in the source code.
So you end up with something like this in custom.js
(it's convenient that the first characters of all the menus are distinct)
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)
}
This code binds Alt+E to clicking edit menu.
It's rather version-dependent (as it depends on the ID of the links on the menu) -- this is tested on Jupyter notebook version 6.1.6.
If you use a for loop to generate the shortcuts (like in the code above), it's very important that you register actions manually (and have different names for them) instead of add_shortcut(shortcut, handler)
because otherwise the handler would generate the action name from the string representation of the handler, and that would be all the same. No JavaScript closure can help you.
If you also want to use Enter key to select a menu, you have to do a little more -- because by default it's bound to enter edit mode:
{
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")
}
})
}
Modify it a little more if you want to add shortcut for the 2 other menus, as they don't conveniently have an ID.