Skip to content

Instantly share code, notes, and snippets.

@Pathoschild
Created October 2, 2015 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pathoschild/5794cccd1671c2566b43 to your computer and use it in GitHub Desktop.
Save Pathoschild/5794cccd1671c2566b43 to your computer and use it in GitHub Desktop.
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