Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jupyter: Move cell to top of notebook

Often I realize halfway through a notebook that I forgot an import and I want to move it to the top of the notebook (where I try to keep most of my imports). Is there a way to add a keyboard shortcut to ~/.jupyter/custom/custom.js that moves a cell to the top of a notebook?

Currently I do this by cutting the cell, scrolling to the top of the notebook, pasting and scrolling back down to where I was (often losing my place on the way back).

Below is some code from fastai forums to accomplish a different task: going to the running cell:

Jupyter.keyboard_manager.command_shortcuts.add_shortcut('CMD-I', {
    help : 'Go to Running cell',
    help_index : 'zz',
    handler : function (event) {
        setTimeout(function() {
            // Find running cell and click the first one
            if ($('.running').length > 0) {
                //alert("found running cell");
                $('.running')[0].scrollIntoView();
            }}, 250);
        return false;
    }
});

screenshot of problem

like image 242
Sam Shleifer Avatar asked Oct 30 '18 18:10

Sam Shleifer


1 Answers

It's partially documented; however you have to know a little JavaScript to create a keyboard shortcut.

As you've figured out, edit custom.js to bind a keyboard shortcut, as mentioned in the documentation (the second method must be used if the action is not built-in)

For the documentation, read the source code (either online or in site-packages/notebook/static/notebook/js/*.js if you installed jupyter locally). In particular, actions.js contains example bindings and notebook.js contains the functions that you can call on the notebook.

This is an example. It has the disadvantage of modifying the jupyter clipboard. To avoid that, you might be able to look into the source code of notebook.move_cell_down function to see how it's implemented, and modify it correspondingly.

Jupyter.keyboard_manager.command_shortcuts.add_shortcut('cmdtrl-I', {
    help : 'Move cell to first in notebook',
    handler : function (env) {
        var index = env.notebook.get_selected_index();
        env.notebook.cut_cell();
        env.notebook.select(0);
        env.notebook.paste_cell_above();
        env.notebook.select(index);
    }
});
like image 185
user202729 Avatar answered Sep 29 '22 03:09

user202729