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 if (!$in_list) {
53 $in_list = "link";
54 say "<ul class='link-list'>";
55 } elsif ($in_list eq "item") {
56 $in_list = "link";
57 say "</ul>";
58 say "<ul class='link-list'>";
59 }
60 my $href = $1;
61 $_ = $2 || $1;
62 say "<li><a href='$href'>". san() ."</a></li>";
63 } elsif (m/^###\s*(.*)$/) {
64 output("h3", $1);
65 } elsif (m/^##\s*(.*)$/) {
66 output("h2", $1);
67 } elsif (m/^#\s*(.*)$/) {
68 output("h1", $1);
69 } elsif (m/^>\s*(.*)$/) {
70 output("blockquote", $1);
71 } else {
72 output("p", $_);
73 }
74 }
76 sub san {
77 s/&/\&amp;/g;
78 s/</\&lt;/g;
79 s/>/\&gt;/g;
80 return $_;
81 }
83 sub output {
84 my ($tn, $content) = @_;
86 if (!$in_list && $tn eq "li") {
87 $in_list = 1;
88 say "<ul>";
89 }
91 if ($in_list && $tn ne "li") {
92 $in_list = 0;
93 say "</ul>";
94 }
96 if ($tn eq "p" && $content eq "") {
97 return;
98 }
100 $_ = $content;
101 say "<$tn>". san() ."</$tn>";