vimeditorcelljupyter-notebook

Edit IPython cell in an external editor


It would be great to have a keyboard short-cut in IPython notebook, which would allow to edit the content of the current cell in an external editor (e.g. gvim). Maybe just copy the content of the current cell into a temporary file, launch gvim on it, and update the current cell each time the file is saved (and delete the temporary file when exiting gvim). Also, maybe update the temporary file if the cell is edited from the browser, so that gvim knows the file has changed.

I am aware of projects like vim-ipython and ipython-vimception, but they don't correspond to my needs. I think the browser is enough for simple things, but when more powerful editing is required there is no need to reinvent the wheel.

Do you know if such a feature exists in IPython notebook already?

Thanks.


Solution

  • This is what I came up with. I added 2 shortcuts:

    So, when you want to edit the cell with your preferred editor, hit 'g', make the changes you want to the cell, save the file in your editor (and quit), then hit 'u'.

    Just execute this cell to enable these features:

    %%javascript
    
    IPython.keyboard_manager.command_shortcuts.add_shortcut('g', {
        handler : function (event) {
            var input = IPython.notebook.get_selected_cell().get_text();
            var cmd = "f = open('.toto.py', 'w');f.close()";
            if (input != "") {
                cmd = '%%writefile .toto.py\n' + input;
            }
            IPython.notebook.kernel.execute(cmd);
            cmd = "import os;os.system('gvim .toto.py')";
            IPython.notebook.kernel.execute(cmd);
            return false;
        }}
    );
    
    IPython.keyboard_manager.command_shortcuts.add_shortcut('u', {
        handler : function (event) {
            function handle_output(msg) {
                var ret = msg.content.text;
                IPython.notebook.get_selected_cell().set_text(ret);
            }
            var callback = {'output': handle_output};
            var cmd = "f = open('.toto.py', 'r');print(f.read())";
            IPython.notebook.kernel.execute(cmd, {iopub: callback}, {silent: false});
            return false;
        }}
    );