Blob


1 #!/usr/bin/env perl
2 #
3 # Copyright (c) 2022 Omar Polo <op@openbsd.org>
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 ($in_list && m/^$/) {
39 say "</ul>";
40 $in_list = 0;
41 } elsif (m/^\*\s+(.*)/) { # NB: at least one space
42 if (!$in_list) {
43 $in_list = "item";
44 say "<ul>";
45 } elsif ($in_list eq "link") {
46 $in_list = "item";
47 say "</ul>";
48 say "<ul>";
49 }
50 output("li", $1);
51 } elsif (m/^=>\s*([^\s]*)\s*(.*)$/) {
52 my $href = $1;
53 my $alt = $2;
55 # special case: images
56 if ($1 =~ /\.(png|jpg|svg)$/) {
57 if ($in_list) {
58 say "</ul>";
59 $in_list = 0;
60 }
61 say "<img src='$href' alt='$alt' />";
62 next;
63 }
65 if (!$in_list) {
66 $in_list = "link";
67 say "<ul class='link-list'>";
68 } elsif ($in_list eq "item") {
69 $in_list = "link";
70 say "</ul>";
71 say "<ul class='link-list'>";
72 }
73 $_ = $alt || $href;
74 say "<li><a href='$href'>". san() ."</a></li>";
75 } elsif (m/^###\s*(.*)$/) {
76 output("h3", $1);
77 } elsif (m/^##\s*(.*)$/) {
78 output("h2", $1);
79 } elsif (m/^#\s*(.*)$/) {
80 output("h1", $1);
81 } elsif (m/^>\s*(.*)$/) {
82 output("blockquote", $1);
83 } else {
84 output("p", $_);
85 }
86 }
88 sub san {
89 s/&/\&amp;/g;
90 s/</\&lt;/g;
91 s/>/\&gt;/g;
92 return $_;
93 }
95 sub output {
96 my ($tn, $content) = @_;
98 if (!$in_list && $tn eq "li") {
99 $in_list = 1;
100 say "<ul>";
103 if ($in_list && $tn ne "li") {
104 $in_list = 0;
105 say "</ul>";
108 if ($tn eq "p" && $content eq "") {
109 return;
112 $_ = $content;
113 say "<$tn>". san() ."</$tn>";