markdownpython-sphinxtoctreecommonmark

Sphinx adds Headings from Markdown File to Document Structure


I have configured Sphinx to use markdown files.

In my index.rst file I have

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   documents/Markdown

In Markdown.md I have

# Markdown

## H2 Heading

When I render the main page I get the H2 heading appearing in the toctree.

enter image description here

I have other parts of my toctree where I want a :maxdepth of more than 1. Why does sphinx read the H2 heading as part of the toctree, and how can I get it to stop doing this, without having to set the the :maxdepth to 1?


Solution

  • @mzjn answers partially your request. Personally, I am not sure how is this exactly done in Markdown but I assume it is similar to reStructuredText. Unfortunately, at the moment there isn't an intuitive way to do this. However, you can do the following:

    .. toctree::
       :maxdepth: 1
    
       documents/Markdown1
    
    .. toctree::
       :maxdepth: 2
    
       documents/Markdown2
    

    This will output the desired behaviour but you will have some vertical spacing between your two trees in this case. Either you do that or you can use:

    .. toctree::
       :maxdepth: 2
    
       documents/Markdown1
       documents/Markdown2
    

    But you will need to transfer what you don't want to be shown to a lower level (H3 for example).