-
Notifications
You must be signed in to change notification settings - Fork 0
/
md2toc
68 lines (58 loc) · 1.58 KB
/
md2toc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/perl -w
# Create linked table of contents from a Markdown file.
# Then include the output inside the original <FILE.md>
use strict;
use warnings;
use Getopt::Std;
package Markdown::Contents;
our $VERSION = '1.3';
my %opts = (l => 2, h => 99, s => 0, q => 0);
if (!getopts('l:h:s:aq', \%opts)) {
goto USAGE;
}
if ($opts{a}) {
my $line = <STDIN>;
if (!$line) {
print STDERR "$0: no standard input: can't parse command\n";
exit 2;
}
chomp $line;
if ($line =~ /^\s*<!--\s*(.*?)\s*-->\s*$/) {
print "<!-- $1 -->\n";
exec $1;
die "exec '$1' failed: $!";
} else {
print STDERR "$0: can't parse command from '$line'\n";
}
exit;
}
if (@ARGV == 0) {
USAGE:
print STDERR "\
Usage: md2toc [options] <FILE.md>\
-l <lowest> specifies lowest heading level to include.\
-h <highest> specifies highest heading level to include.\
-s <skip> skip the first few lines of generated output.\
-a specifies automatic mode: run command specified by HTML comment\
-q question-marks in headings become hyphens in links [false]\n";
exit 1;
}
my $lowest = $opts{l};
my $highest = $opts{h};
my $skip = $opts{s};
while (my $line = <>) {
chomp $line;
if ($line =~ s/^(#+) *//) {
my $level = length($1);
next if $level < $lowest || $level > $highest;
my $link = lc($line);
$link =~ s/ /-/g;
$link =~ s/\?/-/g if $opts{q};
$link =~ s/[^a-z0-9-_]//g;
if ($skip > 0) {
$skip--;
} else {
print ' ' x ($level-$lowest), "* [$line](#$link)\n";
}
}
}