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