Skip to content

Fix invalid TOC HTML when a header is above the first header's level - #754

Open
Enesuygurs wants to merge 2 commits into
trentm:masterfrom
Enesuygurs:fix/toc-shallower-header-nesting
Open

Enesuygurs wants to merge 2 commits into
trentm:masterfrom
Enesuygurs:fix/toc-shallower-header-nesting

Conversation

@Enesuygurs

Copy link
Copy Markdown

With the toc extra, a document whose first header isn't its highest-level one produces broken TOC HTML. For example, ## Overview, # Getting Started, ## Install gives:

<ul>
  <li><a href="#overview">Overview</a></li>
</ul></li>
<li><a href="#getting-started">Getting Started</a>
<ul>
  <li><a href="#install">Install</a></li>
</ul>

The outer list closes straight away, a stray </li> is left behind, and everything after it ends up outside any list.

A related problem shows up when a level is skipped and the document later returns to it. # A, ### B, ## C, ## D puts C next to A at the top level and nests D under C, although both are h2s under A.

calculate_toc_html compared the new header with the current list's level instead of its parent's, and it could close the outermost list. It now closes a nested list only when the header belongs at or above the parent's level; otherwise the header stays in the current list. The outermost list is never closed early, so a header above the first one's level becomes another top-level entry. Properly nested documents give the same output as before, and unlike #337 this doesn't add extra nested lists for skipped levels.

The nesting now matches Python-Markdown's toc extension: I compared 20,000 random header sequences against its toc_tokens, and all of them match and are well-formed.

I added the toc_shallower_headers test case, which fails on master. make testone and make testredos pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant