This repository has been archived on 2021-07-14. You can view files and clone it, but cannot push or open issues or pull requests.
scriptcraft/src/docs/js/generateTOC.js
2014-01-25 09:04:16 +00:00

50 lines
1.4 KiB
JavaScript

args = Array.prototype.slice.call(args,1);
// wph 20140105 trim not availabe in String on Mac OS.
if (typeof String.prototype.trim == 'undefined'){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,'');
};
}
var template = args[0];
var BufferedReader = java.io.BufferedReader;
var FileReader = java.io.FileReader;
var contents = [], line = undefined;
var br = new BufferedReader( new FileReader(template) );
while ( (line = br.readLine()) != null){
contents.push(line);
}
br.close();
var anchors = {};
var createLink = function(text){
var result = text.replace(/_/g,'_');
result = result.replace(/[^a-zA-Z0-9 _\-]/g,'');
result = result.replace(/ /g,'-');
var result = result.toLowerCase();
if (anchors[result]){
result = result + '-' + (anchors[result]++);
}
anchors[result] = 1;
return result;
};
java.lang.System.out.println('## Table of Contents');
for (var i = 0; i < contents.length; i++){
line = contents[i];
if (line.match(/^##\s+/)){
var h2 = line.match(/^##\s+(.*)/)[1].trim();
var link = createLink(h2);
java.lang.System.out.println (' * [' + h2 + '](#' + link + ')');
}
if (line.match(/^###\s+/)){
var h3 = line.match(/^###\s+(.*)/)[1].trim();
var link = createLink(h3);
java.lang.System.out.println (' * [' + h3 + '](#' + link + ')');
}
}