#!/usr/bin/awk BEGIN { env = "none" stack_pointer = 0 push(env) } # Function to push a value onto the stack function push(value) { stack_pointer++ stack[stack_pointer] = value } # Function to pop a value from the stack (LIFO) function pop() { if (stack_pointer > 0) { value = stack[stack_pointer] delete stack[stack_pointer] stack_pointer-- return value } else { return "empty" } } # Function to get last value in LIFO function last() { return stack[stack_pointer] } function replaceInline(line, result, start, end) { # Replace occurrences of **...** with ... while (match(line, /\*\*([^*]+)\*\*/)) { start = RSTART end = RSTART + RLENGTH - 1 # Build the result: before match, , content, , after match line = substr(line, 1, start-1) "" substr(line, start+2, RLENGTH-4) "" substr(line, end+1) } # Replace occurrences of *...* with ... while (match(line, /\*([^*]+)\*/)) { start = RSTART end = RSTART + RLENGTH - 1 # Build the result: before match, , content, , after match line = substr(line, 1, start-1) "" substr(line, start+1, RLENGTH-2) "" substr(line, end+1) } # Replace occurances of [link](url) with link while (match(line, /\[([^\]]+)\]\([^\)]+\)/)) { start = RSTART end = RSTART + RLENGTH - 1 matched = substr($0, RSTART, RLENGTH) if (match(matched, /\[([^\]]+)\]/)) { matched_link = substr(matched, RSTART+1, RLENGTH-2) } if (match(matched, /\([^\)]+\)/)) { matched_url = substr(matched, RSTART+1, RLENGTH-2) } # Build the result: before match, , content, , after match line = substr(line, 1, start-1) "" matched_link "" substr(line, end+1) } # Replace occurences of `...` with ... while (match(line, /`(.+)`/)) { start = RSTART end = RSTART + RLENGTH - 1 line = substr(line, 1, start-1) "" substr(line, start+1, RLENGTH-2) "" substr(line, end+1) } return line } function closeOne() { env = pop() print "" } # Matching headers /^#+ / { match($0, /#+ /); n = RLENGTH; print "" substr($0, n + 1) "" } # Matching blockquotes /^> / { env = last() if (env == "blockquote") { # In a blockquote block only print the text print substr($0, 3); } else { # Otherwise, init the blockquote block push("blockquote") print "
\n" substr($0, 3) } } # Matching unordered lists /^[-+*] / { env = last() if (env == "ul" ) { # In a unordered list block, print a new item print "
  • " replaceInline(substr($0, 3)) "
  • " } else { # Otherwise, init the unordered list block push("ul") print "