Created
June 10, 2017 13:29
-
-
Save mrnugget/c4fb36b017672eaf49a68c618f4a9a5a to your computer and use it in GitHub Desktop.
Reads a markdown file from STDIN and outputs the TOC to STDOUT. Install Racket to run it.
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 racket | |
#lang racket | |
(define (contains-heading? line) | |
(regexp-match #rx"^#+" line)) | |
(define (heading-level line) | |
(length (regexp-match* #rx"#" line))) | |
(define (heading-title line) | |
(string-trim (last (string-split line "#")))) | |
(define (make-heading line) | |
(cons (heading-title line) (heading-level line))) | |
(define (make-heading-padding heading) | |
(make-string (* 2 (sub1 (cdr heading))) #\space)) | |
(define (heading-link heading) | |
(let ((padding (make-heading-padding heading)) | |
(href (string-downcase (string-replace (car heading) " " "-")))) | |
(format "~a* [~a](#~a)" padding (car heading) href))) | |
(let* ((lines (sequence->list (in-lines (current-input-port)))) | |
(headings (map make-heading (filter contains-heading? lines)))) | |
(for ([toc-line (map heading-link headings)]) | |
(printf "~a\n" toc-line))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment