How to move line (not cell) up/down in jupyter notebook using keyboard shortcut?

Viewed 4887

How can I move a line (or set of selected lines) down or up in jupyter notebook. Are there any shortcuts?

After moving line 3 one line up:

For example ALT+UP or ALT+DOWN is for up/down displacement that is used in Eclipse IDE.
This question discusses cell displacement.

5 Answers

TLDR: By following this tutorial, I was able to enable all the sublime-text shortcuts (which includes the moving lines with Ctrl+Up/Ctrl/Down).

I then was able to furthermore, customize the shortcuts by editing the sublime.js

Complete answer:

  1. Find your jupyter path with jupyter --config-dir
  2. Add the following code to <JUPYTER-PATH>/custom/custom.js:
require(["codemirror/keymap/sublime", "notebook/js/cell", "base/js/namespace"],
    function(sublime_keymap, cell, IPython) {
        // setTimeout(function(){ // uncomment line to fake race-condition
        cell.Cell.options_default.cm_config.keyMap = 'sublime';
        var cells = IPython.notebook.get_cells();
        for(var cl=0; cl< cells.length ; cl++){
            cells[cl].code_mirror.setOption('keyMap', 'sublime');
        }
 
        // }, 1000)// uncomment  line to fake race condition 
    } 
);
  1. You need to find this codemirror/keymap/sublime.js (that is required in the code from point 2), for me, it was in <MY-PYTHON-ENVIRONMENT>/lib/python3.8/site-packages/notebook/static/components/codemirror/keymap/sublime.js
  2. At the end of this file, you can edit the shortcuts, in the keyMap.pcSublime section of this file (if you have a PC).
  3. For OP, the lines to edit would be: swapLineUp and swapLineDown

I did this with Ubuntu & sublime installed.


You can select the line with mouse in jupyter notebook. Drag it up or down before the line where you want to move it. Press > button on keyboard while your text is still selected.
This will bring the cursor to end of selected line, but before the text of line being replaced. Press Enter.


enter image description here

There's no such a shortcut in Jupyter, however, you can manage your own shorcuts Go to Help > Edit keyboard Shortcuts and start setting your commands.

There's some good info on this other post which will lead you to manage your profile's notebook.json file and so on.

Hope this was useful ;)

Edit: typo

Related