]> git.plutz.net Git - cgilite/blob - markdown.awk
bugfix: enable image links
[cgilite] / markdown.awk
1 #!/bin/awk -f
2 #!/opt/busybox/awk -f
3
4 # EXPERIMENTAL Markdown processor with minimal dependencies.
5 # Meant to support all features of John Grubers basic Markdown
6 # + a number of common extensions, mostly inspired by Pandoc Markdown
7
8 # Supported Features / TODO:
9 # ==========================
10 # [x] done    [ ] todo    [-] not planned    ? unsure
11 #
12 # Basic Markdown - Block elements:
13 # -------------------------------
14 # - [x] Paragraphs
15 #   - [x] Double space line breaks
16 # - [x] Proper block element nesting
17 # - [x] Headings
18 # - [x] ATX-Style Headings
19 # - [x] Blockquotes
20 # - [x] Lists (ordered, unordered)
21 # - [x] Code blocks (using indention)
22 # - [x] Horizontal rules
23 # - [x] Verbatim HTML block (disabled by default)
24 #
25 # Basic Markdown - Inline elements:
26 # ---------------------------------
27 # - [x] Links
28 # - [x] Reference style links
29 # - [x] Emphasis *em*/**strong** (*Asterisk*, _Underscore_)
30 # - [x] `code`, also ``code containing `backticks` ``
31 # - [x] Images / reference style images
32 # - [x] <automatic links>
33 # - [x] backslash escapes
34 # - [x] Verbatim HTML inline (disabled by default)
35 # - [x] HTML escaping
36 #
37 # NOTE: Set the environment variable MD_HTML=true to enable verbatim HTML
38 #
39 # Extensions - Block elements:
40 # ----------------------------
41 # -  ?  Heading identifiers (php md, pandoc)
42 # - [x] Automatic heading identifiers (custom)
43 # - [x] Fenced code blocks (php md, pandoc)
44 #   - [x] Fenced code attributes
45 # - [/] Tables
46 #   -  ?  Simple table (pandoc)
47 #   -  ?  Multiline table (pandoc)
48 #   - [x] Grid table (pandoc)
49 #   - [x] Pipe table (php md pandoc)
50 # - [x] Line blocks (pandoc)
51 # - [x] Task lists (pandoc, custom)
52 # - [ ] Definition lists (php md, pandoc)
53 # - [-] Numbered example lists (pandoc)
54 # - [-] Metadata blocks (pandoc)
55 # - [x] Metadata blocks (custom)
56 # - [x] Fenced Divs (pandoc)
57 #
58 # Extensions - Inline elements:
59 # ----------------------------
60 # - [x] Ignore embedded_underscores (php md, pandoc)
61 # - [x] ~~strikeout~~ (pandoc)
62 # - [x] ^Superscript^ ~Subscript~ (pandoc)
63 # - [-] Bracketed spans (pandoc)
64 #   - [-] Inline attributes (pandoc)
65 # - [x] Image attributes (custom, pandoc inspired, inline only)
66 # - [x] Wiki style links [[PageName]] / [[PageName|Link Text]]
67 # - [-] TEX-Math (pandoc)
68 # -  ?  Footnotes (php md)
69 # -  ?  Abbreviations (php md)
70 # -  ?  "Curly quotes" (smartypants)
71 # - [ ] em-dashes (--) (smartypants old)
72 # -  ?  ... three-dot ellipsis (smartypants)
73 # - [-] en-dash (smartypants)
74 # - [ ] Automatic em-dash / en-dash
75 # - [ ] Automatic -> Arrows <-
76
77 function debug(text) { printf "\n---\n%s\n---\n", text > "/dev/stderr"; }
78
79 function HTML ( text ) {
80   gsub( /&/,  "\\&amp;",  text );
81   gsub( /</,  "\\&lt;",   text );
82   gsub( />/,  "\\&gt;",   text );
83   gsub( /"/,  "\\&quot;", text );
84   gsub( /'/,  "\\&#x27;", text );
85   gsub( /\\/, "\\&#x5C;", text );
86   return text;
87 }
88
89 function URL ( text ) {
90   gsub( /&/,  "%26",  text );
91   gsub( /"/,  "%22", text );
92   gsub( /'/,  "%27", text );
93   gsub( /\?/,  "%3F", text );
94   gsub( /#/,  "%23", text );
95   gsub( /\[/,  "%5B", text );
96   gsub( /\]/,  "%5D", text );
97   gsub( / /,  "%20", text );
98   gsub( /       /,  "%09", text );
99   gsub( /\\/, "%5C", text );
100   return text;
101 }
102
103 function inline( line, LOCAL, len, code, href, guard ) {
104   nu = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\_]|_[[:alnum:]])*"    # not underline (except when escaped)
105   na = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\\\*])*"  # not asterisk (except when escaped)
106   ieu =  "_([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])_"                 # inner <em> (underline)
107   isu = "__([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])__"                # inner <strong> (underline)
108   iea =    "\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*"     # inner <em> (asterisk)
109   isa = "\\*\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*\\*"  # inner <strong> (asterisk)
110
111   if ( line ~ /^$/ ) {  # Recursion End
112     return "";
113
114   #  omit processing of escaped characters
115   } else if ( line ~ /^\\[]\\`\*_\{\}\(\)#\+-\.![]/) {
116     return substr(line, 2, 1) inline( substr(line, 3) );
117
118   # hard brakes
119   } else if ( match(line, /^  \n/) ) {
120     return "<br>\n" inline( substr(line, RLENGTH + 1) );
121
122   #  ``code spans``
123   } else if ( match( line, /^`+/) ) {
124     len = RLENGTH
125     guard = substr( line, 1, len )
126     if ( match(line, guard ".*" guard) ) {
127       code = substr( line, len + 1, match( substr(line, len + 1), guard ) - 1)
128       len = 2 * length(guard) + length(code)
129       #  strip single surrounding white spaces
130       code = gensub( / (.*) /, "\\1", "1" , code)
131       #  escape HTML within code span
132       gsub( /&/, "\\&amp;", code ); gsub( /</, "\\&lt;", code ); gsub( />/, "\\&gt;", code );
133       return "<code>" code "</code>" inline( substr( line, len + 1 ) )
134     }
135
136   # Wiki style links
137   } else if ( match( line, /^\[\[([^\]\|]+)(\|([^\]]+))?\]\]/) ) {
138     len = RLENGTH;
139     href = gensub(/^\[\[([^\]\|]+)(\|([^\]]+))?\]\]/, "\\1", 1, substr(line, 1, len) );
140     text = gensub(/^\[\[([^\]\|]+)(\|([^\]]+))?\]\]/, "\\3", 1, substr(line, 1, len) );
141     if ( ! text ) text = href;
142     return "<a href=\"" URL(href) "\">" HTML(text) "</a>" inline( substr( line, len + 1) );
143
144   #  quick links ("automatic links" in md doc)
145   } else if ( match( line, /^<[a-zA-Z]+:\/\/([-\.[:alnum:]]+)(:[0-9]*)?(\/[^>]*)?>/ ) ) {
146     len = RLENGTH;
147     href = URL( substr( line, 2, len - 2) );
148     return "<a href=\"" href "\">" href "</a>" inline( substr( line, len + 1) );
149
150   # quick link email
151   } else if ( match( line, /^<[a-zA-Z0-9.!#$%&'\''*+\/=?^_`{|}~-]+@[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*>/ ) ) {
152     len = RLENGTH;
153     href = URL( substr( line, 2, len - 2) );
154     return "<a href=\"mailto:" href "\">" href "</a>" inline( substr( line, len + 1) );
155
156   # inline links
157   #                                 ,_______________________Image____________________________,
158   } else if ( match(line, /^\[([^]]+|!\[[^]]+\]\([^"\)]+([ \t]+"[^"]+")?\)(\{[a-zA-Z \t-]*\})?)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/) ) {
159     len = RLENGTH;
160     text  = gensub(/^\[([^]]+|!\[[^]]+\]\([^"\)]+([ \t]+"[^"]+")?\)(\{[a-zA-Z \t-]*\})?)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/, \
161                    "\\1", 1, substr(line, 1, len) );
162     href  = gensub(/^\[([^]]+|!\[[^]]+\]\([^"\)]+([ \t]+"[^"]+")?\)(\{[a-zA-Z \t-]*\})?)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/, \
163                    "\\4", 1, substr(line, 1, len) );
164     title = gensub(/^\[([^]]+|!\[[^]]+\]\([^"\)]+([ \t]+"[^"]+")?\)(\{[a-zA-Z \t-]*\})?)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/, \
165                    "\\6", 1, substr(line, 1, len) );
166     if ( title ) {
167       return "<a href=\"" URL(href) "\" title=\"" HTML(title) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
168     } else {
169       return "<a href=\"" URL(href) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
170     }
171
172   # reference style links
173   } else if ( match(line, /^\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
174     len = RLENGTH;
175     text = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, substr(line, 1, len) );
176       id = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, substr(line, 1, len) );
177     if ( ! id ) id = text;
178     if ( rl_href[id] && rl_title[id] ) {
179       return "<a href=\"" URL(rl_href[id]) "\" title=\"" HTML(rl_title[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
180     } else if ( rl_href[id] ) {
181       return "<a href=\"" URL(rl_href[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
182     } else {
183       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
184     }
185
186   # inline images
187   } else if ( match(line, /^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/) ) {
188     len = RLENGTH;
189     text   = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/, "\\1", "g", substr(line, 1, len) );
190     href   = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/, "\\2", "g", substr(line, 1, len) );
191     title  = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/, "\\4", "g", substr(line, 1, len) );
192     attrib = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/, "\\6", "g", substr(line, 1, len) );
193     if ( title && attrib ) {
194       return "<img src=\"" URL(href) "\" alt=\"" HTML(text) "\" title=\"" HTML(title) "\" class=\"" HTML(attrib) "\">" \
195              inline( substr( line, len + 1) );
196     } else if ( title ) {
197       return "<img src=\"" URL(href) "\" alt=\"" HTML(text) "\" title=\"" HTML(title) "\">" \
198              inline( substr( line, len + 1) );
199     } else if ( attrib ) {
200       return "<img src=\"" URL(href) "\" alt=\"" HTML(text) "\" class=\"" HTML(attrib) "\">" \
201              inline( substr( line, len + 1) );
202     } else {
203       return "<img src=\"" URL(href) "\" alt=\"" HTML(text) "\">" \
204              inline( substr( line, len + 1) );
205     }
206
207   # reference style images
208   } else if ( match(line, /^!\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
209     len = RLENGTH;
210     text = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, substr(line, 1, len) );
211       id = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, substr(line, 1, len) );
212     if ( ! id ) id = text;
213     if ( rl_href[id] && rl_title[id] ) {
214       return "<img src=\"" URL(rl_href[id]) "\" alt=\"" HTML(text) "\" title=\"" HTML(rl_title[id]) "\">" \
215              inline( substr( line, len + 1) );
216     } else if ( rl_href[id] ) {
217       return "<img src=\"" URL(rl_href[id]) "\" alt=\"" HTML(text) "\">" \
218              inline( substr( line, len + 1) );
219     } else {
220       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
221     }
222
223   #  ~~strikeout~~ (pandoc)
224   } else if ( match(line, /^~~([[:graph:]]|[[:graph:]]([^~]|~[^~])*[[:graph:]])~~/) ) {
225     len = RLENGTH;
226     return "<del>" inline( substr( line, 3, len - 4 ) ) "</del>" inline( substr( line, len + 1 ) );
227
228   #  ^superscript^ (pandoc)
229   } else if ( match(line, /^\^([^[:space:]^]|\\[ ^])+\^/) ) {
230     len = RLENGTH;
231     return "<sup>" inline( substr( line, 2, len - 2 ) ) "</sup>" inline( substr( line, len + 1 ) );
232
233   #  ~subscript~ (pandoc)
234   } else if ( match(line, /^~([^[:space:]~]|\\[ ~])+~/) ) {
235     len = RLENGTH;
236     return "<sub>" inline( substr( line, 2, len - 2 ) ) "</sub>" inline( substr( line, len + 1 ) );
237
238   # ignore embedded underscores (pandoc, php md)
239   } else if ( match(line, "^[[:alnum:]](__|_)") ) {
240     return HTML(substr( line, 1, RLENGTH)) inline( substr(line, RLENGTH + 1) );
241
242   #  __strong__$
243   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__$") ) {
244     len = RLENGTH;
245     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
246
247   #  __strong__
248   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__[[:space:][:punct:]]") ) {
249     len = RLENGTH;
250     return "<strong>" inline( substr( line, 3, len - 5 ) ) "</strong>" inline( substr( line, len) );
251
252   #  **strong**
253   } else if ( match(line, "^\\*\\*(([^\\*[:space:]]|" iea ")|([^\\*[:space:]]|" iea ")(" na "|" iea ")*([^\\*[:space:]]|" iea "))\\*\\*") ) {
254     len = RLENGTH;
255     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
256
257   #  _em_$
258   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_$") ) {
259     len = RLENGTH;
260     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
261
262   #  _em_
263   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_[[:space:][:punct:]]") ) {
264     len = RLENGTH;
265     return "<em>" inline( substr( line, 2, len - 3 ) ) "</em>" inline( substr( line, len ) );
266
267   #  *em*
268   } else if ( match(line, "^\\*(([^\\*[:space:]]|" isa ")|([^\\*[:space:]]|" isa ")(" na "|" isa ")*([^\\*[:space:]]|" isa "))\\*") ) {
269     len = RLENGTH;
270     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
271
272   # Macros
273   } else if ( AllowMacros && match( line, /^<<([^>]|>[^>])+>>/) ) {
274     len = RLENGTH;
275     return macro( substr( line, 3, len - 4 ) ) inline(substr(line, len + 1));
276
277   # Verbatim inline HTML
278   } else if ( AllowHTML && match( line, /^(<!--([^-]|-[^-]|--[^>])*-->|<\?([^\?]|\?[^>])*\?>|<![A-Z][^>]*>|<!\[CDATA\[([^\]]|\][^\]]|\]\][^>])*\]\]>|<\/[A-Za-z][A-Za-z0-9-]*[[:space:]]*>|<[A-Za-z][A-Za-z0-9-]*([[:space:]]+[A-Za-z_:][A-Za-z0-9_\.:-]*([[:space:]]*=[[:space:]]*([[:space:]"'=<>`]+|"[^"]*"|'[^']*'))?)*[[:space:]]*\/?>)/) ) {
279     len = RLENGTH;
280     return substr( line, 1, len) inline(substr(line, len + 1));
281
282   # Literal HTML entities
283   } else if ( match( line, /^&([a-zA-Z]{2,32}|#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});/) ) {
284     len = RLENGTH;
285     return substr( line, 1, len ) inline(substr(line, len + 1));
286
287   # Escape lone HTML character
288   } else if ( match( line, /^[&<>"']/) ) {
289     return HTML(substr(line, 1, 1)) inline(substr(line, 2));
290
291   #  continue walk over string
292   } else {
293     return substr(line, 1, 1) inline( substr(line, 2) );
294   }
295 }
296
297 function _block( block, LOCAL, st, len, hlvl, htxt, guard, code, indent, attrib ) {
298   gsub( /^\n+|\n+$/, "", block );
299
300   if ( block == "" ) {
301     return "";
302
303   # HTML #2 #3 #4 $5
304   } else if ( AllowHTML && match( block, /(^|\n) ? ? ?(<!--([^-]|-[^-]|--[^>])*(-->|$)|<\?([^\?]|\?[^>])*(\?>|$)|<![A-Z][^>]*(>|$)|<!\[CDATA\[([^\]]|\][^\]]|\]\][^>])*(\]\]>|$))/) ) {
305     len = RLENGTH; st = RSTART;
306     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
307
308   # HTML #6
309   } else if ( AllowHTML && match( tolower(block), /(^|\n) ? ? ?<\/?(address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[123456]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)([[:space:]\n>]|\/>)([^\n]|\n[ \t]*[^\n])*(\n[[:space:]]*\n|$)/) ) {
310     len = RLENGTH; st = RSTART;
311     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
312
313   # HTML #1
314   } else if ( AllowHTML && match( tolower(block), /(^|\n) ? ? ?<(script|pre|style)([[:space:]\n>]).*(<\/script>|<\/pre>|<\/style>|$)/) ) {
315     len = RLENGTH; st = RSTART;
316     match( tolower(substr(block, st, len)), /(<\/script>|<\/pre>|<\/style>)/);
317     len = RSTART + RLENGTH;
318     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
319
320   # HTML #7
321   } else if ( AllowHTML && match( block, /^ ? ? ?(<\/[A-Za-z][A-Za-z0-9-]*[[:space:]]*>|<[A-Za-z][A-Za-z0-9-]*([[:space:]]+[A-Za-z_:][A-Za-z0-9_\.:-]*([[:space:]]*=[[:space:]]*([[:space:]"'=<>`]+|"[^"]*"|'[^']*'))?)*[[:space:]]*\/?>)([[:space:]]*\n)([^\n]|\n[ \t]*[^\n])*(\n[[:space:]]*\n|$)/) ) {
322     len = RLENGTH; st = RSTART;
323     return substr(block, st, len) _block(substr(block, st + len));
324
325   # Metadata (custom, block starting with %something)
326   # Metadata is ignored but can be interpreted externally
327   } else if ( match(block, /^%[a-zA-Z]+([[:space:]][^\n]*)?(\n|$)(%[a-zA-Z]+([[:space:]][^\n]*)?(\n|$)|%([[:space:]][^\n]*)?(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
328     len = RLENGTH; st = RSTART;
329     return  _block( substr( block, len + 1) );
330  
331   # Blockquote (leading >)
332   } else if ( match( block, /^> /) ) {
333     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
334     len = RLENGTH; st = RSTART;
335     return "<blockquote>\n" _block( gensub( /(^|\n)> /, "\n", "g", substr(block, 1, st - 1) ) ) "</blockquote>\n\n" \
336            _block( substr(block, st + len) );
337
338   # Pipe Tables (pandoc / php md / gfm )
339   } else if ( match(block, "^((\\|)?([^\n]+\\|)+[^\n]+(\\|)?)\n" \
340                            "((\\|)?:?(-+:?[\\|+])+:?-+:?(\\|)?)\n" \
341                            "((\\|)?([^\n]+\\|)+[^\n]+(\\|)?(\n|$))+" ) ) {
342     len = RLENGTH; st = RSTART;
343     #initialize empty arrays
344     split("", talign); split("", tarray);
345     cols = 0; cnt=0; ttext = "";
346
347     # table header and alignment
348     split( gensub( /(^\||\|$)/, "", "g", \
349            gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
350            substr(block, 1, match(block, /(\n|$)/)) \
351     )), tarray, /\|/);
352     block = substr(block, match(block, /(\n|$)/) + 1 );
353     cols = split( \
354            gensub( /(^\||\|$)/, "", "g", \
355            substr(block, 1, match(block, /(\n|$)/)) \
356     ), talign, /[+\|]/);
357     block = substr(block, match(block, /(\n|$)/) + 1 );
358
359     for( cnt = 1; cnt < cols; cnt++ ) {
360            if (match(talign[cnt], /:-+:/)) talign[cnt]="center";
361       else if (match(talign[cnt],  /-+:/)) talign[cnt]="right";
362       else if (match(talign[cnt],  /:-+/)) talign[cnt]="left";
363       else talign[cnt]="";
364     }
365
366     ttext = "<thead>\n<tr>"
367     for (cnt = 1; cnt < cols; cnt++)
368       ttext = ttext "<th align=\"" talign[cnt] "\">" inline(tarray[cnt]) "</th>"
369     ttext = ttext "</tr>\n</thead><tbody>\n"
370
371     while ( match(block, "^((\\|)?([^\n]+\\|)+[^\n]+(\\|)?(\n|$))+" ) ){
372       split( gensub( /(^\||\|$)/, "", "g", \
373              gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
374              substr(block, 1, match(block, /(\n|$)/)) \
375       )), tarray, /\|/);
376       block = substr(block, match(block, /(\n|$)/) + 1 );
377
378       ttext = ttext "<tr>"
379       for (cnt = 1; cnt < cols; cnt++)
380         ttext = ttext "<td align=\"" talign[cnt] "\">" inline(tarray[cnt]) "</td>"
381       ttext = ttext "</tr>\n"
382     }
383     return "<table>" ttext "</tbody></table>\n" _block(block);
384
385   # Grid Tables (pandoc)
386   } else if ( match(block, "^\\+(-+\\+)+\n" \
387                        "(\\|([^\n]+\\|)+\n)+" \
388                         "\\+(:?=+:?\\+)+\n" \
389                       "((\\|([^\n]+\\|)+\n)+" \
390                             "\\+(-+\\+)+(\n|$))+" \
391             ) ) {
392     len = RLENGTH; st = RSTART;
393     #initialize empty arrays
394     split("", talign); split("", tarray); split("", tread);
395     cols = 0; cnt=0; ttext = "";
396
397     # table header and alignment
398     block = substr(block, match(block, /(\n|$)/) + 1 );
399     while ( match(block, "^\\|([^\n]+\\|)+\n") ) {
400       cols = split( gensub( /(^\||\|$)/, "", "g", \
401              gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
402              substr(block, 1, match(block, /(\n|$)/)) \
403       )), tread, /\|/);
404       block = substr(block, match(block, /(\n|$)/) + 1 );
405       for (cnt = 1; cnt < cols; cnt++)
406         tarray[cnt] = tarray[cnt] "\n" tread[cnt];
407     }
408
409     cols = split( \
410            gensub( /(^\+|\+$)/, "", "g", \
411            substr(block, 1, match(block, /(\n|$)/)) \
412     ), talign, /\+/);
413     block = substr(block, match(block, /(\n|$)/) + 1 );
414
415     for (cnt = 1; cnt < cols; cnt++) {
416            if (match(talign[cnt], /:=+:/)) talign[cnt]="center";
417       else if (match(talign[cnt],  /=+:/)) talign[cnt]="right";
418       else if (match(talign[cnt], /:=+/ )) talign[cnt]="left";
419       else talign[cnt]="";
420     }
421
422     ttext = "<thead>\n<tr>"
423     for (cnt = 1; cnt < cols; cnt++)
424       ttext = ttext "<th align=\"" talign[cnt] "\">" _block(tarray[cnt]) "</th>"
425     ttext = ttext "</tr>\n</thead><tbody>\n"
426
427     while ( match(block, /^((\|([^\n]+\|)+\n)+\+(-+\+)+(\n|$))+/ ) ){
428       split("", tarray);
429       while ( match(block, /^\|([^\n]+\|)+\n/) ) {
430         split( gensub( /(^\||\|$)/, "", "g", \
431                gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
432                substr(block, 1, match(block, /(\n|$)/)) \
433         )), tread, /\|/);
434         block = substr(block, match(block, /(\n|$)/) + 1 );
435         for (cnt = 1; cnt < cols; cnt++)
436           tarray[cnt] = tarray[cnt] "\n" tread[cnt];
437       }
438       block = substr(block, match(block, /(\n|$)/) + 1 );
439
440       ttext = ttext "<tr>"
441       for (cnt = 1; cnt < cols; cnt++)
442         ttext = ttext "<td align=\"" talign[cnt] "\">" _block(tarray[cnt]) "</td>"
443       ttext = ttext "</tr>\n"
444     }
445     return "<table>" ttext "</tbody></table>\n" _block(block);
446
447   # Line Blocks (pandoc)
448   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
449     len = RLENGTH; st = RSTART;
450     code = substr(block, 1, len);
451     gsub(/\n[[:space:]]+/, " ", code);
452     gsub(/\n\| /, "\n", code);
453     gsub(/^\| |\n$/, "", code);
454     return "<div class=\"line-block\">" gensub(/\n/, "<br>\n", "g", inline( code )) "</div>\n" \
455            _block( substr( block, len + 1) );
456
457   # Indented Code Block
458   } else if ( match(block, /^(    |\t)( *\t*[^ \t\n]+ *\t*)+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
459     len = RLENGTH; st = RSTART;
460     code = substr(block, 1, len);
461     gsub(/(^|\n)(    |\t)/, "\n", code);
462     gsub(/^\n|\n+$/, "", code);
463     return "<pre><code>" HTML( code ) "</code></pre>\n" \
464            _block( substr( block, len + 1 ) );
465
466   # Fenced Divs (pandoc, custom)
467   } else if ( match( block, /^(:::+)/ ) ) {
468     guard = substr( block, 1, RLENGTH );
469     code = gensub(/^[^\n]+\n/, "", 1, block);
470     attrib = gensub(/^:::+[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\1", 1, block);
471     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
472     gsub(/(^ | $)/, "", attrib);
473     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
474       len = RLENGTH; st = RSTART;
475       return "<div class=\"" attrib "\">" _block( substr(code, 1, st - 1) ) "</div>\n" \
476              _block( substr( code, st + len ) );
477     } else {
478       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
479       len = RLENGTH; st = RSTART;
480       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
481              _block( substr(block, st + len) );
482     }
483
484   # Fenced Code Block (pandoc)
485   } else if ( match( block, /^(~~~+|```+)/ ) ) {
486     guard = substr( block, 1, RLENGTH );
487     code = gensub(/^[^\n]+\n/, "", 1, block);
488     attrib = gensub(/^(~~~+|```+)[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\2", 1, block);
489     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
490     gsub(/(^ | $)/, "", attrib);
491     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
492       len = RLENGTH; st = RSTART;
493       return "<pre><code class=\"" attrib "\">" HTML( substr(code, 1, st - 1) ) "</code></pre>\n" \
494              _block( substr( code, st + len ) );
495     } else {
496       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
497       len = RLENGTH; st = RSTART;
498       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
499              _block( substr(block, st + len) );
500     }
501
502   # Unordered list
503   } else if ( match( block, "^ ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
504                             "(([ \t]*\n)* ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
505                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
506                             "|[^\n]+(\n|$))*" ) ) {
507   list = substr( block, 1, RLENGTH);
508   block = substr( block, RLENGTH + 1);
509   indent = length( gensub(/[-+*][ \t]+[^\n]+.*$/, "", 1, list) );
510
511   gsub("(^|\n) {0," indent "}", "\n", list);
512   return "\n<ul>\n" _list( substr(list, 2) ) "</ul>\n" _block( block );
513
514   # Ordered list
515   } else if ( match( block, "^ ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
516                             "(([ \t]*\n)* ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
517                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
518                             "|[^\n]+(\n|$))*" ) ) {
519   list = substr( block, 1, RLENGTH);
520   block = substr( block, RLENGTH + 1);
521   indent = length( gensub(/([0-9]+|#)\.[ \t]+[^\n]+.*$/, "", 1, list) );
522
523   gsub("(^|\n) {0," indent "}", "\n", list);
524   return "\n<ol>\n" _list( substr(list, 2) ) "</ol>\n" _block( block );
525
526   # First Order Heading
527   } else if ( match( block, /^[^\n]+\n===+(\n|$)/ ) ) {
528     len = RLENGTH;
529     HL[1]++; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
530     return "<h1 id=\"" HL[1] ":" URL(gensub( /\n.*$/, "", "g", block )) "\">" \
531            inline( gensub( /\n.*$/, "", "g", block ) ) \
532            "<a class=\"anchor\" href=\"#" HL[1] ":" \
533            URL(gensub( /\n.*$/, "", "g", block )) "\"></a></h1>\n\n" \
534            _block( substr( block, len + 1 ) );
535
536   # Second Order Heading
537   } else if ( match( block, /^[^\n]+\n---+(\n|$)/ ) ) {
538     len = RLENGTH;
539     HL[2]++; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
540     return "<h2 id=\"" HL[1] "." HL[2] ":" URL(gensub( /\n.*$/, "", "g", block )) "\">" \
541            inline( gensub( /\n.*$/, "", "g", block ) ) \
542            "<a class=\"anchor\" href=\"#" HL[1] "." HL[2] ":" \
543            URL(gensub( /\n.*$/, "", "g", block )) "\"></a></h2>\n\n" \
544            _block( substr( block, len + 1) );
545
546   # Nth Order Heading
547   } else if ( match( block, /^#{1,6}[ \t]*[^\n]+([ \t]*#*)(\n|$)/ ) ) {
548     len = RLENGTH;
549     hlvl = length( gensub( /^(#{1,6}).*$/, "\\1", "g", block ) );
550     htxt = gensub(/^#{1,6}[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[^\n#])+)([ \t]*#*)(\n.*)?$/, "\\1", 1, block);
551     HL[hlvl]++; for ( n = hlvl + 1; n < 7; n++) { HL[n] = 0;}
552     hid = HL[1]; for ( n = 2; n <= hlvl; n++) { hid = hid "." HL[n] ; }
553     return "<h" hlvl " id=\"" hid ":" URL(htxt) "\">" inline( htxt ) \
554            "<a class=\"anchor\" href=\"#" hid "\"></a></h" hlvl ">\n\n" \
555            _block( substr( block, len + 1) );
556
557   # Split paragraphs
558   } else if ( match( block, /(^|\n)[[:space:]]*(\n|$)/) ) {
559     len = RLENGTH; st = RSTART;
560     return _block( substr(block, 1, st - 1) ) "\n" \
561            _block( substr(block, st + len) );
562
563   # Horizontal rule
564   } else if ( match( block, /(^|\n) ? ? ?((\* *){3,}|(- *){3,}|(_ *){3,})($|\n)/) ) {
565     len = RLENGTH; st = RSTART;
566     return _block(substr(block, 1, st - 1)) "<hr>\n" _block(substr(block, st + len));
567
568   # Plain paragraph
569   } else {
570     return "<p>" inline(block) "</p>\n";
571   }
572 }
573
574 function _list( block, last, LOCAL, p) {
575   if ( ! length(block) ) return "";
576   gsub(/^([-+*]|[0-9]+\.|#\.)(  ? ? ?|\t)/, "", block)
577
578   # slice next list item from input
579   if ( match( block, /\n([-+*]|[0-9]+\.|#\.)[ \t]+[^\n]+/) ) {
580     p = substr( block, 1, RSTART);
581     block = substr( block, RSTART + 1);
582   } else {
583     p = block; block = "";
584   }
585   sub( /\n +([-+*]|[0-9]+\.|#\.)/, "\n&", p );
586
587   # if this should be a paragraph item
588   # either previous item (last) or current item (p) contains blank lines
589   if (match(last, /\n[[:space:]]*\n/) || match(p, /\n[[:space:]]*\n/) ) {
590     last = p; p = _block(p);
591   } else {
592     last = p; p = _block(p);
593     sub( /^<p>/, "", p );
594     sub( /<\/p>\n/, "", p );
595   }
596   sub( /\n$/, "", p );
597
598   # Task List (pandoc, custom)
599          if ( p ~ /^\[ \].*/ )       { return "<li class=\"task pending\"><input type=checkbox disabled>" \
600                                               substr(p, 4) "</li>\n" _list( block, last );
601   } else if ( p ~ /^\[-\].*/ )       { return "<li class=\"task negative\"><input type=checkbox disabled>" \
602                                               substr(p, 4) "</li>\n" _list( block, last );
603   } else if ( p ~ /^\[\?\].*/ )      { return "<li class=\"task unsure\"><input type=checkbox disabled>" \
604                                               substr(p, 4) "</li>\n" _list( block, last );
605   } else if ( p ~ /^\[\/\].*/ )      { return "<li class=\"task partial\"><input type=checkbox disabled>" \
606                                               substr(p, 4) "</li>\n" _list( block, last );
607   } else if ( p ~ /^\[[xX]\].*/ )    { return "<li class=\"task done\"><input type=checkbox disabled checked>" \
608                                             substr(p, 4) "</li>\n" _list( block, last );
609   } else if ( p ~ /^<p>\[ \].*/ )    { return "<li class=\"task pending\"><p><input type=checkbox disabled>" \
610                                               substr(p, 7) "</li>\n" _list( block, last );
611   } else if ( p ~ /^<p>\[-\].*/ )    { return "<li class=\"task negative\"><p><input type=checkbox disabled>" \
612                                               substr(p, 7) "</li>\n" _list( block, last );
613   } else if ( p ~ /^<p>\[\?\].*/ )   { return "<li class=\"task unsure\"><p><input type=checkbox disabled>" \
614                                               substr(p, 7) "</li>\n" _list( block, last );
615   } else if ( p ~ /^<p>\[\/\].*/ )   { return "<li class=\"task partial\"><p><input type=checkbox disabled>" \
616                                               substr(p, 7) "</li>\n" _list( block, last );
617   } else if ( p ~ /^<p>\[[xX]\].*/ ) { return "<li class=\"task done\"><p><input type=checkbox disabled checked>" \
618                                               substr(p, 7) "</li>\n" _list( block, last );
619   } else { return "<li>" p "</li>\n" _list( block, last ); }
620 }
621
622 BEGIN {
623   # Global Vars
624   file = ""; rl_href[""] = ""; rl_title[""] = "";
625   if (ENVIRON["MD_HTML"] == "true") { AllowHTML = "true"; }
626   HL[1] = 0; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
627
628   # Buffering of full file ist necessary, e.g. to find reference links
629   while (getline) { file = file $0 "\n"; }
630   # Clean up MS-DOS line breaks
631   gsub(/\r\n/, "\n", file);
632
633   # Fill array of reference links
634   f = file; rl_id;
635   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
636   # /(^|\n) ? ? ?\[([^]\n]+)\]: ([^ \t\n]+)(\n?[ \t]+("([^"]+)"|'([^']+)'|\(([^)]+)\)))?(\n|$)/
637   while ( match(f, re_reflink ) ) {
638     rl_id           = gensub( re_reflink, "\\2", 1, substr(f, RSTART, RLENGTH) );
639     rl_href[rl_id]  = gensub( re_reflink, "\\3", 1, substr(f, RSTART, RLENGTH) );
640     rl_title[rl_id] = gensub( re_reflink, "\\5", 1, substr(f, RSTART, RLENGTH) );
641     f = substr(f, RSTART + RLENGTH);
642     rl_title[rl_id] = substr( rl_title[rl_id], 2, length(rl_title[rl_id]) - 2 );
643     if ( rl_href[rl_id] ~ /<.*>/ ) rl_href[rl_id] = substr( rl_href[rl_id], 2, length(rl_href[rl_id]) - 2 );
644   }
645   # Clear reflinks from File
646   while( gsub(re_reflink, "\n", file ) );
647   # for (n in rl_href) { debug(n " | " rl_href[n] " | " rl_title[n] ); }
648
649   # Run Block Processing -> The Actual Markdown!
650   printf "%s", _block( file );
651 }