misc-scripts/gmi2html.sh

92 lines
1.7 KiB
Bash

#!/bin/sh
usage() {
echo >&2 \
'usage: gmi2html [-h header] [-p prefix] [-s suffix] [file ...]'
exit 64
}
gmi2html() {
if [ "$prefix" ]; then
printf '%s\n' "$prefix"
fi
awk '
function hescape(s) {
gsub(/&/, "&", s)
gsub(/</, "&lt;", s)
gsub(/>/, "&gt;", s)
gsub(/"/, "&quot;", s)
return s
}
/^```/ {
sub(/^```/, "")
pre = !pre
if (pre)
print "\t<pre alt=\"" hescape($0) "\">"
else
print "\t</pre>"
} !pre && /^=>/ {
u = $2
$1 = ""
$2 = ""
sub(/^[[:space:]]+/, "")
if ($0 !~ /./)
$0 = u
print "\t<a href=\"" hescape(u) "\">" hescape($0) "</a>"
next
} !pre && /^###/ {
sub(/^###[[:space:]]*/, "")
id = tolower($0)
gsub(/[^[:alnum:]]+/, "-", id)
print "\t<h1 id=\"" hescape(id) "\">" \
hescape($0) "</h1>"
next
} !pre && /^##/ {
sub(/^##[[:space:]]*/, "")
id = tolower($0)
gsub(/[^[:alnum:]]+/, "-", id)
print "\t<h2 id=\"" hescape(id) "\">" \
hescape($0) "</h2>"
next
} !pre && /^#/ {
sub(/^#[[:space:]]*/, "")
id = tolower($0)
gsub(/[^[:alnum:]]+/, "-", id)
print "\t<h3 id=\"" hescape(id) "\">" \
hescape($0) "</h3>"
next
} !pre && /^[[:space:]]*$/ {
print "\t<br/>"
next
} {
print hescape($0)
}
END {
if (pre)
print "\t</pre>"
}'
if [ "$suffix" ]; then
printf '%s\n' "$suffix"
fi
}
header='<!doctype html>'
prefix='<html><head></head><body><article><p>'
suffix='</p></article></body></html>'
while getopts h:p:s: opt; do
case "$opt" in
h) header="$OPTARG";;
p) prefix="$OPTARG";;
s) suffix="$OPTARG";;
*) usage;;
esac
done
shift $((OPTIND - 1))
if [ "$header" ]; then
printf '%s\n' "$header"
fi
if [ "$#" -eq 0 ]; then
gmi2html
exit
fi
for f in "$@"; do
gmi2html < "$f"
done