Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Table of Contents #334

Closed
jbenet opened this issue Jan 17, 2014 · 7 comments
Closed

Table of Contents #334

jbenet opened this issue Jan 17, 2014 · 7 comments

Comments

@jbenet
Copy link

jbenet commented Jan 17, 2014

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>
@killercup
Copy link

I'm currently writing something like that for a project using a custom renderer that automatically populates an array of headlines (cf. Readme).

@SimonCropp
Copy link

@killercup can u share some more specific code?

@killercup
Copy link

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.

@SimonCropp
Copy link

@killercup you rock

@jonschlinkert
Copy link

@alanhogan
Copy link

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)

@joshbruce
Copy link
Member

Not sure this is in keeping with the specifications being targeted.

See #956

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

No branches or pull requests

6 participants