-
Notifications
You must be signed in to change notification settings - Fork 0
/
awkdown.awk
75 lines (65 loc) · 2.23 KB
/
awkdown.awk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
BEGIN {
print "<!doctype html><html>"
print "<head>"
print " <meta charset=\"utf-8\">"
print " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
if (head) print head
print "</head>"
print "<body>"
}
/^# / { print "<h1>" substr($0, 3) "</h1>"; next }
/^## / { print "<h2>" substr($0, 4) "</h2>"; next }
/^### / { print "<h3>" substr($0, 5) "</h3>"; next }
/^#### / { print "<h4>" substr($0, 6) "</h4>"; next }
/^---$/ { print "<hr />"; next }
inpre && /^```/ { flush(); print "</pre>"; inpre = 0; next }
/^```/ { print "<pre>"; inpre = 1; next }
/^-/ { if (!inul) print "<ul>"; inul = 1; print "<li>" substr($0, 3) "</li>"; next }
inul && !/^-/ { print "</ul>"; inul = 0; next }
/^[0-9]+./ { if (!inol) print "<ol>"; inol = 1; print "<li>" substr($0, length($1)+2) "</li>"; next }
inol && !/^[0-9]+./ { print "</ol>"; inol = 0; next }
/^> / { if (!inquote) print "<blockquote>"; inquote = 1; print substr($0, 3); next }
inquote && !/^> / { print "</blockquote>"; inquote = 0; next }
/./ { for (i=1; i<=NF; i++) collect($i) }
/^$/ { flushp() }
END { flushp(); flushtags() }
END {
print "</body>"
print "</html>"
}
function collect(v) {
line = line sep v
sep = " "
}
function flush() {
if (line) {
print line
line = sep = ""
}
}
function flushp() {
if (line) {
print "<p>" render(line) "</p>"
line = sep = ""
}
}
function render(line) {
if (match(line, /_(.*)_/)) {
gsub(/_(.*)_/, sprintf("<em>%s</em>", substr(line, RSTART+1, RLENGTH-2)), line)
}
if (match(line, /\*(.*)\*/)) {
gsub(/\*(.*)\*/, sprintf("<strong>%s</strong>", substr(line, RSTART+1, RLENGTH-2)), line)
}
if (match(line, /\[.+\]\(.+\)/)) {
inner = substr(line, RSTART+1, RLENGTH-2)
split(inner, spl, /\]\(/)
gsub(/\[.+\]\(.+\)/, sprintf("<a href=\"%s\">%s</a>", spl[2], spl[1]), line)
}
return line
}
function flushtags() {
if (inquote) print "</blockquote>"
if (inol) print "</ol>"
if (inul) print "</ul>"
if (inpre) print "</pre>"
}