]> git.plutz.net Git - cgilite/blob - markdown.awk
allow bullet symbol as list marker (for copy/paste from office documents)
[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 # Copyright 2021 - 2023 Paul Hänsch
9
10 # Permission to use, copy, modify, and/or distribute this software for any
11 # purpose with or without fee is hereby granted, provided that the above
12 # copyright notice and this permission notice appear in all copies.
13
14 # THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
17 # SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
20 # IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21
22 # Supported Features / TODO:
23 # ==========================
24 # [x] done    [ ] todo    [-] not planned    ? unsure
25 #
26 # Basic Markdown - Block elements:
27 # -------------------------------
28 # - [x] Paragraphs
29 #   - [x] Double space line breaks
30 # - [x] Proper block element nesting
31 # - [x] Headings
32 # - [x] ATX-Style Headings
33 # - [x] Blockquotes
34 # - [x] Lists (ordered, unordered)
35 # - [x] Code blocks (using indention)
36 # - [x] Horizontal rules
37 # - [x] Verbatim HTML block (disabled by default)
38 #
39 # Basic Markdown - Inline elements:
40 # ---------------------------------
41 # - [x] Links
42 # - [x] Reference style links
43 # - [x] Emphasis *em*/**strong** (*Asterisk*, _Underscore_)
44 # - [x] `code`, also ``code containing `backticks` ``
45 # - [x] Images / reference style images
46 # - [x] <automatic links>
47 # - [x] backslash escapes
48 # - [x] Verbatim HTML inline (disabled by default)
49 # - [x] HTML escaping
50 #
51 # NOTE: Set the environment variable MD_HTML=true to enable verbatim HTML
52 #
53 # Extensions - Block elements:
54 # ----------------------------
55 # - [x] Automatic <section>-wrapping (custom)
56 # -  ?  Heading identifiers (php md, pandoc)
57 #   - [x] Heading attributes (custom)
58 #   - [ ] <hr> terminates section
59 # - [x] Automatic heading identifiers (custom)
60 # - [x] Fenced code blocks (php md, pandoc)
61 #   - [x] Fenced code attributes
62 # - [x] Images (as block elements, <figure>-wrapped) (custom)
63 #   - [x] reference style block images
64 # - [/] Tables
65 #   -  ?  Simple table (pandoc)
66 #   -  ?  Multiline table (pandoc)
67 #   - [x] Grid table (pandoc)
68 #     - [x] Headerless
69 #   - [x] Pipe table (php md, pandoc)
70 # - [x] Line blocks (pandoc)
71 # - [x] Task lists (pandoc, custom)
72 # - [x] Definition lists (php md, pandoc)
73 # - [-] Numbered example lists (pandoc)
74 # - [-] Metadata blocks (pandoc)
75 # - [x] Metadata blocks (custom)
76 # - [x] Fenced Divs (pandoc)
77 #
78 # Extensions - Inline elements:
79 # ----------------------------
80 # - [x] Ignore embedded_underscores (php md, pandoc)
81 # - [x] ~~strikeout~~ (pandoc)
82 # - [x] ^Superscript^ ~Subscript~ (pandoc)
83 # - [-] Bracketed spans (pandoc)
84 #   - [-] Inline attributes (pandoc)
85 # - [x] Image attributes (custom, pandoc inspired, not for reference style)
86 # - [x] Wiki style links [[PageName]] / [[PageName|Link Text]]
87 # - [-] TEX-Math (pandoc)
88 # -  ?  Footnotes (php md)
89 # -  ?  Abbreviations (php md)
90 # -  ?  "Curly quotes" (smartypants)
91 # - [ ] em-dashes (--) (smartypants old)
92 # -  ?  ... three-dot ellipsis (smartypants)
93 # - [-] en-dash (smartypants)
94 # - [ ] Automatic em-dash / en-dash
95 # - [x] Automatic -> Arrows <- (custom)
96
97 function debug(text) { printf "\n---\n%s\n---\n", text > "/dev/stderr"; }
98
99 function HTML ( text ) {
100   gsub( /&/,  "\\&amp;",  text );
101   gsub( /</,  "\\&lt;",   text );
102   gsub( />/,  "\\&gt;",   text );
103   gsub( /"/,  "\\&quot;", text );
104   gsub( /'/,  "\\&#x27;", text );
105   gsub( /\\/, "\\&#x5C;", text );
106   return text;
107 }
108
109 function URL ( text, sharp ) {
110   gsub( /&/,  "%26",  text );
111   gsub( /"/,  "%22", text );
112   gsub( /'/,  "%27", text );
113   gsub( /`/,  "%60", text );
114   gsub( /\?/,  "%3F", text );
115   if (sharp) gsub( /#/,  "%23", text );
116   gsub( /\[/,  "%5B", text );
117   gsub( /\]/,  "%5D", text );
118   gsub( / /,  "%20", text );
119   gsub( /       /,  "%09", text );
120   gsub( /\\/, "%5C", text );
121   return text;
122 }
123
124 function inline( line, LOCAL, len, text, code, href, guard ) {
125   nu = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\_]|_[[:alnum:]])*"    # not underline (except when escaped)
126   na = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\\\*])*"  # not asterisk (except when escaped)
127   ieu =  "_([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])_"                 # inner <em> (underline)
128   isu = "__([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])__"                # inner <strong> (underline)
129   iea =    "\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*"     # inner <em> (asterisk)
130   isa = "\\*\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*\\*"  # inner <strong> (asterisk)
131
132   if ( line ~ /^$/ ) {  # Recursion End
133     return "";
134
135   # omit processing of escaped characters
136   } else if ( line ~ /^\\./) {
137     return HTML(substr(line, 2, 1)) inline( substr(line, 3) );
138
139   # hard brakes
140   } else if ( match(line, /^  \n/) ) {
141     return "<br>\n" inline( substr(line, RLENGTH + 1) );
142
143   #  ``code spans``
144   } else if ( match( line, /^`+/) ) {
145     len = RLENGTH
146     guard = substr( line, 1, len )
147     if ( match(line, guard ".*" guard) ) {
148       code = substr( line, len + 1, match( substr(line, len + 1), guard ) - 1)
149       len = 2 * length(guard) + length(code)
150       #  strip single surrounding white spaces
151       gsub( /^ | $/, "", code)
152       #  escape HTML within code span
153       gsub( /&/, "\\&amp;", code ); gsub( /</, "\\&lt;", code ); gsub( />/, "\\&gt;", code );
154       return "<code>" code "</code>" inline( substr( line, len + 1 ) )
155     }
156
157   # Wiki style links
158   } else if ( match( line, /^\[\[([^]|]+)(\|[^]]+)?\]\]/) ) {
159     len = RLENGTH;
160     href = gensub(/^\[\[([^]|]+)(\|([^]]+))?\]\]/, "\\1", 1, substr(line, 1, len) );
161     text = gensub(/^\[\[([^]|]+)(\|([^]]+))?\]\]/, "\\3", 1, substr(line, 1, len) );
162     if ( ! text ) text = href;
163     return "<a href=\"" URL(href) "\">" HTML(text) "</a>" inline( substr( line, len + 1) );
164
165   #  quick links ("automatic links" in md doc)
166   } else if ( match( line, /^<[a-zA-Z]+:\/\/([-\.[:alnum:]]+)(:[0-9]*)?(\/[^>]*)?>/ ) ) {
167     len = RLENGTH;
168     href = URL( substr( line, 2, len - 2) );
169     return "<a href=\"" href "\">" href "</a>" inline( substr( line, len + 1) );
170
171   # quick link email
172   } 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])?)*>/ ) ) {
173     len = RLENGTH;
174     href = URL( substr( line, 2, len - 2) );
175     return "<a href=\"mailto:" href "\">" href "</a>" inline( substr( line, len + 1) );
176
177   # inline links
178   #                                 ,_______________________Image____________________________,
179   } else if ( match(line, /^\[([^]]+|!\[[^]]*\]\([^"\)]+([ \t]+"[^"]+")?\)(\{[a-zA-Z \t-]*\})?)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/) ) {
180     len = RLENGTH;
181     text  = gensub(/^\[([^]]+|!\[[^]]*\]\([^"\)]+([ \t]+"[^"]+")?\)(\{[a-zA-Z \t-]*\})?)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/, \
182                    "\\1", 1, substr(line, 1, len) );
183     href  = gensub(/^\[([^]]+|!\[[^]]*\]\([^"\)]+([ \t]+"[^"]+")?\)(\{[a-zA-Z \t-]*\})?)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/, \
184                    "\\4", 1, substr(line, 1, len) );
185     title = gensub(/^\[([^]]+|!\[[^]]*\]\([^"\)]+([ \t]+"[^"]+")?\)(\{[a-zA-Z \t-]*\})?)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/, \
186                    "\\6", 1, substr(line, 1, len) );
187     if ( title ) {
188       return "<a href=\"" URL(href) "\" title=\"" HTML(title) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
189     } else {
190       return "<a href=\"" URL(href) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
191     }
192
193   # reference style links
194   } else if ( match(line, /^\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
195     len = RLENGTH;
196     text = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, substr(line, 1, len) );
197       id = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, substr(line, 1, len) );
198     if ( ! id ) id = text;
199     if ( rl_href[id] && rl_title[id] ) {
200       return "<a href=\"" URL(rl_href[id]) "\" title=\"" HTML(rl_title[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
201     } else if ( rl_href[id] ) {
202       return "<a href=\"" URL(rl_href[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
203     } else {
204       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
205     }
206
207   # inline images
208   } else if ( match(line, /^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/) ) {
209     len = RLENGTH;
210     text   = gensub(/^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/, "\\1", "g", substr(line, 1, len) );
211     href   = gensub(/^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/, "\\2", "g", substr(line, 1, len) );
212     title  = gensub(/^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/, "\\4", "g", substr(line, 1, len) );
213     attrib = gensub(/^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?/, "\\6", "g", substr(line, 1, len) );
214     if ( title && attrib ) {
215       return "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\" title=\"" HTML(title) "\" class=\"" HTML(attrib) "\">" \
216              inline( substr( line, len + 1) );
217     } else if ( title ) {
218       return "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\" title=\"" HTML(title) "\">" \
219              inline( substr( line, len + 1) );
220     } else if ( attrib ) {
221       return "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\" class=\"" HTML(attrib) "\">" \
222              inline( substr( line, len + 1) );
223     } else {
224       return "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\">" \
225              inline( substr( line, len + 1) );
226     }
227
228   # reference style images
229   } else if ( match(line, /^!\[([^]]*)\] ?\[([^]]*)\]/ ) ) {
230     len = RLENGTH;
231     text = gensub(/^!\[([^\n]*)\] ?\[([^\n]*)\].*/, "\\1", 1, substr(line, 1, len) );
232       id = gensub(/^!\[([^\n]*)\] ?\[([^\n]*)\].*/, "\\2", 1, substr(line, 1, len) );
233     if ( ! id ) id = text;
234     if ( rl_href[id] && rl_title[id] ) {
235       return "<img src=\"" URL(rl_href[id], 1) "\" alt=\"" HTML(text) "\" title=\"" HTML(rl_title[id]) "\">" \
236              inline( substr( line, len + 1) );
237     } else if ( rl_href[id] ) {
238       return "<img src=\"" URL(rl_href[id], 1) "\" alt=\"" HTML(text) "\">" \
239              inline( substr( line, len + 1) );
240     } else {
241       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
242     }
243
244   #  ~~strikeout~~ (pandoc)
245   } else if ( match(line, /^~~([[:graph:]]|[[:graph:]]([^~]|~[^~])*[[:graph:]])~~/) ) {
246     len = RLENGTH;
247     return "<del>" inline( substr( line, 3, len - 4 ) ) "</del>" inline( substr( line, len + 1 ) );
248
249   #  ^superscript^ (pandoc)
250   } else if ( match(line, /^\^([^[:space:]^]|\\[ ^])+\^/) ) {
251     len = RLENGTH;
252     return "<sup>" inline( substr( line, 2, len - 2 ) ) "</sup>" inline( substr( line, len + 1 ) );
253
254   #  ~subscript~ (pandoc)
255   } else if ( match(line, /^~([^[:space:]~]|\\[ ~])+~/) ) {
256     len = RLENGTH;
257     return "<sub>" inline( substr( line, 2, len - 2 ) ) "</sub>" inline( substr( line, len + 1 ) );
258
259   # ignore embedded underscores (pandoc, php md)
260   } else if ( match(line, "^[[:alnum:]](__|_)") ) {
261     return HTML(substr( line, 1, RLENGTH)) inline( substr(line, RLENGTH + 1) );
262
263   #  __strong__$
264   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__$") ) {
265     len = RLENGTH;
266     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
267
268   #  __strong__
269   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__[[:space:][:punct:]]") ) {
270     len = RLENGTH;
271     return "<strong>" inline( substr( line, 3, len - 5 ) ) "</strong>" inline( substr( line, len) );
272
273   #  **strong**
274   } else if ( match(line, "^\\*\\*(([^\\*[:space:]]|" iea ")|([^\\*[:space:]]|" iea ")(" na "|" iea ")*([^\\*[:space:]]|" iea "))\\*\\*") ) {
275     len = RLENGTH;
276     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
277
278   #  _em_$
279   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_$") ) {
280     len = RLENGTH;
281     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
282
283   #  _em_
284   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_[[:space:][:punct:]]") ) {
285     len = RLENGTH;
286     return "<em>" inline( substr( line, 2, len - 3 ) ) "</em>" inline( substr( line, len ) );
287
288   #  *em*
289   } else if ( match(line, "^\\*(([^\\*[:space:]]|" isa ")|([^\\*[:space:]]|" isa ")(" na "|" isa ")*([^\\*[:space:]]|" isa "))\\*") ) {
290     len = RLENGTH;
291     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
292
293   # Macros
294   } else if ( AllowMacros && match( line, /^<<([^>]|>[^>])+>>/) ) {
295     len = RLENGTH;
296     return macro( substr( line, 3, len - 4 ) ) inline(substr(line, len + 1));
297
298   # Verbatim inline HTML
299   } 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:]]*\/?>)/) ) {
300     len = RLENGTH;
301     return substr( line, 1, len) inline(substr(line, len + 1));
302
303   # Literal HTML entities
304   } else if ( match( line, /^&([a-zA-Z]{2,32}|#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});/) ) {
305     len = RLENGTH;
306     return substr( line, 1, len ) inline(substr(line, len + 1));
307
308   # Arrows
309   } else if ( line ~ /^-->( |$)/) {  # ignore multidash-arrow
310     return "--&gt;" inline( substr(line, 4) );
311   } else if ( line ~ /^<-( |$)/) {
312     return "&larr;" inline( substr(line, 3) );
313   } else if ( line ~ /^->( |$)/) {
314     return "&rarr;" inline( substr(line, 3) );
315
316   # Escape lone HTML character
317   } else if ( match( line, /^[&<>"']/) ) {
318     return HTML(substr(line, 1, 1)) inline(substr(line, 2));
319
320   #  continue walk over string
321   } else {
322     return substr(line, 1, 1) inline( substr(line, 2) );
323   }
324 }
325
326 function headline( hlvl, htxt, attrib, LOCAL, sec, n, HL) {
327   match(hstack, /([0-9]+( [0-9]+){5})$/); split( substr(hstack, RSTART),  HL);
328
329   for ( n = hlvl; n <= 6; n++ ) { sec = sec (HL[n]?"</section>":""); }
330   HL[hlvl]++; for ( n = hlvl + 1; n <= 6; n++) { HL[n] = 0;}
331
332   hid = ""; for ( n = 2; n <= blvl; n++) { hid = hid BL[n] "/"; }
333   hid = hid HL[1]; for ( n = 2; n <= hlvl; n++) { hid = hid "." HL[n] ; }
334   hid = hid ":" URL(htxt, 1);
335
336   sub(/([0-9]+( [0-9]+){5})$/, "", hstack);
337   hstack = hstack HL[1] " " HL[2] " " HL[3] " " HL[4] " " HL[5] " " HL[6];
338
339   return sec "<section class=\"" (attrib ? "h" hlvl " " attrib : "h" hlvl)  "\" id=\"" hid "\">" \
340          "<h" hlvl (attrib ? " class=\"" attrib "\"" : "") ">" inline( htxt ) \
341          "<a class=\"anchor\" href=\"#" hid "\"></a>" \
342          "</h" hlvl ">\n";
343 }
344
345 # Nested Block, resets heading counters
346 function _nblock( block, LOCAL, sec, n ) {
347   hstack = hstack " 0 0 0 0 0 0";
348
349   # Block Level
350   blvl++; BL[blvl]++;
351   for ( n = blvl + 1; n in BL; n++) { delete BL[n]; }
352
353   block = _block( block );
354   match(hstack, /([0-9]+( [0-9]+){5})$/); split( substr(hstack, RSTART),  HL);
355   sec = ""; for ( n = 1; n <= 6; n++ ) { sec = sec (HL[n]?"</section>":""); }
356
357   sub("( +[0-9]+){6} *$", "", hstack); blvl--;
358   return block sec;
359 }
360
361 function _block( block, LOCAL, st, len, text, title, attrib, href, guard, code, indent, list ) {
362   gsub( "(^\n+|\n+$)", "", block );
363
364   if ( block == "" ) {
365     return "";
366
367   # HTML #2 #3 #4 $5
368   } else if ( AllowHTML && match( block, /(^|\n) ? ? ?(<!--([^-]|-[^-]|--[^>])*(-->|$)|<\?([^\?]|\?[^>])*(\?>|$)|<![A-Z][^>]*(>|$)|<!\[CDATA\[([^\]]|\][^\]]|\]\][^>])*(\]\]>|$))/) ) {
369     len = RLENGTH; st = RSTART;
370     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
371
372   # HTML #6
373   } 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|$)/) ) {
374     len = RLENGTH; st = RSTART;
375     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
376
377   # HTML #1
378   } else if ( AllowHTML && match( tolower(block), /(^|\n) ? ? ?<(script|pre|style)([[:space:]\n>]).*(<\/script>|<\/pre>|<\/style>|$)/) ) {
379     len = RLENGTH; st = RSTART;
380     match( tolower(substr(block, st, len)), /(<\/script>|<\/pre>|<\/style>)/);
381     len = RSTART + RLENGTH;
382     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
383
384   # HTML #7
385   } 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|$)/) ) {
386     len = RLENGTH; st = RSTART;
387     return substr(block, st, len) _block(substr(block, st + len));
388
389   # Metadata (custom, block starting with %something)
390   # Metadata is ignored but can be interpreted externally
391   } else if ( match(block, /^%[a-zA-Z]+([[:space:]][^\n]*)?(\n|$)(%[a-zA-Z]+([[:space:]][^\n]*)?(\n|$)|%([[:space:]][^\n]*)?(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
392     len = RLENGTH; st = RSTART;
393     return  _block( substr( block, len + 1) );
394  
395   # Blockquote (leading >)
396   } else if ( match( block, /^> /) ) {
397     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
398     len = RLENGTH; st = RSTART;
399     text = substr(block, 1, st - 1); gsub( /(^|\n)> /, "\n", text );
400     text = _nblock( text ); gsub( /^\n|\n$/, "", text )
401     return "<blockquote>" text "</blockquote>\n\n" _block( substr(block, st + len) );
402
403   # Pipe Tables (pandoc / php md / gfm )
404   } else if ( match(block, "^((\\|)?([^\n]+\\|)+[^\n]+(\\|)?)\n" \
405                            "((\\|)?:?(-+:?[\\|+])+:?-+:?(\\|)?)\n" \
406                            "((\\|)?([^\n]+\\|)+[^\n]+(\\|)?(\n|$))+" ) ) {
407     len = RLENGTH; st = RSTART;
408     #initialize empty arrays
409     split("", talign); split("", tarray);
410     cols = 0; cnt=0; ttext = "";
411
412     # table header and alignment
413     split( gensub( /(^\||\|$)/, "", "g", \
414            gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
415            substr(block, 1, match(block, /(\n|$)/)) \
416     )), tarray, /\|/);
417     block = substr(block, match(block, /(\n|$)/) + 1 );
418     cols = split( \
419            gensub( /(^\||\|$)/, "", "g", \
420            substr(block, 1, match(block, /(\n|$)/)) \
421     ), talign, /[+\|]/);
422     block = substr(block, match(block, /(\n|$)/) + 1 );
423
424     for( cnt = 1; cnt < cols; cnt++ ) {
425            if (match(talign[cnt], /:-+:/)) talign[cnt]="center";
426       else if (match(talign[cnt],  /-+:/)) talign[cnt]="right";
427       else if (match(talign[cnt],  /:-+/)) talign[cnt]="left";
428       else talign[cnt]="";
429     }
430
431     ttext = "<thead>\n<tr>"
432     for (cnt = 1; cnt < cols; cnt++)
433       ttext = ttext "<th align=\"" talign[cnt] "\">" inline(tarray[cnt]) "</th>"
434     ttext = ttext "</tr>\n</thead><tbody>\n"
435
436     while ( match(block, "^((\\|)?([^\n]+\\|)+[^\n]+(\\|)?(\n|$))+" ) ){
437       split( gensub( /(^\||\|$)/, "", "g", \
438              gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
439              substr(block, 1, match(block, /(\n|$)/)) \
440       )), tarray, /\|/);
441       block = substr(block, match(block, /(\n|$)/) + 1 );
442
443       ttext = ttext "<tr>"
444       for (cnt = 1; cnt < cols; cnt++)
445         ttext = ttext "<td align=\"" talign[cnt] "\">" inline(tarray[cnt]) "</td>"
446       ttext = ttext "</tr>\n"
447     }
448     return "<table>" ttext "</tbody></table>\n" _block(block);
449
450   # Grid Tables (pandoc)
451   # (with, and without header)
452   } else if ( match( block, "^\\+(-+\\+)+\n" \
453                             "(\\|([^\n]+\\|)+\n)+" \
454                             "(\\+(:?=+:?\\+)+)\n" \
455                            "((\\|([^\n]+\\|)+\n)+" \
456                              "\\+(-+\\+)+(\n|$))+" \
457                    ) || \
458               match( block, "^()()()" \
459                             "(\\+(:?-+:?\\+)+)\n" \
460                            "((\\|([^\n]+\\|)+\n)+" \
461                              "\\+(-+\\+)+(\n|$))+" \
462   ) ) {
463     len = RLENGTH; st = RSTART;
464     #initialize empty arrays
465     split("", talign); split("", tarray); split("", tread);
466     cols = 0; cnt=0; ttext = "";
467
468     # Column Count
469     cols = split(   gensub( "^(\\+(:?-+:?\\+)+)(\n.*)*$", "\\1", 1, block), tread, /\+/) - 2;
470     # debug(" Cols: " gensub( "^(\\+(:?-+:?\\+)+)(\n.*)*$", "\\1", 1, block ));
471
472     # table alignment
473     split( gensub( "^(.*\n)?\\+((:?=+:?\\+|(:-+|-+:|:-+:)\\+)+)(\n.*)$", "\\2", "g", block ), talign, /\+/ );
474     # debug("Align: " gensub( "^(.*\n)?\\+((:?=+:?\\+|(:-+|-+:|:-+:)\\+)+)(\n.*)$", "\\2", "g", block ));
475
476     for (cnt = 1; cnt <= cols; cnt++) {
477            if (match(talign[cnt], /:(-+|=+):/)) talign[cnt]="center";
478       else if (match(talign[cnt],  /(-+|=+):/)) talign[cnt]="right";
479       else if (match(talign[cnt], /:(-+|=+)/ )) talign[cnt]="left";
480       else talign[cnt]="";
481     }
482
483     if ( match(block, "^\\+(-+\\+)+\n" \
484                       "(\\|([^\n]+\\|)+\n)+" \
485                        "\\+(:?=+:?\\+)+\n" \
486                      "((\\|([^\n]+\\|)+\n)+" \
487                        "\\+(-+\\+)+(\n|$))+" \
488     ) ) {
489       # table header
490       block = substr(block, match(block, /(\n|$)/) + 1 );
491       while ( match(block, "^\\|([^\n]+\\|)+\n") ) {
492         split( gensub( /(^\||\|$)/, "", "g", \
493                  gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
494                    substr(block, 1, match(block, /(\n|$)/)) \
495         )), tread, /\|/);
496         block = substr(block, match(block, /(\n|$)/) + 1 );
497         for (cnt = 1; cnt <= cols; cnt++)
498           tarray[cnt] = tarray[cnt] "\n" tread[cnt];
499       }
500
501       ttext = "<thead>\n<tr>"
502       for (cnt = 1; cnt <= cols; cnt++)
503         ttext = ttext "<th align=\"" talign[cnt] "\">" _nblock(tarray[cnt]) "</th>"
504       ttext = ttext "</tr>\n</thead>"
505     }
506
507     # table body
508     block = substr(block, match(block, /(\n|$)/) + 1 );
509     ttext = ttext "<tbody>\n"
510
511     while ( match(block, /^((\|([^\n]+\|)+\n)+\+(-+\+)+(\n|$))+/ ) ){
512       split("", tarray);
513       while ( match(block, /^\|([^\n]+\|)+\n/) ) {
514         split( gensub( /(^\||\|$)/, "", "g", \
515                gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
516                substr(block, 1, match(block, /(\n|$)/)) \
517         )), tread, /\|/);
518         block = substr(block, match(block, /(\n|$)/) + 1 );
519         for (cnt = 1; cnt <= cols; cnt++)
520           tarray[cnt] = tarray[cnt] "\n" tread[cnt];
521       }
522       block = substr(block, match(block, /(\n|$)/) + 1 );
523
524       ttext = ttext "<tr>"
525       for (cnt = 1; cnt <= cols; cnt++)
526         ttext = ttext "<td align=\"" talign[cnt] "\">" _nblock(tarray[cnt]) "</td>"
527       ttext = ttext "</tr>\n"
528     }
529     return "<table>" ttext "</tbody></table>\n" _nblock(block);
530
531   # Line Blocks (pandoc)
532   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
533     len = RLENGTH; st = RSTART;
534
535     text = substr(block, 1, len); gsub(/\n[[:space:]]+/, " ", text);
536     gsub(/\n\| /, "\n", text); gsub(/^\| |\n$/, "", text);
537     text = inline(text); gsub(/\n/, "<br>\n", text);
538
539     return "<div class=\"line-block\">" text "</div>\n" _block( substr( block, len + 1) );
540
541   # Indented Code Block
542   } else if ( match(block, /^(    |\t)( *\t*[^ \t\n]+ *\t*)+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
543     len = RLENGTH; st = RSTART;
544     code = substr(block, 1, len);
545     gsub(/(^|\n)(    |\t)/, "\n", code);
546     gsub(/^\n|\n+$/, "", code);
547     return "<pre><code>" HTML( code ) "</code></pre>\n" \
548            _block( substr( block, len + 1 ) );
549
550   # Fenced Divs (pandoc, custom)
551   } else if ( match( block, /^(:::+)/ ) ) {
552     guard = substr( block, 1, RLENGTH );
553     code = block; sub(/^[^\n]+\n/, "", code);
554     attrib = gensub(/^:::+[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\1", 1, block);
555     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
556     gsub(/(^ | $)/, "", attrib);
557     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
558       len = RLENGTH; st = RSTART;
559       return "<div class=\"" attrib "\">" _nblock( substr(code, 1, st - 1) ) "</div>\n" \
560              _block( substr( code, st + len ) );
561     } else {
562       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
563       len = RLENGTH; st = RSTART;
564       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
565              _block( substr(block, st + len) );
566     }
567
568   # Fenced Code Block (pandoc)
569   } else if ( match( block, /^(~~~+|```+)/ ) ) {
570     guard = substr( block, 1, RLENGTH );
571     code = gensub(/^[^\n]+\n/, "", 1, block);
572     attrib = gensub(/^(~~~+|```+)[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\2", 1, block);
573     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
574     gsub(/(^ | $)/, "", attrib);
575     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
576       len = RLENGTH; st = RSTART;
577       return "<pre><code class=\"" attrib "\">" HTML( substr(code, 1, st - 1) ) "</code></pre>\n" \
578              _block( substr( code, st + len ) );
579     } else {
580       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
581       len = RLENGTH; st = RSTART;
582       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
583              _block( substr(block, st + len) );
584     }
585
586   # First Order Heading H1 + Attrib
587   } else if ( match( block, /^([^\n]+)([ \t]*\{([^\}\n]+)\})\n===+(\n|$)/ ) ) {
588     len = RLENGTH; text = attrib = block;
589     sub(/([ \t]*\{([^\}\n]+)\})\n===+(\n.*)?$/, "", text);
590     sub(/\}\n===+(\n.*)?$/, "", attrib); sub(/^([^\n]+)[ \t]*\{/, "", attrib);
591     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib); gsub(/(^ | $)/, "", attrib);
592
593     return headline(1, text, attrib) _block( substr( block, len + 1 ) );
594
595   # First Order Heading H1
596   } else if ( match( block, /^([^\n]+)\n===+(\n|$)/ ) ) {
597     len = RLENGTH; text = substr(block, 1, len);
598     sub(/\n===+(\n.*)?$/, "", text);
599
600     return headline(1, text, 0) _block( substr( block, len + 1 ) );
601
602   # Second Order Heading H2 + Attrib
603   } else if ( match( block, /^([^\n]+)([ \t]*\{([^\}\n]+)\})\n---+(\n|$)/ ) ) {
604     len = RLENGTH; text = attrib = block;
605     sub(/([ \t]*\{([^\}\n]+)\})\n---+(\n.*)?$/, "", text);
606     sub(/\}\n---+(\n.*)?$/, "", attrib); sub(/^([^\n]+)[ \t]*\{/, "", attrib);
607     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib); gsub(/(^ | $)/, "", attrib);
608
609     return headline(2, text, attrib) _block( substr( block, len + 1) );
610
611   # Second Order Heading H2
612   } else if ( match( block, /^([^\n]+)\n---+(\n|$)/ ) ) {
613     len = RLENGTH; text = substr(block, 1, len);
614     sub(/\n---+(\n.*)?$/, "", text);
615
616     return headline(2, text, 0) _block( substr( block, len + 1) );
617
618   # Nth Order Heading H1 H2 H3 H4 H5 H6 + Attrib
619   } else if ( match( block, /^(#{1,6})[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[ \t]*[^ \t\n#])+)[ \t]*#*([ \t]*\{([a-zA-Z \t-]*)\})(\n|$)/ ) ) {
620     len = RLENGTH; text = attrib = substr(block, 1, len);
621     match(block, /^#{1,6}/); n = RLENGTH;
622
623     sub(/^(#{1,6})[ \t]*/, "", text);   sub(/[ \t]*#*([ \t]*\{([a-zA-Z \t-]*)\})(\n.*)?$/, "", text);
624     sub(/^(#{1,6})[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[ \t]*[^ \t\n#])+)[ \t]*#*[ \t]*\{/, "", attrib);
625     sub(/\})(\n.*)?$/, "", attrib);
626     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib); gsub(/(^ | $)/, "", attrib);
627
628     return headline( n, text, attrib ) _block( substr( block, len + 1) );
629
630   # Nth Order Heading H1 H2 H3 H4 H5 H6
631   } else if ( match( block, /^(#{1,6})[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[ \t]*[^ \t\n#])+)[ \t]*#*(\n|$)/ ) ) {
632     len = RLENGTH; text = substr(block, 1, len);
633     match(block, /^#{1,6}/); n = RLENGTH;
634     sub(/^(#{1,6})[ \t]*/, "", text); sub(/[ \t]*#*(\n.*)?$/, "", text);
635
636     return headline( n, text, 0 ) _block( substr( block, len + 1) );
637
638   # block images (wrapped in <figure>)
639   } else if ( match(block, /^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?(\n|$)/) ) {
640     len = RLENGTH;
641     text   = gensub(/^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?(\n.*)?$/, "\\1", "g", block);
642     href   = gensub(/^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?(\n.*)?$/, "\\2", "g", block);
643     title  = gensub(/^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?(\n.*)?$/, "\\4", "g", block);
644     attrib = gensub(/^!\[([^]]*)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)(\{([a-zA-Z \t-]*)\})?(\n.*)?$/, "\\6", "g", block);
645     if ( title && attrib ) {
646       return "<figure data-src=\"" URL(href, 1) "\" class=\"" HTML(attrib) "\">" \
647                "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\" class=\"" HTML(attrib) "\">" \
648                "<figcaption>" inline(title) "</figcaption>" \
649              "</figure>\n\n" \
650              _block( substr( block, len + 1) );
651     } else if ( title ) {
652       return "<figure data-src=\"" URL(href, 1) "\">" \
653                "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\">" \
654                "<figcaption>" inline(title) "</figcaption>" \
655              "</figure>\n\n" \
656              _block( substr( block, len + 1) );
657     } else if ( attrib ) {
658       return "<figure data-src=\"" URL(href, 1) "\" class=\"" HTML(attrib) "\">" \
659                "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\" class=\"" HTML(attrib) "\">" \
660              "</figure>\n\n" \
661              _block( substr( block, len + 1) );
662     } else {
663       return "<figure data-src=\"" URL(href, 1) "\">" \
664                "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\">" \
665              "</figure>\n\n" \
666              _block( substr( block, len + 1) );
667     }
668
669   # reference style images (block)
670   } else if ( match(line, /^!\[([^]]*)\] ?\[([^]]*)\](\n|$)/ ) ) {
671     len = RLENGTH;
672     text = gensub(/^!\[([^\n]*)\] ?\[([^\n]*)\](\n.*)?$/, "\\1", 1, block);
673       id = gensub(/^!\[([^\n]*)\] ?\[([^\n]*)\](\n.*)?$/, "\\2", 1, block);
674     if ( ! id ) id = text;
675     if ( rl_href[id] && rl_title[id] ) {
676       return "<figure data-src=\"" URL(rl_href[id], 1) "\">" \
677                "<img src=\"" URL(rl_href[id], 1) "\" alt=\"" HTML(text) "\">" \
678                "<figcaption>" inline(rl_title[id]) "</figcaption>" \
679              "</figure>\n\n" \
680              _block( substr( block, len + 1) );
681     } else if ( rl_href[id] ) {
682       return "<figure data-src=\"" URL(rl_href[id], 1) "\">" \
683                "<img src=\"" URL(rl_href[id], 1) "\" alt=\"" HTML(text) "\">" \
684              "</figure>\n\n" \
685              _block( substr( block, len + 1) );
686     } else {
687       return "<p>" HTML(substr(block, 1, len)) "</p>\n" _block( substr(block, len + 1) );
688     }
689
690   # Macros (standalone <<macro>> calls handled as block, so they are not wrapped in paragraph)
691   } else if ( AllowMacros && match( block, /^<<(([^>]|>[^>])+)>>(\n|$)/) ) {
692     len = RLENGTH;
693     text = gensub(/^<<(([^>]|>[^>])+)>>(\n.*)?$/, "\\1", 1, block);
694     return macro(text) _block(substr(block, len + 1) );
695
696   # Definition list
697   } else if (match( block, "^(([ \t]*\n)*[^:\n \t][^\n]+\n" \
698                            "([ \t]*\n)* ? ? ?:[ \t][^\n]+(\n|$)" \
699                           "(([ \t]*\n)* ? ? ?:[ \t][^\n]+(\n|$)" \
700                            "|[^:\n \t][^\n]+(\n|$)" \
701                            "|( ? ? ?\t|  +)[^\n]+(\n|$)" \
702                            "|([ \t]*\n)+( ? ? ?\t|  +)[^\n]+(\n|$))*)+" \
703   )) {
704     list = substr( block, 1, RLENGTH); block = substr( block, RLENGTH + 1);
705     return "\n<dl>\n" _dlist( list ) "</dl>\n" _block( block );
706
707   # Unordered list types
708   } else if ( text = _startlist( block, "ul", "-",   "([+*•]|[0-9]+\\.|#\\.|[0-9]+\\)|#\\))") ) {
709     return text;
710   } else if ( text = _startlist( block, "ul", "\\+", "([-*•]|[0-9]+\\.|#\\.|[0-9]+\\)|#\\))") ) {
711     return text;
712   } else if ( text = _startlist( block, "ul", "\\*", "([-+•]|[0-9]+\\.|#\\.|[0-9]+\\)|#\\))") ) {
713     return text;
714   } else if ( text = _startlist( block, "ul", "•", "([-+*]|[0-9]+\\.|#\\.|[0-9]+\\)|#\\))") ) {
715     return text;
716
717   # Ordered list types
718   } else if ( text = _startlist( block, "ol", "[0-9]+\\.", "([-+*•]|#\\.|[0-9]+\\)|#\\))") ) {
719     return text;
720   } else if ( text = _startlist( block, "ol", "[0-9]+\\)", "([-+*•]|[0-9]+\\.|#\\.|#\\))") ) {
721     return text;
722   } else if ( text = _startlist( block, "ol", "#\\.", "([-+*•]|[0-9]+\\.|[0-9]+\\)|#\\))") ) {
723     return text;
724   } else if ( text = _startlist( block, "ol", "#\\)", "([-+*•]|[0-9]+\\.|#\\.|[0-9]+\\))") ) {
725     return text;
726
727   # Split paragraphs
728   } else if ( match( block, /(^|\n)[[:space:]]*(\n|$)/) ) {
729     len = RLENGTH; st = RSTART;
730     return _block( substr(block, 1, st - 1) ) "\n" \
731            _block( substr(block, st + len) );
732
733   # Horizontal rule
734   } else if ( match( block, /(^|\n) ? ? ?((\* *){3,}|(- *){3,}|(_ *){3,})($|\n)/) ) {
735     len = RLENGTH; st = RSTART;
736     return _block(substr(block, 1, st - 1)) "<hr>\n" _block(substr(block, st + len));
737
738   # Plain paragraph
739   } else {
740     return "<p>" inline(block) "</p>\n";
741   }
742 }
743
744 function _startlist(block, type, mark, exclude, LOCAL, st, len, list, indent, text) {
745   if (match( block, "(^|\n) ? ? ?" mark "[ \t][^\n]+(\n|$)" \
746                                    "(([ \t]*\n)* ? ? ?" mark "[ \t][^\n]+(\n|$)" \
747                                    "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
748                                    "|[^\n \t][^\n]+(\n|$))*" ) ) {
749     st = RSTART; len = RLENGTH; list = substr( block, st, len);
750
751     sub("^\n", "", list); match(list, "^ ? ? ?"); indent = RLENGTH;
752     gsub( "(^|\n) {0," indent "}", "\n", list); sub("^\n", "", list);
753
754     text = substr(block, 1, st - 1); block = substr(block, st + len);
755     if (match(text, /\n[[:space:]]*\n/)) return 0;
756     if (match(text, "(^|\n) ? ? ?" exclude "[ \t][^\n]+")) return 0;
757     if (match( list, "\n" exclude "[ \t]" )) {
758       block = substr(list, RSTART + 1) block;
759       list = substr(list, 1, RSTART);
760     }
761
762     return _block( text ) "<" type ">\n" _list( list, mark ) "</" type ">\n" _block( block );
763   } else return 0;
764 }
765
766 function _list (block, mark, p, LOCAL, len, st, text, indent, task) {
767   if ( match(block, "^([ \t]*\n)*$")) return;
768
769   match(block, "^" mark "[ \t]"); indent = RLENGTH;
770   sub("^" mark "[ \t]", "", block);
771
772   if (match(block, /\n[ \t]*\n/)) p = 1;
773
774   match( block, "\n" mark "[ \t][^\n]+(\n|$)" );
775   st = (RLENGTH == -1) ? length(block) + 1 : RSTART;
776   text = substr(block, 1, st); block = substr(block, st + 1);
777
778   gsub("\n {0," indent "}", "\n", text);
779
780   task = match( text, /^\[ \]/   ) ? "<li class=\"task pending\"><input type=checkbox disabled>"      : \
781          match( text, /^\[-\]/   ) ? "<li class=\"task negative\"><input type=checkbox disabled>"     : \
782          match( text, /^\[\/\]/  ) ? "<li class=\"task partial\"><input type=checkbox disabled>"      : \
783          match( text, /^\[\?\]/  ) ? "<li class=\"task unsure\"><input type=checkbox disabled>"       : \
784          match( text, /^\[[xX]\]/) ? "<li class=\"task done\"><input type=checkbox disabled checked>" : "<li>";
785   sub(/^\[[-? \/xX]\]/, "", text);
786
787   text = _nblock( text );
788   if ( ! p && match( text, "^<p>(</p[^>]|</[^p]|<[^/]|[^<])*</p>\n$" ))
789      gsub( "(^<p>|</p>\n$)", "", text);
790
791   return task text "</li>\n" _list(block, mark, p);
792 }
793
794 function _dlist (block, LOCAL, len, st, text, indent, p) {
795   if (match( block, "^([ \t]*\n)*[^:\n \t][^\n]+\n" )) {
796     len = RLENGTH; text = substr(block, 1, len);
797     gsub( "(^\n*|\n*$)", "", text );
798     return "<dt>" inline( text ) "</dt>\n" _dlist( substr(block, len + 1) );
799   } else if (match( block, "^([ \t]*\n)* ? ? ?:[ \t][^\n]+(\n|$)" \
800                          "([^:\n \t][^\n]+(\n|$)" \
801                          "|( ? ? ?\t|  +)[^\n]+(\n|$)" \
802                          "|([ \t]*\n)+( ? ? ?\t|  +)[^\n]+(\n|$))*" \
803   )) {
804     len = RLENGTH; text = substr(block, 1, len);
805     sub( "^([ \t]*\n)*", "", text);
806     match(text, "^ ? ? ?:(\t| +)"); indent = RLENGTH;
807     sub( "^ ? ? ?:(\t| +)", "", text);
808     gsub( "(^|\n) {0," indent "}", "\n", text );
809
810     text = _nblock(text);
811     if (match( text, "^<p>(</p[^>]|</[^p]|<[^/]|[^<])*</p>\n$" ))
812        gsub( "(^<p>|</p>\n$)", "", text);
813
814     return "<dd>" text "</dd>\n" _dlist( substr(block, len + 1) );
815   }
816 }
817
818 BEGIN {
819   # Global Vars
820   file = ""; rl_href[""] = ""; rl_title[""] = "";
821   if (ENVIRON["MD_HTML"] == "true") { AllowHTML = "true"; }
822   HL[1] = 0; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
823   # hls = "0 0 0 0 0 0";
824
825   # Buffering of full file ist necessary, e.g. to find reference links
826   while (getline) { file = file $0 "\n"; }
827   # Clean up MS-DOS line breaks
828   gsub(/\r\n/, "\n", file);
829
830   # Fill array of reference links
831   f = file; rl_id;
832   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
833   # /(^|\n) ? ? ?\[([^]\n]+)\]: ([^ \t\n]+)(\n?[ \t]+("([^"]+)"|'([^']+)'|\(([^)]+)\)))?(\n|$)/
834   while ( match(f, re_reflink ) ) {
835     rl_id           = gensub( re_reflink, "\\2", 1, substr(f, RSTART, RLENGTH) );
836     rl_href[rl_id]  = gensub( re_reflink, "\\3", 1, substr(f, RSTART, RLENGTH) );
837     rl_title[rl_id] = gensub( re_reflink, "\\5", 1, substr(f, RSTART, RLENGTH) );
838     f = substr(f, RSTART + RLENGTH);
839     rl_title[rl_id] = substr( rl_title[rl_id], 2, length(rl_title[rl_id]) - 2 );
840     if ( rl_href[rl_id] ~ /<.*>/ ) rl_href[rl_id] = substr( rl_href[rl_id], 2, length(rl_href[rl_id]) - 2 );
841   }
842   # Clear reflinks from File
843   while( gsub(re_reflink, "\n", file ) );
844   # for (n in rl_href) { debug(n " | " rl_href[n] " | " rl_title[n] ); }
845
846   # Run Block Processing -> The Actual Markdown!
847   printf "%s", _nblock( file );
848 }