Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map keyboard shortcut to code snippet in Jupyter Lab

Tags:

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.

like image 978
Sraffa Avatar asked Mar 22 '18 23:03

Sraffa


People also ask

How do I add a code snippet to Jupyter Notebook?

Inserting a snippetClick the snippet's insert icon to paste the snippet content in the desired destination, such as a cell in a notebook or an open editor window. Drag-and-Drop of the snippet has also been incorporated in the latest Elyra release.

How do I change keyboard shortcuts in JupyterLab?

Starting with Jupyter Notebook 5.0, you can customize the command mode shortcuts from within the Notebook Application itself. Head to the ``Help`` menu and select the ``Edit keyboard Shortcuts`` item. A dialog will guide you through the process of adding custom keyboard shortcuts.

How do I create a shortcut to a folder in Jupyter Notebook?

Creating Your Own Jupyter Notebook Shortcut. To begin, we must have already installed Jupyter Notebook or Jupyter Lab. Next, navigate to the folder we want to create your shortcut. Right-click, select 'New', then create a shortcut.


1 Answers

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;
    }}
);")
like image 173
PaulDong Avatar answered Sep 22 '22 13:09

PaulDong