233

I am using ipython Jupyter notebook. Let's say I defined a function that occupies a lot of space on my screen. Is there a way to collapse the cell?

I want the function to remain executed and callable, yet I want to hide / collapse the cell in order to better visualize the notebook. How can I do this?

aloha
  • 4,554
  • 6
  • 32
  • 40
  • 12
    JupyterLab has this since 2019. Highlight a cell and then click on the blue bar next to it. You'll see it represented as three dots now. It will be respected when you save and reopen later or elsewhere. There is further features and options, such as `View` > `Collapse All Code`, see [here](https://discourse.jupyter.org/t/hiding-code-cell-on-launch/1763/2?u=fomightez) and [the link here](https://discourse.jupyter.org/t/hiding-code-cell-on-launch/1763/5?u=fomightez). – Wayne Feb 21 '20 at 17:10

13 Answers13

156

UPDATE:

The newer jupyter-lab is a more modern and feature-rich interface which supports cell folding by default. See @intsco's answer below

UPDATE 2

Since jupyter-lab now also supports extensions, you can extend the built-in cell-folding functionality with the Collapsible_Headings extension.

Original answer:

The jupyter contrib nbextensions Python package contains a code-folding extension that can be enabled within the notebook. Follow the link (Github) for documentation.

To install using command line:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user

To make life easier in managing them, I'd also recommend the jupyter nbextensions configurator package. This provides an extra tab in your Notebook interface from where you can easily (de)activate all installed extensions.

Installation:

pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user
Energya
  • 2,623
  • 2
  • 19
  • 24
  • 17
    Cool stuff, although I wish the "Codefolding" nbextension would fold entire cells, and not just code blocks. – bsmith89 Feb 06 '17 at 19:10
  • I am not able to get the extension tree as described in Github link – user2110239 Sep 19 '17 at 10:06
  • 2
    If anybody runs into installation issues with conda try: `pip install jupyter_contrib_nbextensions` then `jupyter contrib nbextensions install --sys-prefix --skip-running-check`. I wish jupyter would have this package by default. – user1700890 Oct 26 '17 at 17:44
  • 7
    Simplest installation path is [via conda itself](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/install.html#conda): `conda install -c conda-forge jupyter_contrib_nbextensions`. – Max Ghenis Mar 05 '18 at 01:45
  • Error: no such file or directory, when I attempt to run jupyter with it after I installed it. github docs said to add this to the jupyter command line: nbextension enable codefolding/main – Geoffrey Anderson Apr 30 '18 at 18:03
  • 3
    Just a quick note for anyone using the newer JupyterLab. According to the mentioned GitHub site, these extensions work in JupyterLab. I wondered this myself so I figured I'd let others know. Quoting the GitHub repo: `Due to major differences between the Jupyter Notebook and JupyterLab, the extensions in this repository will not work in JupyterLab`. – NYCeyes Nov 30 '18 at 19:14
  • Adding to @MaxGhenis comment: `conda install -c defaults -c conda-forge jupyter_contrib_nbextensions` avoids superseding already installed packages by conda-forge (e.g. ca-certificates would sometimes be superseded by older versions) – rvf Mar 06 '19 at 12:58
  • 8
    You CAN collapse an entire cell if you put a #comment at the top of the cell. Jupyter then provides a drop down arrow that will collapse the entire cell. – EatSleepCode Jun 13 '19 at 14:24
  • what jupyter version should we use to be able to hide the code? I have been switching between 6.X and 5.X because it doesn't show all the extension (hide code included) – Chris Nov 13 '19 at 22:13
  • 1
    To follow up on @NYCeyes comment relating to JupyterLab. The point about extensions for classic style notebooks not being compatible by default with JupyterLab is valid. However, I've now commented below the original question that the collapse functionality is built right in to JupyterLab since version 1.0 (released June 2019). Just highlight a cell and click the blue bar to collapse it. The state is respected when the notebook is reopened. – Wayne Feb 21 '20 at 17:25
  • 1
    @Chris I'm using the "Codefolding" extension in Jupyter Notebook 6.4.0 and it seems to work just fine. I installed `jupyter_contrib_nbextensions` and the configurator, and had to un-check `disable configuration for nbextensions without explicit compatibility` to select the Codefolding extension. I reopened my notebook after that. Then I was able to fold at top-comments as well as the usual blocks like loops. – MartyMacGyver Aug 05 '21 at 23:00
88

JupyterLab supports cell collapsing. Clicking on the blue cell bar on the left will fold the cell. enter image description here

intsco
  • 1,276
  • 12
  • 14
  • 12
    doesn't persist in exporting though – cosmosa Sep 04 '19 at 14:42
  • Is there a good solution for this? I so very badly want to hide collapsed cells when I export. I want to keep some code and some output, and hide some other code and output, so I can't just hide *all* code..... – Russell Richie Jan 10 '20 at 17:16
  • 3
    The code and output can be collapsed as described in this answer. Furthermore the information is persisted. It is written in the metadata of the cell. `source_hidden` and `outputs_hidden` is set. https://nbformat.readthedocs.io/en/latest/format_description.html#cell-metadata – gillesB Apr 09 '20 at 12:27
  • 1
    Beautiful - exactly what I was looking for. Wish the UI made this feature more obvious somehow. – flow2k Nov 24 '20 at 08:07
  • Does this extension enable grouping multiple cells (and subgroups) into a hierarchy, like Mathematica's front end? – alancalvitti Apr 06 '21 at 15:40
  • That is a preposterously & tediously inefficient way of collapsing a current or selected cell. ` to exit cell, reach for mouse, move pointer to blue bar, click blue bar, find now with the ruddy mouse where your focus needs to be, return focus there with mouse....` The apparent inadequacy of Jupyter Lab keyboard controls (please correct me if I am wrong, and you can in fact perform this operation with just a flick of a finger) is such that using it is like trying to sort a bucket of live eels with your bare hands. It really is a mystery that it's interface is so awful. – markling Apr 25 '23 at 12:48
34

You can create a cell and put the following code in it:

%%html
<style>
div.input {
    display:none;
}
</style>

Running this cell will hide all input cells. To show them back, you can use the menu to clear all outputs.

Otherwise you can try notebook extensions like below:

https://github.com/ipython-contrib/IPython-notebook-extensions/wiki/Home_3x

Pan Yan
  • 1,622
  • 1
  • 18
  • 21
  • The notebook extensions are really good. There are a bunch of other things too. https://github.com/ipython-contrib/jupyter_contrib_nbextensions – shahensha Jan 26 '17 at 18:32
26

I had a similar issue and the "nbextensions" pointed out by @Energya worked very well and effortlessly. The install instructions are straight forward (I tried with anaconda on Windows) for the notebook extensions and for their configurator.

That said, I would like to add that the following extensions should be of interest.

  • Hide Input | This extension allows hiding of an individual codecell in a notebook. This can be achieved by clicking on the toolbar button: Hide Input

  • Collapsible Headings | Allows notebook to have collapsible sections, separated by headings Collapsible Headings

  • Codefolding | This has been mentioned but I add it for completeness Codefolding

21

There are many answers to this question, all of which I feel are not satisfactory (some more than others), of the many extensions - code folding, folding by headings etc etc. None do what I want in simple and effective way. I am literally amazed that a solution has not been implemented (as it has for Jupyter Lab).

In fact, I was so dissatisfied that I have developed a very simple notebook extension that can expand/collapse the code in a notebook cell, while keeping it executable.

The GitHub repository: https://github.com/BenedictWilkins/cellfolding

Below is a small demo of what the extension does:

Simply double clicking left of the code cell will collapse it to a single line:

Double clicking again will expand the cell.

The extension can be installed easily with pip:

pip install nbextension-cellfolding
jupyter nbextension install --py cellfolding --user
jupyter nbextension enable --py cellfolding --user 

and is also compatible with nbextension configurator. I hope that people will find this useful!

BenedictWilkins
  • 1,173
  • 8
  • 25
13

Create custom.js file inside ~/.jupyter/custom/ with following contents:

$("<style type='text/css'> .cell.code_cell.collapse { max-height:30px; overflow:hidden;} </style>").appendTo("head");
$('.prompt.input_prompt').on('click', function(event) {
    console.log("CLICKED", arguments)   
    var c = $(event.target.closest('.cell.code_cell'))
    if(c.hasClass('collapse')) {
        c.removeClass('collapse');
    } else {
        c.addClass('collapse');
    }
});

After saving, restart the server and refresh the notebook. You can collapse any cell by clicking on the input label (In[]).

Sundar
  • 173
  • 1
  • 6
  • 4
    This did not work for me as the div to be changed is not loaded, when the custom js is executed. However, this can be fixed wrapping everything in setTimeout(function() {...}, 3000); – Steohan Dec 06 '16 at 12:20
  • 3
    This worked for me after changing the 4th line to: `var c = $(event.target).closest('.cell.code_cell')` and following Steohan's suggestion to wrap everything in setTimeout. – proteome Jul 14 '17 at 21:57
  • 1
    You can simply use c.toggleClass('collapse'); instead of the if-else statement. – gouravkr Dec 24 '19 at 09:32
11

The hide_code extension allows you to hide individual cells, and/or the prompts next to them. Install as

pip3 install hide_code

Visit https://github.com/kirbs-/hide_code/ for more info about this extension.

Linas
  • 773
  • 6
  • 13
9

Firstly, follow Energya's instruction:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user

Second is the key: After opening jupiter notebook, click the Nbextension tab. Now Search "colla" from the searching tool provided by Nbextension(not by the web browser), then you will find something called "Collapsible Headings"

This is what you want!

user40780
  • 1,828
  • 7
  • 29
  • 50
5

As others have mentioned, you can do this via nbextensions. I wanted to give the brief explanation of what I did, which was quick and easy:

To enable collabsible headings: In your terminal, enable/install Jupyter Notebook Extensions by first entering:

pip install jupyter_contrib_nbextensions

Then, enter:

jupyter contrib nbextension install

Re-open Jupyter Notebook. Go to "Edit" tab, and select "nbextensions config". Un-check box directly under title "Configurable nbextensions", then select "collapsible headings".

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Wondering why one cannot access `nbextensions config` directly from the main dashboard and has to open a notebook instead. Alternatively, as others have mentioned, one can access it via `localhost:8888/nbextensions` (or whichever port is in your configuration) – Antoine Mar 26 '20 at 11:05
  • Thanks! It's very helpful. I wonder how to proceed for jupyterlab though – Mez13 Oct 28 '20 at 15:19
3

There's also an improved version of Pan Yan suggestion. It adds the button that shows code cells back:

%%html
<style id=hide>div.input{display:none;}</style>
<button type="button" 
onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
Show inputs</button>

Or python:

# Run me to hide code cells

from IPython.core.display import display, HTML
display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))
  • 2
    The codes hides ALL input cell, not a particular cell. – Jack Fleeting Dec 16 '18 at 14:38
  • Just what I wanted for output, but you can collapse/hide all output by toggling it in the Jupyter menu : Cell > All Output > Toggle – markling Mar 14 '19 at 10:14
  • Shame, this is the only solution I found that hides the code by default and only shows it on click. Unfortunately, this hides all the cells and not just one target one. – penelope Feb 11 '20 at 14:53
  • @penelope you can check if different cells have different html elements IDs or unique classes. If yes then you can modify my answer accordingly. My answer affects all cells because it doesn't differentiate between cells. – Peter Zagubisalo Feb 11 '20 at 15:49
