WalkingRandomly
WalkingRandomly

Reputation: 4557

How can I block comment code in the IPython notebook?

I have defined a function in an IPython notebook and would like to be able to block comment a section of it. Intuitively, I'd expect to be able to highlight a section of code, right click and have an option to comment out the selection but this has not been implemented.

Is there a way to do this?

Upvotes: 35

Views: 36752

Answers (4)

Numbermind
Numbermind

Reputation: 103

For me Ctrl + ^/~. I'm using windows 10 and Jupyter Notebook.

Upvotes: 0

Raphael Montaud
Raphael Montaud

Reputation: 31

Solution that should work for any keyboard layout:

Following this blogpost: https://towardsdatascience.com/jupyter-notebook-extensions-517fa69d2231, you can install some plugins for jupyter notebook with the command:

pip install jupyter_contrib_nbextensions && jupyter contrib nbextension install 

Now launch jupyter and go the new Nbextensions tab. There is a plugin called Comment/Uncomment Hotkey. Activate it and choose your hotkey. For example Alt + C. Now you can comment/uncomment a line or a block by selecting it and using your new hotkey.

Upvotes: 3

nomara
nomara

Reputation: 31

i have a german Keyboard and tried out some keys. The following worked: [strg] + [#]

Upvotes: 3

Jakob
Jakob

Reputation: 20811

Default solution

In IPython 2.x and 3.x (cmd|ctrl)-/ works but requires an english (american) keyboard layout, see https://github.com/ipython/ipython/pull/3673.

Other keyboard layouts

In case you have a non-english keyboard layout, you can define a custom keybinding for the codemirror editor via your custom.js. To this end add e.g. the following lines

define([
    'base/js/namespace',
    'base/js/events'
    ],
    function(IPython, events) {
        events.on("app_initialized.NotebookApp",
            function () {
                IPython.Cell.options_default.cm_config.extraKeys = {"Ctrl-," : "toggleComment"};
            }
        );
    }
);

to use Ctrl+, to toggle (block) comments. I use this with a german keyboard layout and IPython 3.0. The previous solution (see edits) worked fine with chrome, but not with firefox.

Old solution (IPython 1.x)

If you are using IPython 1.x you can try the comment-uncomment.js from https://github.com/ipython-contrib/IPython-notebook-extensions - I haven't tried this yet, but I guess its a good start.

Upvotes: 55

Related Questions