Skip to content

Instantly share code, notes, and snippets.

@rauschma
Created August 6, 2021 17:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauschma/bf805d71b37bbdd8cbe2999bcea3ca29 to your computer and use it in GitHub Desktop.
Save rauschma/bf805d71b37bbdd8cbe2999bcea3ca29 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
// Usage:
// cat my-file.md | ./gist-toc.mjs
// pbpaste | ./gist-toc.mjs | pbcopy # clipboard -> clipboard (macOS)
function createSlug(str) {
str = str.replace(/[?%:`]/g, '');
str = str.replace(/ +/g, '-');
return str.toLowerCase();
}
function createToc(text) {
let lines = text.trim().split(/\r?\n/);
lines = lines.filter(line => line.startsWith('##'));
lines = lines.map((line) => {
const match = /^(?<prefix>#{2,})\s+(?<title>.*)$/.exec(line);
if (match && match.groups) {
const {prefix, title} = match.groups;
const indent = ' '.repeat(prefix.length-2);
return indent + `* [${title}](#${createSlug(title)})`;
} else {
return 'ERROR: ' + line;
}
});
return lines.join('\n') + '\n';
}
async function main() {
let text = '';
for await (const chunk of process.stdin) {
text += chunk.toString('utf-8');
}
const toc = createToc(text);
text = text.replace('[[toc]]\n', toc);
console.log(text);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment