Would be nice to generate a table of contents from a markdown file, like http://pythonhosted.org/Markdown/extensions/toc.html
something like:
> cat foo.md
#1
## 1 1
### 1 1 1
## 1 2
## 1 3
### 1 3 1
> marked --toc foo.md
<ul>
<li><a href="#1">1</a>
<ul>
<li><a href="#1-1">1 1</a>
<ul>
<li><a href="#1-1-1">1 1 1</a></li>
<ul>
</li>
<li><a href="#1-2">1 2</a></li>
<li><a href="#1-3">1 3</a>
<ul>
<li><a href="#1-3-1">1 3 1</a></li>
<ul>
<li>
</ul>
</li>
</ul>
I'm currently writing something like that for a project using a custom renderer that automatically populates an array of headlines (cf. Readme).
@killercup can u share some more specific code?
Sure.
var marked = require('marked');
var renderer = new marked.Renderer();
var toc = []; // your table of contents as a list.
renderer.heading = function(text, level) {
var slug = text.toLowerCase().replace(/[^\w]+/g, '-');
toc.push({
level: level,
slug: slug,
title: text
});
return "<h" + level + " id=\"" + slug + "\"><a href=\"#" + slug + "\" class=\"anchor\"></a>" + text + "</h" + level + ">";
};
var convertMarkdown = function(text) {
return marked(text, {
renderer: renderer
});
};
For a complete implementation see here. This populates the toc array with headline objects. If you want to transform this flat list into a tree, you could use a function like the one found here called tocToTree.
@killercup you rock
Note that some Markdown implementations/variants support this. Python-markdown comes to mind:
https://pythonhosted.org/Markdown/extensions/toc.html
However, it’s not common or standardized (sadly, there is basically no such thing as a Markdown standard).
Here’s a bunch of implementations ignoring [TOC] on Babelmark 2
(also… +1)
Not sure this is in keeping with the specifications being targeted.
See #956
Most helpful comment
Sure.
For a complete implementation see here. This populates the
tocarray with headline objects. If you want to transform this flat list into a tree, you could use a function like the one found here calledtocToTree.