Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate GitHub wiki table of contents
/**
* This script generates a Markdown table of contents for a GitHub wiki page.
* The end result is a block like this:
*
* ## Contents
* * [Header](#header)
* * [Subheader](#subheader)
* * [Sub-subheader](#sub-subheader)
* * [Sub-subheader 2](#sub-subheader-2)
* * [Header 2](#header-2)
*
*/
// find article headers
var headers = $('#wiki-body, .preview-content').find('h1, h2, h3, h4, h5');
var isPreview = !!$('.preview-content').length;
// find top header level (e.g., 2 if there are <h2> but no <h1> headers)
var minLevel = Math.min.apply(Math, headers.map(function() { return this.tagName.match(/\d/)[0]; }));
// build table of contents
var toc = '## Contents\n';
headers.map(function() {
var header = $(this);
var text = $.trim(header.text());
var anchor = header.find('a:first').attr('id');
if(isPreview)
anchor = anchor.replace(/^user-content-/, '');
var level = this.tagName.match(/\d/)[0] - minLevel + 1;
for(var i = 1; i < level; i++)
toc += ' ';
toc += '* [' + text + '](#' + anchor + ')\n';
});
console.log(toc);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment