Skip to content

Instantly share code, notes, and snippets.

@killwing
Created December 29, 2011 11:24
Show Gist options
  • Save killwing/1533617 to your computer and use it in GitHub Desktop.
Save killwing/1533617 to your computer and use it in GitHub Desktop.
[mdcontentgen] generate content list for markdown
#!/usr/local/bin/node
var fs = require('fs');
var file = process.argv[2];
if (!file) throw 'no input file';
var seq = false;
if (file == '-s') {
if (!process.argv[3]) throw 'no input file';
seq = true;
file = process.argv[3];
}
fs.readFile(file, 'utf8', function(err, buffer) {
if (err) throw err;
var lines = buffer.split('\n');
var content = ['# Content'];
var lv1No = 0;
var lv2No = 0;
var lv3No = 0;
for (i in lines) {
var title = /^(#+)\s+(<span id=".+">\s+)?([\d\.]+\s+)?(.+)/.exec(lines[i]);
if (title) {
var lv = title[1].length;
var words = title[4].trim().split(' ');
var id = words.join('-');
var seqno = '';
if (seq) {
if (lv == 1) {
++lv1No;
seqno = lv1No.toString();
lv2No = 0;
lv3No = 0;
} else if (lv == 2) {
++lv2No;
seqno = lv1No.toString() + '.' + lv2No.toString();
lv3No = 0;
} else if (lv == 3) {
++lv3No;
seqno = lv1No.toString() + '.' + lv2No.toString() + '.' + lv3No.toString();
}
seqno += ' ';
}
if (!title[2] || seq) { // not has archor or need add seq
lines[i] = title[1] + ' <span id="' + id + '"> ' + seqno + title[4];
}
var indent = '';
while (--lv) {
indent += '\t';
}
content.push(indent + '* [' + seqno + title[4] + '](#' + id + ')');
}
}
content.push('\n');
var all = content.concat(lines).join('\n');
fs.writeFile('New.'+file, all, function (err) {
if (err) throw err;
console.log('done!');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment