Skip to content

Instantly share code, notes, and snippets.

@mgechev
Last active May 9, 2018 18:30
Show Gist options
  • Save mgechev/7aa4bbaf050a178f313b4a653d6fdb27 to your computer and use it in GitHub Desktop.
Save mgechev/7aa4bbaf050a178f313b4a653d6fdb27 to your computer and use it in GitHub Desktop.
const { readFileSync, writeFileSync } = require('fs');
const re = /\[.*?\](\(.*?\))/g
const addFootnotes = (path, output, ignoreRegExps = []) => {
let text = readFileSync(path).toString();
let match;
let current = 1;
const matches = [];
const links = {};
while (match = re.exec(text)) {
const link = match[1].substring(1, match[1].length - 1);
if (ignoreRegExps.reduce((a, c) => a || c.test(link), false)) {
continue;
}
if (links[link] === undefined) {
links[link] = current++;
}
matches.push({ start: match.index, str: match[0], idx: current - 1 });
}
let linksList = [];
Object.keys(links).forEach(l => linksList[links[l] - 1] = l);
const notes = linksList.map((l, idx) => `${idx + 1}. [###] ${l}`).join('\n');
for (let i = matches.length - 1; i >= 0; i--) {
const c = matches[i];
text = text.substr(0, c.start + c.str.length) + '<sup>' + c.idx + '</sup>' + text.substr(c.start + c.str.length, text.length)
}
const result = text + '\n\n' + notes + '\n';
return writeFileSync(output, result);
};
module.exports.addFootnotes = addFootnotes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment