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