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