Created
August 6, 2021 17:13
-
-
Save rauschma/bf805d71b37bbdd8cbe2999bcea3ca29 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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