#!/bin/gawk -f BEGIN { list = "" quote = 0 code = 0 } function handle_meta( i, n, cats, link) { if ($0 ~ /^; /) { if (meta_count == 0) { } else if (meta_count == 1) { sub(/^; /, "") n = split($0, cats, " ") printf "" } else if (meta_count == 2) { sub(/^; /, "") print "

" $0 "

" } meta_count++ next } } function handle_list_item(condition, type) { if ($0 ~ condition) { if (list != type) { if (list != "") print "" print "<" type ">" list = type } sub(condition, "") print "
  • " $0 "
  • " next } } function handle_quote() { if ($0 == "\"\"\"") { if (quote == 0) { print "
    " quote = 1 } else { print "
    " quote = 0 } next } } function handle_codeblock() { if ($0 ~ /^'''/) { if (code == 0) { if (list != "") { print "" list = "" } print "
    "
                code = 1
            } else {
                print "
    " code = 0 } next } if (code == 1) { gsub(/&/, "\\&") gsub(//, "\\>") print next } } function inline(delim, tag, escaped, pattern) { escaped = delim gsub(/\*/, "\\*", escaped) gsub(/\./, "\\.", escaped) pattern = escaped "([^" escaped "]+)" escaped while (match($0, pattern)) { $0 = substr($0, 1, RSTART-1) \ "<" tag ">" substr($0, RSTART+length(delim), \ RLENGTH-length(delim)*2) "" \ substr($0, RSTART+RLENGTH) } } function inline_link(pattern, result, pre, arr) { pattern = "\\[([^]]+)\\]\\(([^)]+)\\)" result = "" while (match($0, pattern, arr)) { pre = substr($0, 1, RSTART-1) result = result pre "" arr[1] "" $0 = substr($0, RSTART+RLENGTH) } $0 = result $0 } function inline_image(pattern, result, pre, arr) { pattern = "!\\[([^]]+)\\]\\(([^)]+)\\)" result = "" while (match($0, pattern, arr)) { pre = substr($0, 1, RSTART-1) result = result pre "" "\""" "" $0 = substr($0, RSTART+RLENGTH) } $0 = result $0 } function inline_footnote_ref(pattern, result, pre, arr) { pattern = ".\\[\\^([^]]+)\\]" result = "" while (match($0, pattern, arr)) { pre = substr($0, 1, RSTART) result = result pre "" arr[1] "" $0 = substr($0, RSTART+RLENGTH) } $0 = result $0 } function handle_header(i, level) { if ($0 ~ /^#+[ ]/) { level = 0 while (substr($0, level+1, 1) == "#") level++ sub(/^#+[ ]+/, "") print "" $0 "" next } } function handle_footnote(pattern, arr) { pattern = "^\\[\\^([^]]+)\\]:[ ]*(.*)" if (match($0, pattern, arr)) { if (footnote != 1) { print "
      " footnote = 1 } print "
    1. " arr[2] \ "
    2. " list = "ol" next } } { handle_meta() handle_quote() handle_codeblock() inline("**", "b") inline("*", "em") inline("--", "s") inline("'''", "code") inline_image() inline_link() inline_footnote_ref() handle_list_item("^- ", "ul") handle_list_item("^[0-9]+\\.[ ]+", "ol") handle_footnote() if (list != "") { print "" list = "" } handle_header() if ($0 != "") { print "

      " $0 "

      " } } END { if (list != "") print "" }