File: markdown-toc-filter

package info (click to toggle)
nailing-cargo 1.1.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,948 kB
  • sloc: perl: 2,622; sh: 16; makefile: 6
file content (44 lines) | stat: -rwxr-xr-x 698 bytes parent folder | download
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
#!/usr/bin/perl -wn

use strict;
use autodie;

our (@doc, @toc);
our $last;

sub scanline () {
  if (m/^-+$/ || m/^=+$/) {
    my $lev = $& =~ m/^=/ ? '  ' : '    ';
    my $href = $last;
    $href =~ y/ A-Z/-a-z/;
    $href =~ y/-._a-z//cd;
    my $text = $last;
    $text = 'Introduction' if $. == 2;
    push @toc, "${lev}* [$text](#$href)\n";
  }
  $last = $_;
  chomp $last;
}

if (1..(m/^[A-Z]/ && m/table of contents/i)) {
  # before TOC
  scanline();
  print;
} elsif (m/^\w/..0) {
  # after TOC
  push @doc, $_;
  scanline();
} else {
  # in TOC
  print if m/^===|^---/;
  scanline();
}

END {
  print <<END, @toc, "\n";

<!-- TOC autogenerated by $0, do not edit -->

END
  print @doc;
}