Blob


1 #!/usr/bin/env perl
2 #
3 # Copyright (c) 2022 Omar Polo <op@omarpolo.com>
4 #
5 # Permission to use, copy, modify, and distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 #
9 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 use v5.10;
18 use strict;
19 use warnings;
21 my $in_pre = 0;
22 my $in_list = 0;
24 while (<>) {
25 chomp;
26 if ($in_pre && m/^```/) {
27 $in_pre = 0;
28 say "</pre>";
29 } elsif (!$in_pre && m/^```/) {
30 if ($in_list) {
31 $in_list = 0;
32 say "</ul>";
33 }
34 $in_pre = 1;
35 print "<pre>";
36 } elsif ($in_pre) {
37 say san($_);
38 } elsif (m/^</) {
39 say;
40 } elsif ($in_list && m/^$/) {
41 say "</ul>";
42 $in_list = 0;
43 } elsif (m/^\*\s+(.*)/) { # NB: at least one space
44 if (!$in_list) {
45 $in_list = "item";
46 say "<ul>";
47 } elsif ($in_list eq "link") {
48 $in_list = "item";
49 say "</ul>";
50 say "<ul>";
51 }
52 output("li", $1);
53 } elsif (m/^=>\s*([^\s]*)\s*(.*)$/) {
54 my $href = $1;
55 my $alt = $2 || $1;
57 # special case: images
58 if ($1 =~ /\.(png|jpg|svg)$/) {
59 if ($in_list) {
60 say "</ul>";
61 $in_list = 0;
62 }
63 print "<figure>";
64 print "<a href='$href'>";
65 print "<img src='$href' alt='$alt' />";
66 print "</a>";
67 print "<figcaption>$alt</figcaption>";
68 print "</figure>\n";
69 next;
70 }
72 if (!$in_list) {
73 $in_list = "link";
74 say "<ul class='link-list'>";
75 } elsif ($in_list eq "item") {
76 $in_list = "link";
77 say "</ul>";
78 say "<ul class='link-list'>";
79 }
80 $_ = $alt;
81 say "<li><a href='$href'>". san() ."</a></li>";
82 } elsif (m/^###\s*(.*)$/) {
83 output("h3", $1);
84 } elsif (m/^##\s*(.*)$/) {
85 output("h2", $1);
86 } elsif (m/^#\s*(.*)$/) {
87 output("h1", $1);
88 } elsif (m/^>\s*(.*)$/) {
89 output("blockquote", $1);
90 } else {
91 output("p", $_);
92 }
93 }
95 say "</ul>" if $in_list;
96 say "</pre>" if $in_pre;
98 sub san {
99 s/&/\&amp;/g;
100 s/</\&lt;/g;
101 s/>/\&gt;/g;
102 return $_;
105 sub output {
106 my ($tn, $content) = @_;
108 if (!$in_list && $tn eq "li") {
109 $in_list = 1;
110 say "<ul>";
113 if ($in_list && $tn ne "li") {
114 $in_list = 0;
115 say "</ul>";
118 if ($tn eq "p" && $content eq "") {
119 return;
122 $_ = $content;
123 say "<$tn>". san() ."</$tn>";