Add footnotes.pl to repo.
[scripts.git] / footnotes / footnotes.pl
1 #! /usr/bin/perl -W
2 #
3 # footnotes Version 0.1 by Thomas Hochstein
4 #
5 # This script will convert footnotes in WP-footnotes notation
6 # to MultiMarkDown, i.e. replace "((Text for footnote))" with
7 # "[^1]" and add "[^1]: Text for footnote" at the end of the
8 # text, incrementing the counter each time, or the other way
9 # round.
10
11 # Copyright (c) 2014 Thomas Hochstein <thh@inter.net>
12 #
13 # It can be redistributed and/or modified under the same terms under 
14 # which Perl itself is published.
15
16 my $VERSION = "0.1";
17
18 use strict;
19 use Getopt::Long qw(GetOptions);
20
21 # read commandline option(s)
22 my ($OptTo,$OptFile);
23 GetOptions ('t|to=s'     => \$OptTo,
24             'f|file=s'   => \$OptFile,
25             'h|help'     => \&ShowPOD,
26             'V|version'  => \&ShowVersion) or exit 1;
27
28 # read whole article from STDIN or --file
29 undef $/;
30 my $article;
31 if ($OptFile) {
32   open(FILE, "< $OptFile") or die "Can't open $OptFile: $!";
33   $article = <FILE>;
34   close(FILE);
35 } else {
36   $article = <>;
37 }
38 $/ = "\n";
39
40 # conversion and output
41 my $output;
42
43 if (lc($OptTo) eq 'mmd') {
44   $output = &ConvertToMMD($article);
45 } elsif (lc($OptTo) eq 'wp') {
46   $output = &ConvertToWP($article);
47 } else {
48         print "Please set '--to' to 'mmd' or 'wp'!\n";
49   exit(1);
50 }
51
52 print $output;
53 exit(0);
54
55 ################################################################################
56
57 sub ConvertToMMD {
58   my $article = shift;
59   my $footnotes;
60   my $counter = 1;
61   
62   # match and remove all ((...)),
63   # replacing them with [^n], incrementing n each time
64   while ( $article =~ s/\(\((.+?)\)\)/"[^$counter]"/seo ) {
65     $footnotes .= "[^$counter]: " . $1 . "\n";
66     $counter++;
67   }
68
69   return "$article\n\n$footnotes\n";
70 }
71
72 sub ConvertToWP {
73   my $article = shift;
74   my @footnotes;
75   my $counter = 1;
76
77   # read footnotes in [^n] format
78   while ( $article =~ s/^\[\^$counter\]: (.+)$//m ) {
79     $footnotes[$counter] = $1;
80     $counter++;
81   }
82
83   # replace footnote plcaeholders with footnote content
84   $counter = 0;
85   foreach my $footnote (@footnotes) {
86     $article =~ s/\[\^$counter\]/"(($footnote))"/eg;
87     $counter++;
88   }
89
90   # remove trailing whitespace
91   $article =~ s/\n+$//g;
92
93   return "$article\n";
94 }
95
96 sub ShowVersion {
97   print "MMD-FootNotes v$VERSION\n";
98   print "Copyright (c) 2014 Thomas Hochstein <thh\@inter.net>\n";
99   print "This program is free software; you may redistribute it ".
100         "and/or modify it under the same terms as Perl itself.\n";
101   exit(100);
102 };
103
104 sub ShowPOD {
105   exec('perldoc', $0);
106   exit(100);
107 };
This page took 0.01245 seconds and 3 git commands to generate.