-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmktoc
executable file
·116 lines (103 loc) · 2.32 KB
/
mktoc
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#! /usr/bin/perl
# Update a TOC in a .md file. The TOC has to be under a headline that collapses into
# an anchor that is 'table-of-contents'.
#
# This only understands '#' headline format.
use strict;
use warnings;
my $skip = 0;
my $in_place = 0;
sub anchor($)
{
my ($k) = @_;
$k =~ s(/)()g;
$k =~ s/[^0-9a-z_]+/-/gi;
$k =~ s/^-//;
$k =~ s/-$//;
return lc($k);
}
sub insert_toc($)
{
my ($fn) = @_;
# load:
my @sec = ('');
open(my $f, '<', $fn) or die "Error: $fn: $@\n";
my $pre = 0;
while (<$f>) {
if ($pre) {
if (/^```/) {
$pre = 0;
}
}
else {
if (/^```/) {
$pre = 1;
}
elsif (/^#/) {
push @sec,'';
}
}
$sec[-1] .= $_;
}
close $f;
# make toc:
my $toc = '';
for my $sec (@sec) {
if ($sec =~ /^(#+)([^#].*)\n/) {
my ($i,$h) = ($1,$2);
$h =~ s/^\s+//;
$h =~ s/\s+$//;
my $k = anchor($h);
my $l = length($i);
if ($l > $skip) {
$toc .= (' ' x ($l - $skip - 1))." * [$h](#$k)\n";
}
}
}
# replace toc:
my $change = 0;
for my $sec (@sec) {
if ($sec =~ /^(#+([^#].*))\n/) {
my ($h, $k) = ($1, anchor($2));
if ($k eq 'table-of-contents') {
my $new_sec = "$h\n\n$toc\n";
if ($sec ne $new_sec) {
$sec = $new_sec;
$change = 1;
}
}
}
}
# do not save unless there was a change:
return unless $change;
# save:
open(my $g, '>', "$fn.new") or die "Error: $fn.new: $@\n";
for my $sec (@sec) {
print {$g} $sec;
}
close $g;
# rename:
if ($in_place) {
rename("$fn.new", "$fn") or die "Error: $fn.new -> $fn: $@\n";
}
}
my @file = ();
for my $arg (@ARGV) {
if ($arg =~ /^-/) {
if ($arg =~ /^-+skip([0-6])$/) {
$skip = $1;
}
elsif ($arg =~ /^-+in-place$/) {
$in_place = 1;
}
else {
die "Error: '$arg': unrecognised option\n";
}
}
else {
push @file, $arg;
}
}
for my $file (@file) {
insert_toc($file);
}