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