TOC (Table Of Content) Generator


#1

Would it be possible to have a Table Of Content Generator?

The idea is just to have the possibility to insert the generated listing of all the headers in a nested list:

  • H1
    • H2
    • H2
  • H1
    • H2
      • h3

Of course, some ameliorations from here are easy to find (e.g.: the possibility to limit the levels reported ; the insertion of hyperlinks in the TOC ; etc. …) but this would already be fine.

Thanks!


#2

A really good way to get fine control over printing style, and automatically generate a hyperlinked TOC in a variety of formats, is to experiment with Brett Terpstra’s Marked, which is an excellent adjunct to FoldingText.

See Marked 2 > Preferences > Printing > Printing table of contents


#3

@nmc if your end goal is a nice published looking TOC I think @complexpoint is right in suggesting Marked. But with that said it’s pretty easy to generate the list you are describing using FoldingText and AppleScript. Try this:

tell application "FoldingText"
  tell front document
    evaluate script "function(editor, options) {
      var tree = editor.tree(),
        headings = tree.evaluateNodePath('//heading'),
        toc = [];
      
      headings.forEach(function(each) {
        var level = each.typeIndentLevel(),
          text = '- ' + each.text();
          
        while (level > 1) {
          text = '  ' + text;
          level--;
        }
        
        toc.push(text);
      });
      
      toc = toc.join('\\n');
      
      require('ft/system/pasteboard').Pasteboard.writeString(toc);
      
      return toc;
    }" with options {}
  end tell
end tell

It returns a markdown list of the table of contents and also copies that list to the pasteboard.


#4

Thanks for your answers.

@complexpoint:

Yes, I use Marked 2, and thought about this option when writing here. I can have FT and Marked 2 open aside, but in this case I lose one of the advantages of FT which is his minimalism.

@jessegrosjean:

Thanks for the script, I will test it tonight.


#5

Understood – and if you want hyperlinks from TOC to headers in the final output (using MMD and ‘Generate IDs on headlines’ in Marked)

You could just add [...][] to Jesse’s code

function(editor, options) {
    var tree = editor.tree(),
        headings = tree.evaluateNodePath('//heading'),
        toc = [];

    headings.forEach(function(each) {
        var level = each.typeIndentLevel();

        toc.push(Array(level).join('\\t') + '- [' + each.text() + '][]');
    });

    toc = toc.join('\\n');

    require('ft/system/pasteboard').Pasteboard.writeString(toc);

    return toc;
}

#6

Thanks a lot, I’m really impressed: it goes much further than what I could hope!

Both scripts work perfectly, their only limit is they need a Header 1 (but it’s not a problem).

Thanks again!