-
Notifications
You must be signed in to change notification settings - Fork 0
/
md-toc.pl
executable file
·71 lines (58 loc) · 1.25 KB
/
md-toc.pl
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
#!/usr/bin/perl
# -*- mode: cperl; cperl-indent-level: 4 -*-
# $ md-toc.pl $
# Write new .md content in case the TOC
# part of the input file has changed.
# In case of file does not already have
# TOC, it needs seed line beginning with
# '·' (U+00B7, 0xC2 0xB7, MIDDLE DOT).
use 5.8.1;
use strict;
use warnings;
die "Usage: $0 filename\n" unless @ARGV;
my $fn = $ARGV[0];
die "$fn.bak exists" if -e "$fn.bak";
open I, '<', $ARGV[0] or die;
my (@lh, @lt, @lr, @ln);
while (<I>) {
chomp, push(@lt, $_), last if /^·/;
push @lh, $_;
}
while (<I>) {
push(@lr, $_), last unless /^·/;
chomp;
push @lt, $_;
}
my $p;
while (<I>) {
push @lr, $_;
if (/^-----/) {
chomp $p;
$_ = $p;
s/^\W+//; s/\W+$//; s/\W+/-/g;
push @ln, "· [$p](#$_)";
}
$p = $_;
}
my $current_toc = join("\n", @lt);
my $new_toc = join("\\\n", @ln);
#if (0) {
if ($current_toc eq $new_toc) {
print "No changes in TOC.\n";
}
else {
print "Renaming to '$fn.bak'\n";
die "Could not rename\n"
unless rename "$fn", "$fn.bak";
open O, '>', "$fn" or die;
print O @lh, $new_toc, "\n", @lr;
close O;
print "Wrote '$fn'\n";
}
exit;
#}
#print @lh;
print join("\n", @lt), "\n";
print "--------\n";
print join("\\\n", @ln), "\n";
#print @lr;