Making Multi-Level Anchors Work With globalindex.py for Sphinx

One of the issues I’ve come across when using Sphinx (awesome application) for writing documentation is that the table of contents disappear when using the singlefile format (which generates the documentation as one large page instead of having to click through to other files).

Luckily Matteo Franchin had the same issue, and created a small extension for Sphinx that allows you to add a TOC to SingleHTML builders as well! The problem I discovered after a while is that it ends up adding redundante HTML anchors for each level when resolving the TOC, where it ends up generating #html#anchors like that. Which doesn’t work.

I solved the issue (.. for my simple case, this is still a hack) by adding regular expression that removes any HTML anchors that are followed by another HTML-anchor (and could very possibly eat a lot more in edge cases, but hey, it works for me!).

rendered_toctree = re.sub(r'(#[^ "]+)#', '#', rendered_toctree);

The lines around line 59 should then look like:

            rendered_toctree = builder._get_local_toctree(docname, **kwargs)
            rendered_toctree = re.sub(r'(#[^ "]+)#', '#', rendered_toctree);
            node['content'] = rendered_toctree