#!/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(/, "<", s)
gsub(/>/, ">", s)
gsub(/"/, """, s)
return s
}
/^```/ {
sub(/^```/, "")
pre = !pre
if (pre)
print "\t
"
else
print "\t
"
} !pre && /^=>/ {
u = $2
$1 = ""
$2 = ""
sub(/^[[:space:]]+/, "")
if ($0 !~ /./)
$0 = u
print "\t" hescape($0) ""
next
} !pre && /^###/ {
sub(/^###[[:space:]]*/, "")
id = tolower($0)
gsub(/[^[:alnum:]]+/, "-", id)
print "\t" \
hescape($0) "
"
next
} !pre && /^##/ {
sub(/^##[[:space:]]*/, "")
id = tolower($0)
gsub(/[^[:alnum:]]+/, "-", id)
print "\t" \
hescape($0) "
"
next
} !pre && /^#/ {
sub(/^#[[:space:]]*/, "")
id = tolower($0)
gsub(/[^[:alnum:]]+/, "-", id)
print "\t" \
hescape($0) "
"
next
} !pre && /^[[:space:]]*$/ {
print "\t
"
next
} {
print hescape($0)
}
END {
if (pre)
print "\t"
}'
if [ "$suffix" ]; then
printf '%s\n' "$suffix"
fi
}
header=''
prefix=''
suffix='
'
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