Table of Contents (2)¶
The toc2 extension enables to collect all running headers and display them in a floating window, as a sidebar or with a navigation menu. The extension is also draggable, resizable, collapsable, dockable and features automatic numerotation with unique links ids, and an optional toc cell. Sections of currently selected/edited or running cells are highlighted in the toc. Some minor diplay tweaks are also available (moving header tile/menus, widening cells); Finally, the toc can preserved when exporting to html.
First demo: Floating toc window and SideBar, toc auto-update, section numbering¶
Second demo: Save as html with toc / Navigation menu¶
Third demo: Notebook scrolling and Collapsing sections¶
The table of contents is automatically updated when modifications occur in the notebook. The toc window can be moved and resized. It can be docked as a sidebar or dragged from the sidebar into a floating window. The table of contents can be collapsed or the window can be completely hidden. The navigation menu can be enabled/disabled via the nbextensions configuration utility. It can also be resized. The position, dimensions, and states (that is ‘collapsed’ and ‘hidden’ states) are remembered (actually stored in the notebook’s metadata) and restored on the next session.
There is a configurable option to skip h1 headers from the ToC, to allow their use as a notebook title. However, this cause issues in latex exports, where h1 are converted to sections. Alternatively, headers of any level can be omitted from being the toc by adding an html tag with the css class tocSkip at the end of the header line; e.g. as in
## title The toc window also provides two links in its header for further functionalities:
- the “n” link toggles automatic numerotation of all header lines
- the “t” link toggles a toc cell in the notebook, which contains the actual table of contents, possibly with the numerotation of the different sections. The position of the toc cell in the notebook can be configured by creating a cell with metadata (View > Cell Toolbar > Edit Metadata): < “toc”: 1 >, this cell will then be replaced by the table of contents.
The state of these two toggles is memorized and restored on reload.
Configuration¶
The initial configuration can be set using the jupyter_nbextensions_configurator facility, included with jupyter_contrib_nbextnensions. Configurable options include:
- Display Table of Contents as a sidebar (otherwise as a floating window; default: true)
- Title of the sidebar/window (default: Contents )
- The maximum depth of headers to display on toc (with a default of 4)
- The state of the toc cell (default: false, ie not present)
- Title of the toc cell sidebar/window (default: Table of Contents )
- Add a navigation menu (default: true)
- Widening the display area to fit the browser window (may be useful with sidebar option; default: true)
- The numbering of headers (true by default)
- Moving header title and menus on the left (default: true)
- Marking toc item of first header displayed on viewport when scrolling the notebook (default: true)
- Skipping h1 headers, useful if you want to use h1 as unnumbered notebook title (default: false)
- Customization of highlighting the title of currently selected/running sections.
- Customization of background, fonts, border and highlighting colors in the toc window and navigation menus (as third demo).
- Collapse/uncollapse ToC2 sections when collapsible_headings is used to collapse/uncollapse notebook sections (default: false).
Some config settings are stored in notebook metadata, so that they can be altered per-notebook, as well as setting the default in the configurator. The differents states and position of the floating window have reasonable defaults and can be modfied per notebook.
Demo with dark theme¶
Export¶
It is possible to export (most of) table of contents functionalities to html. The idea is to link a relevant part of the javascript extension and the css, and add a small script in the html file. This is done using a template by
jupyter nbconvert FILE.ipynb --template toc
jupyter nbconvert FILE.ipynb --template toc2
An exporter is also available. It is now possible to export to html with toc by
jupyter nbconvert --to html_toc FILE.ipynb
If you also use latex_envs, you can embed both functionalities while exporting with
jupyter nbconvert --to html_with_toclenvs FILE.ipynb
For the first template (toc), the files toc2.js and main.css (originally located in /jupyter_contrib_nbextensions/nbextensions/toc2 ) must reside in the same directory as intended for the html file. In the second template, these files are linked to the ipython-contrib/jupyter_contrib_nbextensions github website. Export configuration (parameters) shall be edited directly in the template files (in templates directory /jupyter_contrib_nbextensions/templates ). An option “Save as HTML (with toc)” is also provided in the File menu and enables the direct conversion of the actual notebook. This option requires the IPython kernel and is not present with other kernels.
Testing¶
- At loading of the notebook, configuration and initial rendering of the table of contents were fired on the event “notebook_loaded.Notebook”. It happens that the extension is sometimes loaded after this event. I now rely on a direct rendering at load and on a combination of “notebook_loaded.Notebook” and “kernel_ready.Kernel”.
- This extension also includes a quick workaround as described in #429
History¶
- This extension was adapted by minrk in minrk/ipython_extensions from gist.github.com/magican/5574556
- Added to the ipython-contrib/jupyter_contrib_nbextensions repo by @JanSchulz
- @juhasch, automatic update on markdown rendering,
- @JanSchulz, enable maths in headers links
- @jfbercher december 06, 2015 – Big update: automatic numbering, toc cell, window dragging, configuration parameters
- @jfbercher december 24, 2015 – nested numbering in toc-window, following the fix by @paulovn in @minrk’s repo. December 30-31, updated config in toc2.yaml to enable choosing the initial visible state of toc_window via a checkbox ; and now resizable.
- @slonik-az february 13, 2016. Rewritten toc numberings (more robust version), fixed problems with skipped heading levels, some code cleanup
- @jfbercher february 21, 2016. Fixed some issues when resizing the toc window. Now avoid overflows, clip the text and add a scrollbar.
- @jfbercher february 22, 2016. Add current toc number to headings anchors. This enable to get unique anchors for recurring headings with the same text. An anchor with the original ID is still created and can be used (but toc uses the new ones!). It is also possible to directly add an html anchor within the heading text. This is taken into account when building toc links (see comments in code).
- @jfbercher april 29, 2016. Triggered by @cqcn1991, cf discussion here, add a sidebar option. The floating toc window can be dragged and docked as a left sidebar. The sidebar can be dragged out as a floating window. These different states are stored and restored when reloading the notebook. Add html export capability via templates toc.tpl and toc2.tpl (see above).
- @jfbercher may 04, 2016. Added a “Save as HTML with toc” menu. Added a new “Navigate” menu with presents the contents of the toc. Changed default styling for links in tocs.
- @jfbercher july 28, 2016. A dedicated exporter was added. It is now possible to export to html with toc by jupyter nbconvert —to html_toc FILE.ipynb
- @jfbercher september 21, 2016. Fixed empty size of navigation menu (if no resize had occur). Changed system/notebook configuration parameters storing, loading and merging.
- @jfbercher november 16, 2016.
- Fixed saving issue due to a race condition in loading/writing metadata; see issues #1882 and #762
- As suggested by @dinya in #791, added highlighting of the section that contains the currently edited/selected/executing cell. Colors can be customized by changing .toc-item-highlight-select and .toc-item-highlight-execute classes in css. -[update nov 23]. As suggested by @jcb91, the highlight colors can now be configured via the nbextensions–configurator, instead of changing the css.
- Threshold (number of headings levels in toc)taken globally as requested in #646 (if it exists, otherwise default)
- Make toc2 template inherits from nbextensions template, as mentioned in #847
- On header/menu/toolbar resize (resize-header.Page event), resize toc2 sidebar
- On ‘toggle-all-headers’ event from hide_menubar extension, resize toc2 sidebar
- Remove MathJax preview in headers and links – addresses (issue 14 in latex_envs)[https://github.com/jfbercher/jupyter_latex_envs/issues/14]
- Added a parameter to enable/disable cell widening (which is useful when sideBar is on) — default is to widen — address #871
- Updated README to please @KadeG in #871
- Support customization of background, fonts, border and highlighting colors in the toc window and navigation menus with PR #969
- correct toc tree construction
- simplify toc cell processing
- constrain draggable toc to the body
- various bits of cleanup
- add settings dialog for per-notebook metadata-stored settings
© Copyright 2015-2018, Jupyter Contrib Team. Revision 03109e43 .
Built with Sphinx using a theme provided by Read the Docs.
Read the Docs v: latestVersions latest stable Downloads On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.
How to Add a Table of Contents in the Jupyter Notebook
When dealing with large amounts of data, the several steps can mix. Even a simple project might become immensely confusing to an outside observer without the proper comments and explanation. Consider yourself a manager who is watching an endless line of code, statistics, and variables being assigned in complete anonymity.
It is essential to build a framework that is simple for the new readers to understand in order to avoid this situation. A table of contents is a very helpful approach to illustrate the procedure and can even aid in developing an initial strategy.
In this article, we will demonstrate how to create a table of contents using a Jupyter notebook.
How to Add a Table of Contents in a Jupyter Notebook
No matter how big or little the project is, adding a table of contents makes it clear with what path the project will take. The only tools required to include a table of contents in a Jupyter notebook are the “anchor tags” in the appropriate places. The links that point to the other sections of the notebook’s table of content are translated into such links.
Creating a table of content in a Jupyter notebook is quite easy and simple. You can complete it in the following number of steps:
Step 1: Select the Markdown Format
We can add the table of content in the Jupyter notebook using the HTML anchor. This is a simple two-step process. Open the Jupyter notebook and select the markdown cell format instead of the code.Step 2: Create the Structure of the Table of Content
First, create a table of contents using the markdown in the notebook. Here, we also need to link the anchors that we will create in the next step. Use the following text and paste it into the markdown cell:## Table of Contents
* [Chapter 1](#chapter1)
* [Section 1.1](#section_1_1)
* [Sub Section 1.1.1](#sub_section_1_1_1)
* [Chapter 2](#chapter2)
* [Section 2.1](#section_2_1)
* [Sub Section 2.1.1](#sub_section_2_1_1)
* [Sub Section 2.1.2](#sub_section_2_1_2)
* [Section 2.2](#section_2_2)
* [Sub Section 2.2.1](#sub_section_2_2_1)
* [Sub Section 2.2.2](#sub_section_2_2_2)
* [Chapter 3](#chapter3)
* [Section 3.1](#section_3_1)
* [Sub Section 3.1.1](#sub_section_3_1_1)
* [Sub Section 3.1.2](#sub_section_3_1_2)
* [Section 3.2](#section_3_2)
* [Sub Section 3.2.1](#sub_section_3_2_1)
* [Sub Section 3.2.2](#sub_section_3_2_2)Press “Shift + Enter” to run the previous lines in the Jupyter notebook. The table of content should display like this:
The structure of the table of content follows the markdown format available in the Jupyter notebook. In the previous screenshot, the displayed name of the link is enclosed in brackets [] and the reference to the anchor tags is placed in parenthesis preceded by a hash (#) symbol.
The markdown cell in the anchor tag is included in either a title to go with the operation or a description of the current processes.
Step 3: Create Anchor Tags
Now, we will create the anchor tags in order to link with the table of contents. Create the chapters, sections, and subsections. Enter the following text in the next markdown cell:Press “Shift + Enter” or run this cell to see the effects. The following output should display on your notebook:
Here, you will notice that you can easily navigate to the desired section from the table of content.
Conclusion
We demonstrated in this article how to create a table of content in a Jupyter notebook. Using a table of content, you can easily manage all the content and can easily navigate to the desired section of your document. We can also add a table of content in a Jupyter notebook using the pre-build extensions. I hope this article increases your understanding about the Jupyter notebook.
About the author
Samreena Aslam
Samreena Aslam holds a master’s degree in Software Engineering. Currently, she’s working as a Freelancer & Technical writer. She’s a Linux enthusiast and has written various articles on Computer programming, different Linux flavors including Ubuntu, Debian, CentOS, and Mint.
How can I add a table of contents to a Jupyter / JupyterLab notebook?
You can provide a conceptual structure for your computational document as a whole using different levels of headings; there are 6 levels available, from level 1 (top level) down to level 6 (paragraph). These can be used later for constructing tables of contents, etc.
However, I can’t find instructions anywhere on how to use my hierarchical headings to create such a table of contents. Is there a way to do this? NB: I’d also be interested in other kinds of navigation using ipython notebook headings, if any exist. For instance, jumping back and forward from heading to heading in order to quickly find the start of each section, or hiding (folding) the contents of an entire section. This is my wish-list — but any kind of navigation at all would be of interest. Thanks!
44.1k 17 17 gold badges 154 154 silver badges 162 162 bronze badges
asked Jan 16, 2014 at 0:54
user2428107 user2428107
3,033 3 3 gold badges 18 18 silver badges 20 20 bronze badgessee @Nikolay ‘s answer below for a general solution that works across all webpages.. this is a great answer.
Jun 21, 2017 at 7:19
To complement the existing Jupyter notebook solutions, I added JupyterLab instructions below.
Dec 11, 2019 at 12:5111 Answers 11
You can add a TOC manually with Markdown and HTML. Here’s how I have been adding:
Create TOC at top of Jupyter Notebook:
## TOC: * [First Bullet Header](#first-bullet) * [Second Bullet Header](#second-bullet)
Add html anchors throughout body:
## First Bullet Header
It may not be the best approach, but it works.
23.1k 9 9 gold badges 50 50 silver badges 319 319 bronze badges
answered Oct 2, 2016 at 12:56
Matt Dancho Matt Dancho
6,938 3 3 gold badges 35 35 silver badges 26 26 bronze badges
This does not work for me anymore, but a similar approach does.
May 24, 2017 at 2:27also same "similar approach" as this: stackoverflow.com/questions/5319754/… tl;dr: use for anchor and for link use: Take me to [pookie](#pookie)
May 24, 2017 at 19:12
For all headings in your markdowns, notebook automatically adds anchors. You can click on the pilcrow (¶) on the right of the headings that you see when you hover over them, to reveal the anchor in your browser address bar. You can use this anchor instead of adding anchors manually to sections of your markdown. Also the best thing is that it works across cells.
Apr 11, 2020 at 15:21
I have this script add_toc.py that adds a markdown cell at the top with a list of contents. A poor man's solution if you don't want to install extensions.
May 1, 2020 at 15:47
JupyterLab ToC instructions
There are already many good answers to this question, but they often require tweaks to work properly with notebooks in JupyterLab. I wrote this answer to detail the possible ways of including a ToC in a notebook while working in and exporting from JupyterLab.
As a side panel
The jupyterlab-toc extension adds the ToC as a side panel that can number headings, collapse sections, and be used for navigation (see gif below for a demo). This extension is included by default since JupyterLab 3.0, in older version you can install it with the following command
jupyter labextension install @jupyterlab/toc
In the notebook as a cell
At the time being, this can either be done manually as in Matt Dancho's answer, or automatically via the toc2 jupyter notebook extension in the classic notebook interface.
conda install -c conda-forge jupyter_contrib_nbextensions
Then, launch JupyterLab, go to Help --> Launch Classic Notebook , and open the notebook in which you want to add the ToC. Click the toc2 symbol in the toolbar to bring up the floating ToC window (see the gif below if you can't find it), click the gear icon and check the box for "Add notebook ToC cell". Save the notebook and the ToC cell will be there when you open it in JupyterLab. The inserted cell is a markdown cell with html in it, it will not update automatically.
The default options of the toc2 can be configured in the "Nbextensions" tab in the classic notebook launch page. You can e.g. choose to number headings and to anchor the ToC as a side bar (which I personally think looks cleaner).
In an exported HTML file
nbconvert can be used to export notebooks to HTML following rules of how to format the exported HTML. The toc2 extension mentioned above adds an export format called html_toc , which can be used directly with nbconvert from the command line (after the toc2 extension has been installed):
jupyter nbconvert file.ipynb --to html_toc # Append `--ExtractOutputPreprocessor.enabled=False` # to get a single html file instead of a separate directory for images
Remember that shell commands can be added to notebook cells by prefacing them with an exclamation mark ! , so you can stick this line in the last cell of the notebook and always have an HTML file with a ToC generated when you hit "Run all cells" (or whatever output you desire from nbconvert ). This way, you could use jupyterlab-toc to navigate the notebook while you are working, and still get ToCs in the exported output without having to resort to using the classic notebook interface (for the purists among us).
Note that configuring the default toc2 options as described above, will not change the format of nbconver --to html_toc . You need to open the notebook in the classic notebook interface for the metadata to be written to the .ipynb file (nbconvert reads the metadata when exporting) Alternatively, you can add the metadata manually via the Notebook tools tab of the JupyterLab sidebar, e.g. something like:
If you prefer a GUI-driven approach, you should be able to open the classic notebook and click File --> Save as HTML (with ToC) (although note that this menu item was not available for me).
The gifs above are linked from the respective documentation of the extensions.
Installing Table of Contents extension to Jupyter notebook
Table of contents 2 is a very useful extension to Jupyter notebook that allows you to have a nested outline with links to all the Markdown headings in a Jupyter notebook. This is basically essential when you’re working with a notebook of any real length. I don’t know why it isn’t just a standard feature in Jupyter.
Figuring out how to install it is a bit annoying as instructions are poorly written across several Github repos, but the process is actually very simple (if a little hacky). Assuming you followed my instructions on setting up a virtual environment in Python 3, activate it with (substitute your own path if needed):
source .virtualenvs/jupyter/
Now install jupyter_contrib_nbextensions. This bundles a bunch of extensions to Jupyter, as well as a configuration panel that will be added to the Jupyter interface.
pip install jupyter_contrib_nbextensions
This command is needed to complete the installation of the extensions to Jupyter itself:
jupyter contrib nbextension install --user
Now on the main Jupyter page, click the tab “Nbextensions”, then check the box for “Table of contents (2)”.
Now when you start a notebook, click the “Table of Contents” button, and you’ll get a sidebar on the left with your table of contents. Voila!