Skip to content

Instantly share code, notes, and snippets.

@apainintheneck
Created September 10, 2022 19:11
Show Gist options
  • Save apainintheneck/bb382634b99b1032ec06697b9ca4d49a to your computer and use it in GitHub Desktop.
Save apainintheneck/bb382634b99b1032ec06697b9ca4d49a to your computer and use it in GitHub Desktop.
A small program that generates a table of contents for a markdown file.
#!/usr/bin/env awk -f
# A program that produces a table of contents from a markdown file.
# It assumes that the start title depth is 2 (## or h2) but that can
# be modified by passing in the START variable.
#
# Ex. cat readme.md | ./tocgen.awk
# Ex. cat readme.md | ./tocgen.awk -v START=1
BEGIN {
if(!START) START = 2
else {
if(START < 1 || START > 4) {
print "Error: START must be between 1-4 inclusive"
exit(1)
}
}
print "## Table of Contents"
}
$1 ~ /^#+$/ && NF > 1 {
if(length($1) < START) next
if(length($1) >= START + 3) next
title = parse_title()
path = to_url_path(title)
print_indent()
printf("- [%s](#%s)\n", title, path)
}
function to_url_path(title, local_path) {
local_path = tolower(title)
gsub(/[^A-Za-z _-]/, "", local_path)
gsub(/[ ]/, "-", local_path)
return local_path
}
function parse_title( local_title) {
local_title = substr($0, 2 + length($1))
local_title = strip(local_title)
return local_title
}
function print_indent() {
for(i = length($1); i > START; --i)
printf("%s", " ")
}
function strip(str, local_str) {
local_str = str
gsub(/^[ ]+|[ ]+$/, "", local_str)
return local_str
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment