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