Search code examples
jupyter-notebookjupyterjupyter-labjupyterhub

Keyboard shortcut to expand code snippets in JupyterLab


Does anyone know how to make a shortcut that would paste a certain code to the selected cell or expand a snippet into a chunk of code?
For example I would like to fill a cell with a list of useful imports when pressing something like Ctrl+Shift+M. This would expand the cell content to:
import numpy as np import pandas as pd (...) .

Optionally this could work also like text completion tools available in some IDEs. For example when I write something like:
;imp + TAB .

it would expand into the same list as above.

Any ideas how this could be defined in JupyterLab?

I saw this answer, but it does not work for me (returning javascript error)


Solution

  • In JupyterLab 2.1+ you can add a shortcut to insert a snippet using the following settings:

    {
        "shortcuts": [
            {
                "command": "apputils:run-first-enabled",
                "selector": "body",
                "keys": ["Accel Shift M"],
                "args": {
                    "commands": [
                        "console:replace-selection",
                        "fileeditor:replace-selection",
                        "notebook:replace-selection",
                    ],
                    "args": {"text": "import numpy as np\nimport pandas as pd\n"}
                }
            }
        ]
    }
    

    For more detailed instruction see my new answer to the question you linked.

    Another option is to use one of the code snippet extensions for JupyterLab: