Keyboard shortcut to move cells up and down in Jupyter Lab

While PyCharm is my go-to Python IDE for software development, I love Jupyter Lab for data science and machine learning work, as well as general exploration. For example, if I’m coding against a poorly documented web API, it’s great to be able to pick apart the response object piece by piece in a notebook to figure out what I’m dealing with.

When I first started working in Jupyter Lab, I really missed the ability to move blocks of code around with just the keyboard. Most modern IDE’s have this feature, and once you’ve gotten used to working this way, it’s hard to live without.

It turns out you can configure a custom shortcut in Jupyter Lab to at least get this behavior at the cell level, while in command mode. While this isn’t as powerful as moving single lines of code up an down in an IDE I’ve still found it to be a nice improvement that makes working in Jupyter notebooks a bit more enjoyable.

1. Click Settings > Advanced Settings Editor

2. Select Keyboard Shortcuts

3. In the “User Preferences” pane on the right, add this code (or combine it with whatever other user shortcuts you’ve already defined):

{
    // notebook:move-cell-up
    // notebook:move-cell-down
    "shortcuts":[
        {
            "command": "notebook:move-cell-up",
            "keys": [
                "Ctrl Shift ArrowUp"
            ],
            "selector": ".jp-Notebook:focus"
        },
        {
            "command": "notebook:move-cell-down",
            "keys": [
                "Ctrl Shift ArrowDown"
            ],
            "selector": ".jp-Notebook:focus"
        }
    ]
}

I’ve chose to use Ctrl + Shift + up / down to mimic PyCharm’s behavior. You can of course use whatever key combo makes sense for your workflow.

Now you can move the selected cell or cells up and down in our notebook with just the keyboard. Enjoy!

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.