3

You don't need to do much except to enable the extensions:

http://localhost:8888/nbextensions?nbextension=collapsible_headings
http://localhost:8888/nbextensions?nbextension=codefolding/main

enter image description here

Most probable you will find all your extensions in here:

http://localhost:8888/nbextensions

enter image description here

prosti
  • 42,291
  • 14
  • 186
  • 151
2

What I use to get the desired outcome is:

  1. Save the below code block in a file named toggle_cell.py in the same directory as of your notebook
from IPython.core.display import display, HTML
toggle_code_str = '''
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Sloution"></form>
'''

toggle_code_prepare_str = '''
    <script>
    function code_toggle() {
        if ($('div.cell.code_cell.rendered.selected div.input').css('display')!='none'){
            $('div.cell.code_cell.rendered.selected div.input').hide();
        } else {
            $('div.cell.code_cell.rendered.selected div.input').show();
        }
    }
    </script>

'''

display(HTML(toggle_code_prepare_str + toggle_code_str))

def hide_sloution():
    display(HTML(toggle_code_str))
  1. Add the following in the first cell of your notebook
from toggle_cell import toggle_code as hide_sloution
  1. Any cell you need to add the toggle button to simply call hide_sloution()
0

I had the same problem, I found this extension useful

pip install aquirdturtle_collapsible_headings

enter image description here

Darkstar Dream
  • 1,649
  • 1
  • 12
  • 23