]> git.plutz.net Git - cgilite/blob - markdown.awk
link and image syntax allowing whitespace URLs, repace use of non-posix gensub()
[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   if ( line ~ /^$/ ) {  # Recursion End
126     return "";
127
128   # omit processing of escaped characters
129   } else if ( line ~ /^\\./) {
130     return HTML(substr(line, 2, 1)) inline( substr(line, 3) );
131
132   # hard brakes
133   } else if ( match(line, /^  \n/) ) {
134     return "<br>\n" inline( substr(line, RLENGTH + 1) );
135
136   #  ``code spans``
137   } else if ( match( line, /^`+/) ) {
138     len = RLENGTH
139     guard = substr( line, 1, len )
140     if ( match(line, guard ".*" guard) ) {
141       code = substr( line, len + 1, match( substr(line, len + 1), guard ) - 1)
142       len = 2 * length(guard) + length(code)
143       #  strip single surrounding white spaces
144       gsub( /^ | $/, "", code)
145       #  escape HTML within code span
146       gsub( /&/, "\\&amp;", code ); gsub( /</, "\\&lt;", code ); gsub( />/, "\\&gt;", code );
147       return "<code>" code "</code>" inline( substr( line, len + 1 ) )
148     }
149
150   # Macros
151   } else if ( match( line, /^<<([^>]|>[^>])+>>/ ) ) {
152     len = RLENGTH;
153     return "<code class=\"macro\">" HTML( substr( line, 3, len - 4 ) ) "</code>" inline(substr(line, len + 1));
154
155   # Wiki style links
156   } else if ( match( line, /^\[\[([^]|]+)(\|[^]]+)?\]\]/) ) {
157     len = RLENGTH;
158     href = gensub(/^\[\[([^]|]+)(\|([^]]+))?\]\]/, "\\1", 1, substr(line, 1, len) );
159     text = gensub(/^\[\[([^]|]+)(\|([^]]+))?\]\]/, "\\3", 1, substr(line, 1, len) );
160     if ( ! text ) text = href;
161     return "<a href=\"" URL(href) "\">" HTML(text) "</a>" inline( substr( line, len + 1) );
162
163   #  quick links ("automatic links" in md doc)
164   } else if ( match( line, /^<[a-zA-Z]+:\/\/([-\.[:alnum:]]+)(:[0-9]*)?(\/[^>]*)?>/ ) ) {
165     len = RLENGTH;
166     href = URL( substr( line, 2, len - 2) );
167     return "<a href=\"" href "\">" href "</a>" inline( substr( line, len + 1) );
168
169   # quick link email
170   } 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])?)*>/ ) ) {
171     len = RLENGTH;
172     href = URL( substr( line, 2, len - 2) );
173     return "<a href=\"mailto:" href "\">" href "</a>" inline( substr( line, len + 1) );
174
175   # Verbatim inline HTML
176   } 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:]]*\/?>)/) ) {
177     len = RLENGTH;
178     return substr( line, 1, len) inline(substr(line, len + 1));
179
180   # inline links
181   } else if ( match(line, "^" lii "\\([\\n\\t ]*" lid "([\\n\\t ]+" lit ")?[\\n\\t ]*\\)") ) {
182     len = RLENGTH;
183     text = href = title = substr( line, 1, len);
184     sub("^\\[", "", text); sub("\\]\\([\\n\\t ]*" lid "([\\n\\t ]+" lit ")?[\\n\\t ]*\\)$", "", text);
185     sub("^" lii "\\([\\n\\t ]*", "", href); sub("([\\n\\t ]+" lit ")?[\\n\\t ]*\\)$", "", href);
186     sub("^" lii "\\([\\n\\t ]*" lid, "", title); sub("[\\n\\t ]*\\)$", "", title); sub("^[\\n\\t ]+", "", title);
187
188     if ( match(href, /^<.*>$/) ) { sub(/^</, "", href); sub(/>$/, "", href); }
189          if ( match(title, /^".*"$/) ) { sub(/^"/, "", title); sub(/"$/, "", title); }
190     else if ( match(title, /^'.*'$/) ) { sub(/^'/, "", title); sub(/'$/, "", title); }
191     else if ( match(title, /^\(.*\)$/) ) { sub(/^\(/, "", title); sub(/\)$/, "", title); }
192
193     gsub(/\\/, "", href); gsub(/\\/, "", title); gsub(/[\n\t]+/, " ", title);
194
195     return "<a href=\"" URL(href) "\"" (title?" title=\"" HTML(title) "\"":"") ">" \
196            inline( text ) "</a>" inline( substr( line, len + 1) );
197
198   # reference style links
199   } else if ( match(line, /^\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
200     len = RLENGTH;
201     text = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, substr(line, 1, len) );
202       id = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, substr(line, 1, len) );
203     if ( ! id ) id = text;
204     if ( rl_href[id] && rl_title[id] ) {
205       return "<a href=\"" URL(rl_href[id]) "\" title=\"" HTML(rl_title[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
206     } else if ( rl_href[id] ) {
207       return "<a href=\"" URL(rl_href[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
208     } else {
209       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
210     }
211
212   # inline images
213   } else if ( match(line, "^!" lix "\\([\\n\\t ]*" lid "([\\n\\t ]+" lit ")?[\\n\\t ]*\\)(\\{[a-zA-Z \\t-]*\\})?") ) {
214     len = RLENGTH; text = href = title = attrib = substr( line, 1, len);
215
216     sub("^!\\[", "", text);
217     sub("\\]\\([\\n\\t ]*" lid "([\\n\\t ]+" lit ")?[\\n\\t ]*\\)(\\{[a-zA-Z \\t-]*\\})?$", "", text);
218
219     sub("^!" lix "\\([\\n\\t ]*", "", href);
220     sub("([\\n\\t ]+" lit ")?[\\n\\t ]*\\)(\\{[a-zA-Z \\t-]*\\})?$", "", href);
221
222     sub("^!" lix "\\([\\n\\t ]*" lid, "", title);
223     sub("[\\n\\t ]*\\)(\\{[a-zA-Z \\t-]*\\})?$", "", title);
224     sub("^[\\n\\t ]+", "", title);
225
226     sub("^!" lix "\\([\\n\\t ]*" lid "([\\n\\t ]+" lit ")?[\\n\\t ]*\\)", "", attrib);
227     sub(/^\{[ \t]*/, "", attrib); sub(/[ \t]*\}$/, "", attrib); gsub(/[ \t]+/, " ", attrib);
228
229     if ( match(href, /^<.*>$/) ) { sub(/^</, "", href); sub(/>$/, "", href); }
230          if ( match(title, /^".*"$/) ) { sub(/^"/, "", title); sub(/"$/, "", title); }
231     else if ( match(title, /^'.*'$/) ) { sub(/^'/, "", title); sub(/'$/, "", title); }
232     else if ( match(title, /^\(.*\)$/) ) { sub(/^\(/, "", title); sub(/\)$/, "", title); }
233
234     gsub(/\\/, "", href); gsub(/\\/, "", title); gsub(/[\n\t]+/, " ", title);
235
236     return "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\"" \
237            (title?" title=\"" HTML(title) "\"":"") (attrib?" class=\"" HTML(attrib) "\"":"") \
238            ">" inline( substr( line, len + 1) );
239
240   # reference style images
241   } else if ( match(line, /^!\[([^]]*)\] ?\[([^]]*)\]/ ) ) {
242     len = RLENGTH;
243     text = gensub(/^!\[([^\n]*)\] ?\[([^\n]*)\].*/, "\\1", 1, substr(line, 1, len) );
244       id = gensub(/^!\[([^\n]*)\] ?\[([^\n]*)\].*/, "\\2", 1, substr(line, 1, len) );
245     if ( ! id ) id = text;
246     if ( rl_href[id] && rl_title[id] ) {
247       return "<img src=\"" URL(rl_href[id], 1) "\" alt=\"" HTML(text) "\" title=\"" HTML(rl_title[id]) "\">" \
248              inline( substr( line, len + 1) );
249     } else if ( rl_href[id] ) {
250       return "<img src=\"" URL(rl_href[id], 1) "\" alt=\"" HTML(text) "\">" \
251              inline( substr( line, len + 1) );
252     } else {
253       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
254     }
255
256   #  ~~strikeout~~ (pandoc)
257   } else if ( match(line, /^~~([[:graph:]]|[[:graph:]]([^~]|~[^~])*[[:graph:]])~~/) ) {
258     len = RLENGTH;
259     return "<del>" inline( substr( line, 3, len - 4 ) ) "</del>" inline( substr( line, len + 1 ) );
260
261   #  ^superscript^ (pandoc)
262   } else if ( match(line, /^\^([^[:space:]^]|\\[ ^])+\^/) ) {
263     len = RLENGTH;
264     return "<sup>" inline( substr( line, 2, len - 2 ) ) "</sup>" inline( substr( line, len + 1 ) );
265
266   #  ~subscript~ (pandoc)
267   } else if ( match(line, /^~([^[:space:]~]|\\[ ~])+~/) ) {
268     len = RLENGTH;
269     return "<sub>" inline( substr( line, 2, len - 2 ) ) "</sub>" inline( substr( line, len + 1 ) );
270
271   # ignore embedded underscores (pandoc, php md)
272   } else if ( match(line, "^[[:alnum:]](__|_)") ) {
273     return HTML(substr( line, 1, RLENGTH)) inline( substr(line, RLENGTH + 1) );
274
275   #  __strong__$
276   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__$") ) {
277     len = RLENGTH;
278     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
279
280   #  __strong__
281   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__[[:space:][:punct:]]") ) {
282     len = RLENGTH;
283     return "<strong>" inline( substr( line, 3, len - 5 ) ) "</strong>" inline( substr( line, len) );
284
285   #  **strong**
286   } else if ( match(line, "^\\*\\*(([^\\*[:space:]]|" iea ")|([^\\*[:space:]]|" iea ")(" na "|" iea ")*([^\\*[:space:]]|" iea "))\\*\\*") ) {
287     len = RLENGTH;
288     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
289
290   #  _em_$
291   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_$") ) {
292     len = RLENGTH;
293     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
294
295   #  _em_
296   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_[[:space:][:punct:]]") ) {
297     len = RLENGTH;
298     return "<em>" inline( substr( line, 2, len - 3 ) ) "</em>" inline( substr( line, len ) );
299
300   #  *em*
301   } else if ( match(line, "^\\*(([^\\*[:space:]]|" isa ")|([^\\*[:space:]]|" isa ")(" na "|" isa ")*([^\\*[:space:]]|" isa "))\\*") ) {
302     len = RLENGTH;
303     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
304
305   # Literal HTML entities
306   } else if ( match( line, /^&([a-zA-Z]{2,32}|#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});/) ) {
307     len = RLENGTH;
308     return substr( line, 1, len ) inline(substr(line, len + 1));
309
310   # Arrows
311   } else if ( line ~ /^-->( |$)/) {  # ignore multidash-arrow
312     return "--&gt;" inline( substr(line, 4) );
313   } else if ( line ~ /^<-( |$)/) {
314     return "&larr;" inline( substr(line, 3) );
315   } else if ( line ~ /^->( |$)/) {
316     return "&rarr;" inline( substr(line, 3) );
317
318   # Escape lone HTML character
319   } else if ( match( line, /^[&<>"']/) ) {
320     return HTML(substr(line, 1, 1)) inline(substr(line, 2));
321
322   #  continue walk over string
323   } else {
324     return substr(line, 1, 1) inline( substr(line, 2) );
325   }
326 }
327
328 function headline( hlvl, htxt, attrib, LOCAL, sec, n, HL) {
329   match(hstack, /([0-9]+( [0-9]+){5})$/); split( substr(hstack, RSTART),  HL);
330
331   for ( n = hlvl; n <= 6; n++ ) { sec = sec (HL[n]?"</section>":""); }
332   HL[hlvl]++; for ( n = hlvl + 1; n <= 6; n++) { HL[n] = 0;}
333
334   hid = ""; for ( n = 2; n <= blvl; n++) { hid = hid BL[n] "/"; }
335   hid = hid HL[1]; for ( n = 2; n <= hlvl; n++) { hid = hid "." HL[n] ; }
336   hid = hid ":" URL(htxt, 1);
337
338   sub(/([0-9]+( [0-9]+){5})$/, "", hstack);
339   hstack = hstack HL[1] " " HL[2] " " HL[3] " " HL[4] " " HL[5] " " HL[6];
340
341   return sec "<section class=\"" (attrib ? "h" hlvl " " attrib : "h" hlvl)  "\" id=\"" hid "\">" \
342          "<h" hlvl (attrib ? " class=\"" attrib "\"" : "") ">" inline( htxt ) \
343          "<a class=\"anchor\" href=\"#" hid "\"></a>" \
344          "</h" hlvl ">\n";
345 }
346
347 # Nested Block, resets heading counters
348 function _nblock( block, LOCAL, sec, n ) {
349   hstack = hstack " 0 0 0 0 0 0";
350
351   # Block Level
352   blvl++; BL[blvl]++;
353   for ( n = blvl + 1; n in BL; n++) { delete BL[n]; }
354
355   block = _block( block );
356   match(hstack, /([0-9]+( [0-9]+){5})$/); split( substr(hstack, RSTART),  HL);
357   sec = ""; for ( n = 1; n <= 6; n++ ) { sec = sec (HL[n]?"</section>":""); }
358
359   sub("( +[0-9]+){6} *$", "", hstack); blvl--;
360   return block sec;
361 }
362
363 function _block( block, LOCAL, st, len, text, title, attrib, href, guard, code, indent, list ) {
364   gsub( "(^\n+|\n+$)", "", block );
365
366   if ( block == "" ) {
367     return "";
368
369   # HTML #2 #3 #4 $5
370   } else if ( AllowHTML && match( block, /(^|\n) ? ? ?(<!--([^-]|-[^-]|--[^>])*(-->|$)|<\?([^\?]|\?[^>])*(\?>|$)|<![A-Z][^>]*(>|$)|<!\[CDATA\[([^\]]|\][^\]]|\]\][^>])*(\]\]>|$))/) ) {
371     len = RLENGTH; st = RSTART;
372     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
373
374   # HTML #6
375   } 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|$)/) ) {
376     len = RLENGTH; st = RSTART;
377     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
378
379   # HTML #1
380   } else if ( AllowHTML && match( tolower(block), /(^|\n) ? ? ?<(script|pre|style)([[:space:]\n>]).*(<\/script>|<\/pre>|<\/style>|$)/) ) {
381     len = RLENGTH; st = RSTART;
382     match( tolower(substr(block, st, len)), /(<\/script>|<\/pre>|<\/style>)/);
383     len = RSTART + RLENGTH;
384     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
385
386   # HTML #7
387   } 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|$)/) ) {
388     len = RLENGTH; st = RSTART;
389     return substr(block, st, len) _block(substr(block, st + len));
390
391   # Metadata (custom, block starting with %something)
392   # Metadata is ignored but can be interpreted externally
393   } else if ( match(block, /^%[a-zA-Z]+([[:space:]][^\n]*)?(\n|$)(%[a-zA-Z]+([[:space:]][^\n]*)?(\n|$)|%([[:space:]][^\n]*)?(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
394     len = RLENGTH; st = RSTART;
395     return  _block( substr( block, len + 1) );
396  
397   # Blockquote (leading >)
398   } else if ( match( block, /^> /) ) {
399     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
400     len = RLENGTH; st = RSTART;
401     text = substr(block, 1, st - 1); gsub( /(^|\n)> /, "\n", text );
402     text = _nblock( text ); gsub( /^\n|\n$/, "", text )
403     return "<blockquote>" text "</blockquote>\n\n" _block( substr(block, st + len) );
404
405   # Pipe Tables (pandoc / php md / gfm )
406   } else if ( match(block, "^((\\|)?([^\n]+\\|)+[^\n]+(\\|)?)\n" \
407                            "((\\|)?(:?-+:?[\\|+])+:?-+:?(\\|)?)\n" \
408                            "((\\|)?([^\n]+\\|)+[^\n]+(\\|)?(\n|$))+" ) ) {
409     len = RLENGTH; st = RSTART;
410     #initialize empty arrays
411     split("", talign); split("", tarray);
412     cols = 0; cnt=0; ttext = "";
413
414     # table header and alignment
415     split( gensub( /(^\||\|$)/, "", "g", \
416            gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
417            substr(block, 1, match(block, /(\n|$)/)) \
418     )), tarray, /\|/);
419     block = substr(block, match(block, /(\n|$)/) + 1 );
420     cols = split( \
421            gensub( /(^\||\|$)/, "", "g", \
422            substr(block, 1, match(block, /(\n|$)/)) \
423     ), talign, /[+\|]/);
424     block = substr(block, match(block, /(\n|$)/) + 1 );
425
426     for( cnt = 1; cnt < cols; cnt++ ) {
427            if (match(talign[cnt], /:-+:/)) talign[cnt]="center";
428       else if (match(talign[cnt],  /-+:/)) talign[cnt]="right";
429       else if (match(talign[cnt],  /:-+/)) talign[cnt]="left";
430       else talign[cnt]="";
431     }
432
433     ttext = "<thead>\n<tr>"
434     for (cnt = 1; cnt < cols; cnt++)
435       ttext = ttext "<th align=\"" talign[cnt] "\">" inline(tarray[cnt]) "</th>"
436     ttext = ttext "</tr>\n</thead><tbody>\n"
437
438     while ( match(block, "^((\\|)?([^\n]+\\|)+[^\n]+(\\|)?(\n|$))+" ) ){
439       split( gensub( /(^\||\|$)/, "", "g", \
440              gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
441              substr(block, 1, match(block, /(\n|$)/)) \
442       )), tarray, /\|/);
443       block = substr(block, match(block, /(\n|$)/) + 1 );
444
445       ttext = ttext "<tr>"
446       for (cnt = 1; cnt < cols; cnt++)
447         ttext = ttext "<td align=\"" talign[cnt] "\">" inline(tarray[cnt]) "</td>"
448       ttext = ttext "</tr>\n"
449     }
450     return "<table>" ttext "</tbody></table>\n" _block(block);
451
452   # Grid Tables (pandoc)
453   # (with, and without header)
454   } else if ( match( block, "^\\+(-+\\+)+\n" \
455                             "(\\|([^\n]+\\|)+\n)+" \
456                             "(\\+(:?=+:?\\+)+)\n" \
457                            "((\\|([^\n]+\\|)+\n)+" \
458                              "\\+(-+\\+)+(\n|$))+" \
459                    ) || \
460               match( block, "^()()()" \
461                             "(\\+(:?-+:?\\+)+)\n" \
462                            "((\\|([^\n]+\\|)+\n)+" \
463                              "\\+(-+\\+)+(\n|$))+" \
464   ) ) {
465     len = RLENGTH; st = RSTART;
466     #initialize empty arrays
467     split("", talign); split("", tarray); split("", tread);
468     cols = 0; cnt=0; ttext = "";
469
470     # Column Count
471     cols = split(   gensub( "^(\\+(:?-+:?\\+)+)(\n.*)*$", "\\1", 1, block), tread, /\+/) - 2;
472     # debug(" Cols: " gensub( "^(\\+(:?-+:?\\+)+)(\n.*)*$", "\\1", 1, block ));
473
474     # table alignment
475     split( gensub( "^(.*\n)?\\+((:?=+:?\\+|(:-+|-+:|:-+:)\\+)+)(\n.*)$", "\\2", "g", block ), talign, /\+/ );
476     # debug("Align: " gensub( "^(.*\n)?\\+((:?=+:?\\+|(:-+|-+:|:-+:)\\+)+)(\n.*)$", "\\2", "g", block ));
477
478     for (cnt = 1; cnt <= cols; cnt++) {
479            if (match(talign[cnt], /:(-+|=+):/)) talign[cnt]="center";
480       else if (match(talign[cnt],  /(-+|=+):/)) talign[cnt]="right";
481       else if (match(talign[cnt], /:(-+|=+)/ )) talign[cnt]="left";
482       else talign[cnt]="";
483     }
484
485     if ( match(block, "^\\+(-+\\+)+\n" \
486                       "(\\|([^\n]+\\|)+\n)+" \
487                        "\\+(:?=+:?\\+)+\n" \
488                      "((\\|([^\n]+\\|)+\n)+" \
489                        "\\+(-+\\+)+(\n|$))+" \
490     ) ) {
491       # table header
492       block = substr(block, match(block, /(\n|$)/) + 1 );
493       while ( match(block, "^\\|([^\n]+\\|)+\n") ) {
494         split( gensub( /(^\||\|$)/, "", "g", \
495                  gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
496                    substr(block, 1, match(block, /(\n|$)/)) \
497         )), tread, /\|/);
498         block = substr(block, match(block, /(\n|$)/) + 1 );
499         for (cnt = 1; cnt <= cols; cnt++)
500           tarray[cnt] = tarray[cnt] "\n" tread[cnt];
501       }
502
503       ttext = "<thead>\n<tr>"
504       for (cnt = 1; cnt <= cols; cnt++)
505         ttext = ttext "<th align=\"" talign[cnt] "\">" _nblock(tarray[cnt]) "</th>"
506       ttext = ttext "</tr>\n</thead>"
507     }
508
509     # table body
510     block = substr(block, match(block, /(\n|$)/) + 1 );
511     ttext = ttext "<tbody>\n"
512
513     while ( match(block, /^((\|([^\n]+\|)+\n)+\+(-+\+)+(\n|$))+/ ) ){
514       split("", tarray);
515       while ( match(block, /^\|([^\n]+\|)+\n/) ) {
516         split( gensub( /(^\||\|$)/, "", "g", \
517                gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
518                substr(block, 1, match(block, /(\n|$)/)) \
519         )), tread, /\|/);
520         block = substr(block, match(block, /(\n|$)/) + 1 );
521         for (cnt = 1; cnt <= cols; cnt++)
522           tarray[cnt] = tarray[cnt] "\n" tread[cnt];
523       }
524       block = substr(block, match(block, /(\n|$)/) + 1 );
525
526       ttext = ttext "<tr>"
527       for (cnt = 1; cnt <= cols; cnt++)
528         ttext = ttext "<td align=\"" talign[cnt] "\">" _nblock(tarray[cnt]) "</td>"
529       ttext = ttext "</tr>\n"
530     }
531     return "<table>" ttext "</tbody></table>\n" _nblock(block);
532
533   # Line Blocks (pandoc)
534   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
535     len = RLENGTH; st = RSTART;
536
537     text = substr(block, 1, len); gsub(/\n[[:space:]]+/, " ", text);
538     gsub(/\n\| /, "\n", text); gsub(/^\| |\n$/, "", text);
539     text = inline(text); gsub(/\n/, "<br>\n", text);
540
541     return "<div class=\"line-block\">" text "</div>\n" _block( substr( block, len + 1) );
542
543   # Indented Code Block
544   } else if ( match(block, /^(    |\t)( *\t*[^ \t\n]+ *\t*)+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
545     len = RLENGTH; st = RSTART;
546     code = substr(block, 1, len);
547     gsub(/(^|\n)(    |\t)/, "\n", code);
548     gsub(/^\n|\n+$/, "", code);
549     return "<pre><code>" HTML( code ) "</code></pre>\n" \
550            _block( substr( block, len + 1 ) );
551
552   # Fenced Divs (pandoc, custom)
553   } else if ( match( block, /^(:::+)/ ) ) {
554     guard = substr( block, 1, RLENGTH );
555     code = block; sub(/^[^\n]+\n/, "", code);
556     attrib = gensub(/^:::+[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\1", 1, block);
557     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
558     gsub(/(^ | $)/, "", attrib);
559     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
560       len = RLENGTH; st = RSTART;
561       return "<div class=\"" attrib "\">" _nblock( substr(code, 1, st - 1) ) "</div>\n" \
562              _block( substr( code, st + len ) );
563     } else {
564       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
565       len = RLENGTH; st = RSTART;
566       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
567              _block( substr(block, st + len) );
568     }
569
570   # Fenced Code Block (pandoc)
571   } else if ( match( block, /^(~~~+|```+)/ ) ) {
572     guard = substr( block, 1, RLENGTH );
573     code = gensub(/^[^\n]+\n/, "", 1, block);
574     attrib = gensub(/^(~~~+|```+)[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\2", 1, block);
575     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
576     gsub(/(^ | $)/, "", attrib);
577     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
578       len = RLENGTH; st = RSTART;
579       return "<pre><code class=\"" attrib "\">" HTML( substr(code, 1, st - 1) ) "</code></pre>\n" \
580              _block( substr( code, st + len ) );
581     } else {
582       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
583       len = RLENGTH; st = RSTART;
584       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
585              _block( substr(block, st + len) );
586     }
587
588   # First Order Heading H1 + Attrib
589   } else if ( match( block, /^([^\n]+)([ \t]*\{([^\}\n]+)\})\n===+(\n|$)/ ) ) {
590     len = RLENGTH; text = attrib = block;
591     sub(/([ \t]*\{([^\}\n]+)\})\n===+(\n.*)?$/, "", text);
592     sub(/\}\n===+(\n.*)?$/, "", attrib); sub(/^([^\n]+)[ \t]*\{/, "", attrib);
593     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib); gsub(/(^ | $)/, "", attrib);
594
595     return headline(1, text, attrib) _block( substr( block, len + 1 ) );
596
597   # First Order Heading H1
598   } else if ( match( block, /^([^\n]+)\n===+(\n|$)/ ) ) {
599     len = RLENGTH; text = substr(block, 1, len);
600     sub(/\n===+(\n.*)?$/, "", text);
601
602     return headline(1, text, 0) _block( substr( block, len + 1 ) );
603
604   # Second Order Heading H2 + Attrib
605   } else if ( match( block, /^([^\n]+)([ \t]*\{([^\}\n]+)\})\n---+(\n|$)/ ) ) {
606     len = RLENGTH; text = attrib = block;
607     sub(/([ \t]*\{([^\}\n]+)\})\n---+(\n.*)?$/, "", text);
608     sub(/\}\n---+(\n.*)?$/, "", attrib); sub(/^([^\n]+)[ \t]*\{/, "", attrib);
609     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib); gsub(/(^ | $)/, "", attrib);
610
611     return headline(2, text, attrib) _block( substr( block, len + 1) );
612
613   # Second Order Heading H2
614   } else if ( match( block, /^([^\n]+)\n---+(\n|$)/ ) ) {
615     len = RLENGTH; text = substr(block, 1, len);
616     sub(/\n---+(\n.*)?$/, "", text);
617
618     return headline(2, text, 0) _block( substr( block, len + 1) );
619
620   # Nth Order Heading H1 H2 H3 H4 H5 H6 + Attrib
621   } else if ( match( block, /^(#{1,6})[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[ \t]*[^ \t\n#])+)[ \t]*#*([ \t]*\{([a-zA-Z \t-]*)\})(\n|$)/ ) ) {
622     len = RLENGTH; text = attrib = substr(block, 1, len);
623     match(block, /^#{1,6}/); n = RLENGTH;
624
625     sub(/^(#{1,6})[ \t]*/, "", text);   sub(/[ \t]*#*([ \t]*\{([a-zA-Z \t-]*)\})(\n.*)?$/, "", text);
626     sub(/^(#{1,6})[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[ \t]*[^ \t\n#])+)[ \t]*#*[ \t]*\{/, "", attrib);
627     sub(/\})(\n.*)?$/, "", attrib);
628     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib); gsub(/(^ | $)/, "", attrib);
629
630     return headline( n, text, attrib ) _block( substr( block, len + 1) );
631
632   # Nth Order Heading H1 H2 H3 H4 H5 H6
633   } else if ( match( block, /^(#{1,6})[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[ \t]*[^ \t\n#])+)[ \t]*#*(\n|$)/ ) ) {
634     len = RLENGTH; text = substr(block, 1, len);
635     match(block, /^#{1,6}/); n = RLENGTH;
636     sub(/^(#{1,6})[ \t]*/, "", text); sub(/[ \t]*#*(\n.*)?$/, "", text);
637
638     return headline( n, text, 0 ) _block( substr( block, len + 1) );
639
640   # block images (wrapped in <figure>)
641   } else if ( match(block, "^!" lix "\\([\\n\\t ]*" lid "([\\n\\t ]+" lit ")?[\\n\\t ]*\\)(\\{[a-zA-Z \\t-]*\\})?(\\n|$)") ) {
642     len = RLENGTH; text = href = title = attrib = substr( block, 1, len);
643
644     sub("^!\\[", "", text);
645     sub("\\]\\([\\n\\t ]*" lid "([\\n\\t ]+" lit ")?[\\n\\t ]*\\)(\\{[a-zA-Z \\t-]*\\})?(\\n.*)?$", "", text);
646
647     sub("^!" lix "\\([\\n\\t ]*", "", href);
648     sub("([\\n\\t ]+" lit ")?[\\n\\t ]*\\)(\\{[a-zA-Z \\t-]*\\})?(\\n.*)?$", "", href);
649
650     sub("^!" lix "\\([\\n\\t ]*" lid, "", title);
651     sub("[\\n\\t ]*\\)(\\{[a-zA-Z \\t-]*\\})?(\\n.*)?$", "", title);
652     sub("^[\\n\\t ]+", "", title);
653
654     sub("^!" lix "\\([\\n\\t ]*" lid "([\\n\\t ]+" lit ")?[\\n\\t ]*\\)", "", attrib);
655     sub("(\\n.*)?$", "", attrib);
656     sub(/^\{[ \t]*/, "", attrib); sub(/[ \t]*\}$/, "", attrib); gsub(/[ \t]+/, " ", attrib);
657
658     if ( match(href, /^<.*>$/) ) { sub(/^</, "", href); sub(/>$/, "", href); }
659          if ( match(title, /^".*"$/) ) { sub(/^"/, "", title); sub(/"$/, "", title); }
660     else if ( match(title, /^'.*'$/) ) { sub(/^'/, "", title); sub(/'$/, "", title); }
661     else if ( match(title, /^\(.*\)$/) ) { sub(/^\(/, "", title); sub(/\)$/, "", title); }
662
663     gsub(/\\/, "", href);
664
665     return "<figure data-src=\"" URL(href, 1) "\"" (attrib?" class=\"" HTML(attrib) "\"":"") ">" \
666            "<img src=\"" URL(href, 1) "\" alt=\"" HTML(text) "\"" \
667            (attrib?" class=\"" HTML(attrib) "\"":"") ">" \
668            (title?"<figcaption>" inline(title) "</figcaption>":"") \
669            "</figure>\n\n" \
670            _block( substr( block, len + 1) );
671
672   # reference style images (block)
673   } else if ( match(line, /^!\[([^]]*)\] ?\[([^]]*)\](\n|$)/ ) ) {
674     len = RLENGTH;
675     text = gensub(/^!\[([^\n]*)\] ?\[([^\n]*)\](\n.*)?$/, "\\1", 1, block);
676       id = gensub(/^!\[([^\n]*)\] ?\[([^\n]*)\](\n.*)?$/, "\\2", 1, block);
677     if ( ! id ) id = text;
678     if ( rl_href[id] && rl_title[id] ) {
679       return "<figure data-src=\"" URL(rl_href[id], 1) "\">" \
680                "<img src=\"" URL(rl_href[id], 1) "\" alt=\"" HTML(text) "\">" \
681                "<figcaption>" inline(rl_title[id]) "</figcaption>" \
682              "</figure>\n\n" \
683              _block( substr( block, len + 1) );
684     } else if ( rl_href[id] ) {
685       return "<figure data-src=\"" URL(rl_href[id], 1) "\">" \
686                "<img src=\"" URL(rl_href[id], 1) "\" alt=\"" HTML(text) "\">" \
687              "</figure>\n\n" \
688              _block( substr( block, len + 1) );
689     } else {
690       return "<p>" HTML(substr(block, 1, len)) "</p>\n" _block( substr(block, len + 1) );
691     }
692
693   # Macros (standalone <<macro>> calls handled as block, so they are not wrapped in paragraph)
694   } else if ( match( block, /^<<(([^>]|>[^>])+)>>(\n|$)/ ) ) {
695     len = RLENGTH;
696     text = gensub(/^<<(([^>]|>[^>])+)>>(\n.*)?$/, "\\1", 1, block);
697     return "<code class=\"macro\">" HTML(text) "</code>" _block(substr(block, len + 1) );
698
699   # Definition list
700   } else if (match( block, "^(([ \t]*\n)*[^:\n \t][^\n]+\n" \
701                            "([ \t]*\n)* ? ? ?:[ \t][^\n]+(\n|$)" \
702                           "(([ \t]*\n)* ? ? ?:[ \t][^\n]+(\n|$)" \
703                            "|[^:\n \t][^\n]+(\n|$)" \
704                            "|( ? ? ?\t|  +)[^\n]+(\n|$)" \
705                            "|([ \t]*\n)+( ? ? ?\t|  +)[^\n]+(\n|$))*)+" \
706   )) {
707     list = substr( block, 1, RLENGTH); block = substr( block, RLENGTH + 1);
708     return "\n<dl>\n" _dlist( list ) "</dl>\n" _block( block );
709
710   # Unordered list types
711   } else if ( text = _startlist( block, "ul", "-",   "([+*•]|[0-9]+\\.|#\\.|[0-9]+\\)|#\\))") ) {
712     return text;
713   } else if ( text = _startlist( block, "ul", "\\+", "([-*•]|[0-9]+\\.|#\\.|[0-9]+\\)|#\\))") ) {
714     return text;
715   } else if ( text = _startlist( block, "ul", "\\*", "([-+•]|[0-9]+\\.|#\\.|[0-9]+\\)|#\\))") ) {
716     return text;
717   } else if ( text = _startlist( block, "ul", "•", "([-+*]|[0-9]+\\.|#\\.|[0-9]+\\)|#\\))") ) {
718     return text;
719
720   # Ordered list types
721   } else if ( text = _startlist( block, "ol", "[0-9]+\\.", "([-+*•]|#\\.|[0-9]+\\)|#\\))") ) {
722     return text;
723   } else if ( text = _startlist( block, "ol", "[0-9]+\\)", "([-+*•]|[0-9]+\\.|#\\.|#\\))") ) {
724     return text;
725   } else if ( text = _startlist( block, "ol", "#\\.", "([-+*•]|[0-9]+\\.|[0-9]+\\)|#\\))") ) {
726     return text;
727   } else if ( text = _startlist( block, "ol", "#\\)", "([-+*•]|[0-9]+\\.|#\\.|[0-9]+\\))") ) {
728     return text;
729
730   # Split paragraphs
731   } else if ( match( block, /(^|\n)[[:space:]]*(\n|$)/) ) {
732     len = RLENGTH; st = RSTART;
733     return _block( substr(block, 1, st - 1) ) "\n" \
734            _block( substr(block, st + len) );
735
736   # Horizontal rule
737   } else if ( match( block, /(^|\n) ? ? ?((\* *){3,}|(- *){3,}|(_ *){3,})($|\n)/) ) {
738     len = RLENGTH; st = RSTART;
739     return _block(substr(block, 1, st - 1)) "<hr>\n" _block(substr(block, st + len));
740
741   # Plain paragraph
742   } else {
743     return "<p>" inline(block) "</p>\n";
744   }
745 }
746
747 function _startlist(block, type, mark, exclude, LOCAL, st, len, list, indent, text) {
748   if (match( block, "(^|\n) ? ? ?" mark "[ \t][^\n]+(\n|$)" \
749                                    "(([ \t]*\n)* ? ? ?" mark "[ \t][^\n]+(\n|$)" \
750                                    "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
751                                    "|[^\n \t][^\n]+(\n|$))*" ) ) {
752     st = RSTART; len = RLENGTH; list = substr( block, st, len);
753
754     sub("^\n", "", list); match(list, "^ ? ? ?"); indent = RLENGTH;
755     gsub( "(^|\n) {0," indent "}", "\n", list); sub("^\n", "", list);
756
757     text = substr(block, 1, st - 1); block = substr(block, st + len);
758     if (match(text, /\n[[:space:]]*\n/)) return 0;
759     if (match(text, "(^|\n) ? ? ?" exclude "[ \t][^\n]+")) return 0;
760     if (match( list, "\n" exclude "[ \t]" )) {
761       block = substr(list, RSTART + 1) block;
762       list = substr(list, 1, RSTART);
763     }
764
765     return _block( text ) "<" type ">\n" _list( list, mark ) "</" type ">\n" _block( block );
766   } else return 0;
767 }
768
769 function _list (block, mark, p, LOCAL, len, st, text, indent, task) {
770   if ( match(block, "^([ \t]*\n)*$")) return;
771
772   match(block, "^" mark "[ \t]"); indent = RLENGTH;
773   sub("^" mark "[ \t]", "", block);
774
775   if (match(block, /\n[ \t]*\n/)) p = 1;
776
777   match( block, "\n" mark "[ \t][^\n]+(\n|$)" );
778   st = (RLENGTH == -1) ? length(block) + 1 : RSTART;
779   text = substr(block, 1, st); block = substr(block, st + 1);
780
781   gsub("\n {0," indent "}", "\n", text);
782
783   task = match( text, /^\[ \]/   ) ? "<li class=\"task pending\"><input type=checkbox disabled>"      : \
784          match( text, /^\[-\]/   ) ? "<li class=\"task negative\"><input type=checkbox disabled>"     : \
785          match( text, /^\[\/\]/  ) ? "<li class=\"task partial\"><input type=checkbox disabled>"      : \
786          match( text, /^\[\?\]/  ) ? "<li class=\"task unsure\"><input type=checkbox disabled>"       : \
787          match( text, /^\[[xX]\]/) ? "<li class=\"task done\"><input type=checkbox disabled checked>" : "<li>";
788   sub(/^\[[-? \/xX]\]/, "", text);
789
790   text = _nblock( text );
791   if ( ! p && match( text, "^<p>(</p[^>]|</[^p]|<[^/]|[^<])*</p>\n$" ))
792      gsub( "(^<p>|</p>\n$)", "", text);
793
794   return task text "</li>\n" _list(block, mark, p);
795 }
796
797 function _dlist (block, LOCAL, len, st, text, indent, p) {
798   if (match( block, "^([ \t]*\n)*[^:\n \t][^\n]+\n" )) {
799     len = RLENGTH; text = substr(block, 1, len);
800     gsub( "(^\n*|\n*$)", "", text );
801     return "<dt>" inline( text ) "</dt>\n" _dlist( substr(block, len + 1) );
802   } else if (match( block, "^([ \t]*\n)* ? ? ?:[ \t][^\n]+(\n|$)" \
803                          "([^:\n \t][^\n]+(\n|$)" \
804                          "|( ? ? ?\t|  +)[^\n]+(\n|$)" \
805                          "|([ \t]*\n)+( ? ? ?\t|  +)[^\n]+(\n|$))*" \
806   )) {
807     len = RLENGTH; text = substr(block, 1, len);
808     sub( "^([ \t]*\n)*", "", text);
809     match(text, "^ ? ? ?:(\t| +)"); indent = RLENGTH;
810     sub( "^ ? ? ?:(\t| +)", "", text);
811     gsub( "(^|\n) {0," indent "}", "\n", text );
812
813     text = _nblock(text);
814     if (match( text, "^<p>(</p[^>]|</[^p]|<[^/]|[^<])*</p>\n$" ))
815        gsub( "(^<p>|</p>\n$)", "", text);
816
817     return "<dd>" text "</dd>\n" _dlist( substr(block, len + 1) );
818   }
819 }
820
821 BEGIN {
822   # Global Vars
823   file = ""; rl_href[""] = ""; rl_title[""] = "";
824   if (ENVIRON["MD_HTML"] == "true") { AllowHTML = "true"; }
825   HL[1] = 0; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
826   # hls = "0 0 0 0 0 0";
827
828   # Universal Patterns
829   nu = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\_]|_[[:alnum:]])*"    # not underline (except when escaped)
830   na = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\\\*])*"  # not asterisk (except when escaped)
831   ieu =  "_([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])_"                 # inner <em> (underline)
832   isu = "__([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])__"                # inner <strong> (underline)
833   iea =    "\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*"     # inner <em> (asterisk)
834   isa = "\\*\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*\\*"  # inner <strong> (asterisk)
835
836   lix="\\[(\\\\[^\\n]|[^]\\n\\\\[])*\\]"  # link text
837   lid="(<(\\\\[^\\n]|[^\\n<>\\\\])*>|([^<\\n\\t ()\\\\]|\\\\[^\\n])(\\\\[\\n]|[^\\n\\t ()\\\\])*)"  # link dest
838   lit="(\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'|\\((\\\\.|[^()\\\\])*\\))"  # link text
839   # link text with image def
840   lii="\\[(\\\\[^\\n]|[^]\\n\\\\[])*(!" lix "\\([\\n\\t ]*" lid "([\\n\\t ]+" lit ")?[\\n\\t ]*\\))?(\\\\[^\\n]|[^]\\n\\\\[])*\\]"
841
842   # Buffering of full file ist necessary, e.g. to find reference links
843   while (getline) { file = file $0 "\n"; }
844   # Clean up MS-DOS line breaks
845   gsub(/\r\n/, "\n", file);
846
847   # Fill array of reference links
848   f = file; rl_id;
849   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
850   # /(^|\n) ? ? ?\[([^]\n]+)\]: ([^ \t\n]+)(\n?[ \t]+("([^"]+)"|'([^']+)'|\(([^)]+)\)))?(\n|$)/
851   while ( match(f, re_reflink ) ) {
852     rl_id           = gensub( re_reflink, "\\2", 1, substr(f, RSTART, RLENGTH) );
853     rl_href[rl_id]  = gensub( re_reflink, "\\3", 1, substr(f, RSTART, RLENGTH) );
854     rl_title[rl_id] = gensub( re_reflink, "\\5", 1, substr(f, RSTART, RLENGTH) );
855     f = substr(f, RSTART + RLENGTH);
856     rl_title[rl_id] = substr( rl_title[rl_id], 2, length(rl_title[rl_id]) - 2 );
857     if ( rl_href[rl_id] ~ /<.*>/ ) rl_href[rl_id] = substr( rl_href[rl_id], 2, length(rl_href[rl_id]) - 2 );
858   }
859   # Clear reflinks from File
860   while( gsub(re_reflink, "\n", file ) );
861   # for (n in rl_href) { debug(n " | " rl_href[n] " | " rl_title[n] ); }
862
863   # Run Block Processing -> The Actual Markdown!
864   printf "%s", _nblock( file );
865 }