Blob


1 #!/usr/bin/awk -f
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 BEGIN {
18 in_pre = 0;
19 in_list = 0;
20 }
22 !in_pre && /^###/ { output("<h3>", substr($0, 4), "</h3>"); next }
23 !in_pre && /^##/ { output("<h2>", substr($0, 3), "</h2>"); next }
24 !in_pre && /^#/ { output("<h1>", substr($0, 2), "</h1>"); next }
25 !in_pre && /^>/ { output("<blockquote>", substr($0, 2), "</blockquote>"); next }
26 !in_pre && /^\* / { output("<li>", substr($0, 2), "</li>"); next }
28 !in_pre && /^=>/ {
29 $0 = substr($0, 3);
30 link = $1;
31 $1 = "";
32 output_link(link, $0);
33 next;
34 }
36 !in_pre && /^```/ {
37 in_pre = 1;
38 if (in_list) {
39 in_list = 0;
40 print("</ul>");
41 }
42 print "<pre>";
43 next
44 }
46 in_pre && /^```/ { in_pre = 0; print "</pre>"; next }
47 !in_pre { output("<p>", $0, "</p>"); next }
48 in_pre { print san($0); next }
50 END {
51 if (in_list)
52 print "</ul>"
53 if (in_pre)
54 print "</pre>"
55 }
57 function trim(s) {
58 sub("^[ \t]*", "", s);
59 return s;
60 }
62 function san(s) {
63 gsub("&", "\\&amp;", s)
64 gsub("<", "\\&lt;", s)
65 gsub(">", "\\&gt;", s)
66 return s;
67 }
69 function output(ot, content, et) {
70 content = trim(content);
72 if (!in_list && ot == "<li>") {
73 in_list = 1;
74 print "<ul>";
75 }
77 if (in_list && ot != "<li>") {
78 in_list = 0;
79 print "</ul>";
80 }
82 if (ot == "<p>" && content == "")
83 return;
85 printf("%s%s%s\n", ot, san(content), et);
86 }
88 function output_link(link, content) {
89 if (in_list) {
90 in_list = 0;
91 print "</ul>";
92 }
94 if (content == "")
95 content = link;
97 printf("<p><a href=\"%s\">%s</a></p>\n", link, trim(san(content)));
98 }