Sraffa
Sraffa

Reputation: 1668

Map keyboard shortcut to code snippet in Jupyter Lab

Does anyone know if there a way to bind a code snippet to a keyboard shortcut in Jupyter Lab? For example in R Studio you can use Ctrl+Shift+M to write the pipe operator (%>%) quickly and I got used to that functionality so I would like to replicate it.

I looked at the Keyboard Shortcut menu under Settings but I'm not sure how to use the JSON schema to write such an Override (if it is even possible from there), and the documentation wasn't very clear.

Upvotes: 7

Views: 1857

Answers (2)

krassowski
krassowski

Reputation: 15379

In JupyterLab 2.1+ you can configure your keyboard shortcuts for R with the following:

{
    "shortcuts": [
        {
            "command": "apputils:run-first-enabled",
            "selector": "body",
            "keys": ["Alt -"],
            "args": {
                "commands": [
                    "console:replace-selection",
                    "fileeditor:replace-selection",
                    "notebook:replace-selection",
                ],
                "args": {"text": "<- "}
            }
        },
        {
            "command": "apputils:run-first-enabled",
            "selector": "body",
            "keys": ["Accel Shift M"],
            "args": {
                "commands": [
                    "console:replace-selection",
                    "fileeditor:replace-selection",
                    "notebook:replace-selection",
                ],
                "args": {"text": "%>% "}
            }
        }
    ]
}

Accel means Ctrl on Linux and Windows, or Command on Mac.

Just go to the Advanced Settings Editor -> Keyboard Shortcuts, paste and save:

illustration

Related issues in JupyterLab repository: #4519, #7908, #10114.

Alternatively, for more advanced functionality, like kernel-specific shortcuts or automatic padding you can use jupyterext-text-shortcuts extension.

Upvotes: 7

PaulDong
PaulDong

Reputation: 793

OK I don't have a good answer for Jupyter Lab, but for good old jupyter notebook, just ran the below cell would give you what you want:

IRdisplay::display_javascript("Jupyter.keyboard_manager.edit_shortcuts.add_shortcut('Ctrl-Shift-M', {
    help : 'add pipe symbol',
    help_index : 'zz',
    handler : function (event) {
        var target = Jupyter.notebook.get_selected_cell()
        var cursor = target.code_mirror.getCursor()
        var before = target.get_pre_cursor()
        var after = target.get_post_cursor()
        target.set_text(before + ' %>% ' + after)
        cursor.ch += 5
        target.code_mirror.setCursor(cursor)
        return false;
    }}
);")

Upvotes: 3

Related Questions