]> git.plutz.net Git - cgilite/blob - markdown.awk
anchor links for headlines, bugfix: continue block processing right after tables
[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 # -  ?  Heading identifiers (php md, pandoc)
42 # - [x] Automatic heading identifiers (custom)
43 # - [x] Fenced code blocks (php md, pandoc)
44 #   - [x] Fenced code attributes
45 # - [/] Tables
46 #   -  ?  Simple table (pandoc)
47 #   -  ?  Multiline table (pandoc)
48 #   - [x] Grid table (pandoc)
49 #   - [x] Pipe table (php md pandoc)
50 # - [x] Line blocks (pandoc)
51 # - [x] Task lists (pandoc, custom)
52 # - [ ] Definition lists (php md, pandoc)
53 # - [-] Numbered example lists (pandoc)
54 # - [-] Metadata blocks (pandoc)
55 # - [x] Metadata blocks (custom)
56 # - [x] Fenced Divs (pandoc)
57 #
58 # Extensions - Inline elements:
59 # ----------------------------
60 # - [x] Ignore embedded_underscores (php md, pandoc)
61 # - [x] ~~strikeout~~ (pandoc)
62 # - [x] ^Superscript^ ~Subscript~ (pandoc)
63 # - [-] Bracketed spans (pandoc)
64 #   - [-] Inline attributes (pandoc)
65 # - [-] TEX-Math (pandoc)
66 # -  ?  Footnotes (php md)
67 # -  ?  Abbreviations (php md)
68 # -  ?  "Curly quotes" (smartypants)
69 # - [ ] em-dashes (--) (smartypants old)
70 # -  ?  ... three-dot ellipsis (smartypants)
71 # - [-] en-dash (smartypants)
72 # - [ ] Automatic em-dash / en-dash
73 # - [ ] Automatic -> Arrows <-
74
75 function debug(text) { printf "\n---\n%s\n---\n", text > "/dev/stderr"; }
76
77 function HTML ( text ) {
78   gsub( /&/,  "\\&amp;",  text );
79   gsub( /</,  "\\&lt;",   text );
80   gsub( />/,  "\\&gt;",   text );
81   gsub( /"/,  "\\&quot;", text );
82   gsub( /'/,  "\\&#x27;", text );
83   gsub( /\\/, "\\&#x5C;", text );
84   return text;
85 }
86
87 function inline( line, LOCAL, len, code, href, guard ) {
88   nu = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\_]|_[[:alnum:]])*"    # not underline (except when escaped)
89   na = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\\\*])*"  # not asterisk (except when escaped)
90   ieu =  "_([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])_"                 # inner <em> (underline)
91   isu = "__([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])__"                # inner <strong> (underline)
92   iea =    "\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*"     # inner <em> (asterisk)
93   isa = "\\*\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*\\*"  # inner <strong> (asterisk)
94
95   if ( line ~ /^$/ ) {  # Recursion End
96     return "";
97
98   #  omit processing of escaped characters
99   } else if ( line ~ /^\\[]\\`\*_\{\}\(\)#\+-\.![]/) {
100     return substr(line, 2, 1) inline( substr(line, 3) );
101
102   # hard brakes
103   } else if ( match(line, /^  \n/) ) {
104     return "<br />\n" inline( substr(line, RLENGTH + 1) );
105
106   #  ``code spans``
107   } else if ( match( line, /^`+/) ) {
108     len = RLENGTH
109     guard = substr( line, 1, len )
110     if ( match(line, guard ".*" guard) ) {
111       code = substr( line, len + 1, match( substr(line, len + 1), guard ) - 1)
112       len = 2 * length(guard) + length(code)
113       #  strip single surrounding white spaces
114       code = gensub( / (.*) /, "\\1", "1" , code)
115       #  escape HTML within code span
116       gsub( /&/, "\\&amp;", code ); gsub( /</, "\\&lt;", code ); gsub( />/, "\\&gt;", code );
117       return "<code>" code "</code>" inline( substr( line, len + 1 ) )
118     }
119
120   #  quick links ("automatic links" in md doc)
121   } else if ( match( line, /^<[a-zA-Z]+:\/\/([-\.[:alnum:]]+)(:[0-9]*)?(\/[^>]*)?>/ ) ) {
122     len = RLENGTH;
123     href = HTML( substr( line, 2, len - 2) );
124     return "<a href=\"" href "\">" href "</a>" inline( substr( line, len + 1) );
125
126   # quick link email
127   } 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])?)*>/ ) ) {
128     len = RLENGTH;
129     href = HTML( substr( line, 2, len - 2) );
130     return "<a href=\"mailto:" href "\">" href "</a>" inline( substr( line, len + 1) );
131
132   # inline links
133   } else if ( match(line, /^\[([^]]+)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/) ) {
134     len = RLENGTH;
135     text  = gensub(/^\[([^]]+)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/, "\\1", 1, substr(line, 1, len) );
136     href  = gensub(/^\[([^]]+)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/, "\\2", 1, substr(line, 1, len) );
137     title = gensub(/^\[([^]]+)\]\(([^"\)]+)([[:space:]]+"([^"]+)")?\)/, "\\4", 1, substr(line, 1, len) );
138     if ( title ) {
139       return "<a href=\"" HTML(href) "\" title=\"" HTML(title) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
140     } else {
141       return "<a href=\"" HTML(href) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
142     }
143
144   # reference style links
145   } else if ( match(line, /^\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
146     len = RLENGTH;
147     text = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, substr(line, 1, len) );
148       id = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, substr(line, 1, len) );
149     if ( ! id ) id = text;
150     if ( rl_href[id] && rl_title[id] ) {
151       return "<a href=\"" HTML(rl_href[id]) "\" title=\"" HTML(rl_title[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
152     } else if ( rl_href[id] ) {
153       return "<a href=\"" HTML(rl_href[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
154     } else {
155       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
156     }
157
158   # inline images
159   } else if ( match(line, /^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/) ) {
160     len = RLENGTH;
161     text  = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\1", "g", substr(line, 1, len) );
162     href  = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\2", "g", substr(line, 1, len) );
163     title = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\4", "g", substr(line, 1, len) );
164     if ( title ) {
165       return "<img src=\"" HTML(href) "\" alt=\"" HTML(text) "\" title=\"" HTML(title) "\" />" inline( substr( line, len + 1) );
166     } else {
167       return "<img src=\"" HTML(href) "\" alt=\"" HTML(text) "\" />" inline( substr( line, len + 1) );
168     }
169
170   # reference style images
171   } else if ( match(line, /^!\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
172     len = RLENGTH;
173     text = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, substr(line, 1, len) );
174       id = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, substr(line, 1, len) );
175     if ( ! id ) id = text;
176     if ( rl_href[id] && rl_title[id] ) {
177       return "<img src=\"" HTML(rl_href[id]) "\" alt=\"" HTML(text) "\" title=\"" HTML(rl_title[id]) "\" />" inline( substr( line, len + 1) );
178     } else if ( rl_href[id] ) {
179       return "<img src=\"" HTML(rl_href[id]) "\" alt=\"" HTML(text) "\" />" inline( substr( line, len + 1) );
180     } else {
181       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
182     }
183
184   #  ~~strikeout~~ (pandoc)
185   } else if ( match(line, /^~~([[:graph:]]|[[:graph:]]([^~]|~[^~])*[[:graph:]])~~/) ) {
186     len = RLENGTH;
187     return "<del>" inline( substr( line, 3, len - 4 ) ) "</del>" inline( substr( line, len + 1 ) );
188
189   #  ^superscript^ (pandoc)
190   } else if ( match(line, /^\^([^[:space:]^]|\\[ ^])+\^/) ) {
191     len = RLENGTH;
192     return "<sup>" inline( substr( line, 2, len - 2 ) ) "</sup>" inline( substr( line, len + 1 ) );
193
194   #  ~subscript~ (pandoc)
195   } else if ( match(line, /^~([^[:space:]~]|\\[ ~])+~/) ) {
196     len = RLENGTH;
197     return "<sub>" inline( substr( line, 2, len - 2 ) ) "</sub>" inline( substr( line, len + 1 ) );
198
199   # ignore embedded underscores (pandoc, php md)
200   } else if ( match(line, "^[[:alnum:]](__|_)") ) {
201     return HTML(substr( line, 1, RLENGTH)) inline( substr(line, RLENGTH + 1) );
202
203   #  __strong__$
204   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__$") ) {
205     len = RLENGTH;
206     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
207
208   #  __strong__
209   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__[[:space:][:punct:]]") ) {
210     len = RLENGTH;
211     return "<strong>" inline( substr( line, 3, len - 5 ) ) "</strong>" inline( substr( line, len) );
212
213   #  **strong**
214   } else if ( match(line, "^\\*\\*(([^\\*[:space:]]|" iea ")|([^\\*[:space:]]|" iea ")(" na "|" iea ")*([^\\*[:space:]]|" iea "))\\*\\*") ) {
215     len = RLENGTH;
216     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
217
218   #  _em_$
219   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_$") ) {
220     len = RLENGTH;
221     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
222
223   #  _em_
224   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_[[:space:][:punct:]]") ) {
225     len = RLENGTH;
226     return "<em>" inline( substr( line, 2, len - 3 ) ) "</em>" inline( substr( line, len ) );
227
228   #  *em*
229   } else if ( match(line, "^\\*(([^\\*[:space:]]|" isa ")|([^\\*[:space:]]|" isa ")(" na "|" isa ")*([^\\*[:space:]]|" isa "))\\*") ) {
230     len = RLENGTH;
231     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
232
233   # Macros
234   } else if ( AllowMacros && match( line, /^<<([^>]|>[^>])+>>/) ) {
235     len = RLENGTH;
236     return macro( substr( line, 3, len - 4 ) ) inline(substr(line, len + 1));
237
238   # Verbatim inline HTML
239   } 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:]]*\/?>)/) ) {
240     len = RLENGTH;
241     return substr( line, 1, len) inline(substr(line, len + 1));
242
243   # Literal HTML entities
244   } else if ( match( line, /^&([a-zA-Z]{2,32}|#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});/) ) {
245     len = RLENGTH;
246     return substr( line, 1, len ) inline(substr(line, len + 1));
247
248   # Escape lone HTML character
249   } else if ( match( line, /^[&<>"']/) ) {
250     return HTML(substr(line, 1, 1)) inline(substr(line, 2));
251
252   #  continue walk over string
253   } else {
254     return substr(line, 1, 1) inline( substr(line, 2) );
255   }
256 }
257
258 function _block( block, LOCAL, st, len, hlvl, htxt, guard, code, indent, attrib ) {
259   gsub( /^\n+|\n+$/, "", block );
260
261   if ( block == "" ) {
262     return "";
263
264   # HTML #2 #3 #4 $5
265   } else if ( AllowHTML && match( block, /(^|\n) ? ? ?(<!--([^-]|-[^-]|--[^>])*(-->|$)|<\?([^\?]|\?[^>])*(\?>|$)|<![A-Z][^>]*(>|$)|<!\[CDATA\[([^\]]|\][^\]]|\]\][^>])*(\]\]>|$))/) ) {
266     len = RLENGTH; st = RSTART;
267     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
268
269   # HTML #6
270   } 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|$)/) ) {
271     len = RLENGTH; st = RSTART;
272     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
273
274   # HTML #1
275   } else if ( AllowHTML && match( tolower(block), /(^|\n) ? ? ?<(script|pre|style)([[:space:]\n>]).*(<\/script>|<\/pre>|<\/style>|$)/) ) {
276     len = RLENGTH; st = RSTART;
277     match( tolower(substr(block, st, len)), /(<\/script>|<\/pre>|<\/style>)/);
278     len = RSTART + RLENGTH;
279     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
280
281   # HTML #7
282   } 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|$)/) ) {
283     len = RLENGTH; st = RSTART;
284     return substr(block, st, len) _block(substr(block, st + len));
285
286   # Metadata (custom, block starting with %something)
287   # Metadata is ignored but can be interpreted externally
288   } else if ( match(block, /^%[a-zA-Z]+([[:space:]][^\n]*)?(\n|$)(%[a-zA-Z]+([[:space:]][^\n]*)?(\n|$)|%([[:space:]][^\n]*)?(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
289     len = RLENGTH; st = RSTART;
290     return  _block( substr( block, len + 1) );
291  
292   # Blockquote (leading >)
293   } else if ( match( block, /^> /) ) {
294     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
295     len = RLENGTH; st = RSTART;
296     return "<blockquote>\n" _block( gensub( /(^|\n)> /, "\n", "g", substr(block, 1, st - 1) ) ) "</blockquote>\n\n" \
297            _block( substr(block, st + len) );
298
299   # Pipe Tables (pandoc / php md / gfm )
300   } else if ( match(block, "^((\\|)?([^\n]+\\|)+[^\n]+(\\|)?)\n" \
301                            "((\\|)?:?(-+:?[\\|+])+:?-+:?(\\|)?)\n" \
302                            "((\\|)?([^\n]+\\|)+[^\n]+(\\|)?(\n|$))+" ) ) {
303     len = RLENGTH; st = RSTART;
304     #initialize empty arrays
305     split("", talign); split("", tarray);
306     cols = 0; cnt=0; ttext = "";
307
308     # table header and alignment
309     split( gensub( /(^\||\|$)/, "", "g", \
310            gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
311            substr(block, 1, match(block, /(\n|$)/)) \
312     )), tarray, /\|/);
313     block = substr(block, match(block, /(\n|$)/) + 1 );
314     cols = split( \
315            gensub( /(^\||\|$)/, "", "g", \
316            substr(block, 1, match(block, /(\n|$)/)) \
317     ), talign, /[+\|]/);
318     block = substr(block, match(block, /(\n|$)/) + 1 );
319
320     for( cnt = 1; cnt < cols; cnt++ ) {
321            if (match(talign[cnt], /:-+:/)) talign[cnt]="center";
322       else if (match(talign[cnt],  /-+:/)) talign[cnt]="right";
323       else if (match(talign[cnt],  /:-+/)) talign[cnt]="left";
324       else talign[cnt]="";
325     }
326
327     ttext = "<thead>\n<tr>"
328     for (cnt = 1; cnt < cols; cnt++)
329       ttext = ttext "<th align=\"" talign[cnt] "\">" inline(tarray[cnt]) "</th>"
330     ttext = ttext "</tr>\n</thead><tbody>\n"
331
332     while ( match(block, "^((\\|)?([^\n]+\\|)+[^\n]+(\\|)?(\n|$))+" ) ){
333       split( gensub( /(^\||\|$)/, "", "g", \
334              gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
335              substr(block, 1, match(block, /(\n|$)/)) \
336       )), tarray, /\|/);
337       block = substr(block, match(block, /(\n|$)/) + 1 );
338
339       ttext = ttext "<tr>"
340       for (cnt = 1; cnt < cols; cnt++)
341         ttext = ttext "<td align=\"" talign[cnt] "\">" inline(tarray[cnt]) "</td>"
342       ttext = ttext "</tr>\n"
343     }
344     return "<table>" ttext "</tbody></table>\n" _block(block);
345
346   # Grid Tables (pandoc)
347   } else if ( match(block, "^\\+(-+\\+)+\n" \
348                        "(\\|([^\n]+\\|)+\n)+" \
349                         "\\+(:?=+:?\\+)+\n" \
350                       "((\\|([^\n]+\\|)+\n)+" \
351                             "\\+(-+\\+)+(\n|$))+" \
352             ) ) {
353     len = RLENGTH; st = RSTART;
354     #initialize empty arrays
355     split("", talign); split("", tarray); split("", tread);
356     cols = 0; cnt=0; ttext = "";
357
358     # table header and alignment
359     block = substr(block, match(block, /(\n|$)/) + 1 );
360     while ( match(block, "^\\|([^\n]+\\|)+\n") ) {
361       cols = split( gensub( /(^\||\|$)/, "", "g", \
362              gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
363              substr(block, 1, match(block, /(\n|$)/)) \
364       )), tread, /\|/);
365       block = substr(block, match(block, /(\n|$)/) + 1 );
366       for (cnt = 1; cnt < cols; cnt++)
367         tarray[cnt] = tarray[cnt] "\n" tread[cnt];
368     }
369
370     cols = split( \
371            gensub( /(^\+|\+$)/, "", "g", \
372            substr(block, 1, match(block, /(\n|$)/)) \
373     ), talign, /\+/);
374     block = substr(block, match(block, /(\n|$)/) + 1 );
375
376     for (cnt = 1; cnt < cols; cnt++) {
377            if (match(talign[cnt], /:=+:/)) talign[cnt]="center";
378       else if (match(talign[cnt],  /=+:/)) talign[cnt]="right";
379       else if (match(talign[cnt], /:=+/ )) talign[cnt]="left";
380       else talign[cnt]="";
381     }
382
383     ttext = "<thead>\n<tr>"
384     for (cnt = 1; cnt < cols; cnt++)
385       ttext = ttext "<th align=\"" talign[cnt] "\">" _block(tarray[cnt]) "</th>"
386     ttext = ttext "</tr>\n</thead><tbody>\n"
387
388     while ( match(block, /^((\|([^\n]+\|)+\n)+\+(-+\+)+(\n|$))+/ ) ){
389       split("", tarray);
390       while ( match(block, /^\|([^\n]+\|)+\n/) ) {
391         split( gensub( /(^\||\|$)/, "", "g", \
392                gensub( /(^|[^\\])\\\|/, "\\1\\&#x7C;", "g", \
393                substr(block, 1, match(block, /(\n|$)/)) \
394         )), tread, /\|/);
395         block = substr(block, match(block, /(\n|$)/) + 1 );
396         for (cnt = 1; cnt < cols; cnt++)
397           tarray[cnt] = tarray[cnt] "\n" tread[cnt];
398       }
399       block = substr(block, match(block, /(\n|$)/) + 1 );
400
401       ttext = ttext "<tr>"
402       for (cnt = 1; cnt < cols; cnt++)
403         ttext = ttext "<td align=\"" talign[cnt] "\">" _block(tarray[cnt]) "</td>"
404       ttext = ttext "</tr>\n"
405     }
406     return "<table>" ttext "</tbody></table>\n" _block(block);
407
408   # Line Blocks (pandoc)
409   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
410     len = RLENGTH; st = RSTART;
411     code = substr(block, 1, len);
412     gsub(/\n[[:space:]]+/, " ", code);
413     gsub(/\n\| /, "\n", code);
414     gsub(/^\| |\n$/, "", code);
415     return "<div class=\"line-block\">" gensub(/\n/, "<br />\n", "g", inline( code )) "</div>\n" \
416            _block( substr( block, len + 1) );
417
418   # Indented Code Block
419   } else if ( match(block, /^(    |\t)[^\n]+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
420     len = RLENGTH; st = RSTART;
421     code = substr(block, 1, len);
422     gsub(/(^|\n)(    |\t)/, "\n", code);
423     gsub(/^\n|\n+$/, "", code);
424     return "<pre><code>" HTML( code ) "</code></pre>\n" \
425            _block( substr( block, len + 1 ) );
426
427   # Fenced Divs (pandoc, custom)
428   } else if ( match( block, /^(:::+)/ ) ) {
429     guard = substr( block, 1, RLENGTH );
430     code = gensub(/^[^\n]+\n/, "", 1, block);
431     attrib = gensub(/^:::+[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\1", 1, block);
432     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
433     gsub(/(^ | $)/, "", attrib);
434     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
435       len = RLENGTH; st = RSTART;
436       return "<div class=\"" attrib "\">" _block( substr(code, 1, st - 1) ) "</div>\n" \
437              _block( substr( code, st + len ) );
438     } else {
439       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
440       len = RLENGTH; st = RSTART;
441       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
442              _block( substr(block, st + len) );
443     }
444
445   # Fenced Code Block (pandoc)
446   } else if ( match( block, /^(~~~+|```+)/ ) ) {
447     guard = substr( block, 1, RLENGTH );
448     code = gensub(/^[^\n]+\n/, "", 1, block);
449     attrib = gensub(/^(~~~+|```+)[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\2", 1, block);
450     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
451     gsub(/(^ | $)/, "", attrib);
452     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
453       len = RLENGTH; st = RSTART;
454       return "<pre><code class=\"" attrib "\">" HTML( substr(code, 1, st - 1) ) "</code></pre>\n" \
455              _block( substr( code, st + len ) );
456     } else {
457       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
458       len = RLENGTH; st = RSTART;
459       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
460              _block( substr(block, st + len) );
461     }
462
463   # Unordered list
464   } else if ( match( block, "^ ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
465                             "(([ \t]*\n)* ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
466                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
467                             "|[^\n]+(\n|$))*" ) ) {
468   list = substr( block, 1, RLENGTH);
469   block = substr( block, RLENGTH + 1);
470   indent = length( gensub(/[-+*][ \t]+[^\n]+.*$/, "", 1, list) );
471
472   gsub("(^|\n) {0," indent "}", "\n", list);
473   return "\n<ul>\n" _list( substr(list, 2) ) "</ul>\n" _block( block );
474
475   # Ordered list
476   } else if ( match( block, "^ ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
477                             "(([ \t]*\n)* ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
478                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
479                             "|[^\n]+(\n|$))*" ) ) {
480   list = substr( block, 1, RLENGTH);
481   block = substr( block, RLENGTH + 1);
482   indent = length( gensub(/([0-9]+|#)\.[ \t]+[^\n]+.*$/, "", 1, list) );
483
484   gsub("(^|\n) {0," indent "}", "\n", list);
485   return "\n<ol>\n" _list( substr(list, 2) ) "</ol>\n" _block( block );
486
487   # First Order Heading
488   } else if ( match( block, /^[^\n]+\n===+(\n|$)/ ) ) {
489     len = RLENGTH;
490     HL[1]++; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
491     return "<h1 id=\"" HL[1] " - " HTML(gensub( /\n.*$/, "", "g", block )) "\">" \
492            inline( gensub( /\n.*$/, "", "g", block ) ) \
493            "<a class=\"anchor\" href=\"" HL[1] " - " \
494            HTML(gensub( /\n.*$/, "", "g", block )) "\"></a></h1>\n\n" \
495            _block( substr( block, len + 1 ) );
496
497   # Second Order Heading
498   } else if ( match( block, /^[^\n]+\n---+(\n|$)/ ) ) {
499     len = RLENGTH;
500     HL[2]++; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
501     return "<h2 id=\"" HL[1] "." HL[2] " - " HTML(gensub( /\n.*$/, "", "g", block )) "\">" \
502            inline( gensub( /\n.*$/, "", "g", block ) ) \
503            "<a class=\"anchor\" href=\"" HL[1] "." HL[2] " - " \
504            HTML(gensub( /\n.*$/, "", "g", block )) "\"></a></h2>\n\n" \
505            _block( substr( block, len + 1) );
506
507   # Nth Order Heading
508   } else if ( match( block, /^#{1,6}[ \t]*[^\n]+([ \t]*#*)(\n|$)/ ) ) {
509     len = RLENGTH;
510     hlvl = length( gensub( /^(#{1,6}).*$/, "\\1", "g", block ) );
511     htxt = gensub(/^#{1,6}[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[^\n#])+)([ \t]*#*)(\n.*)?$/, "\\1", 1, block);
512     HL[hlvl]++; for ( n = hlvl + 1; n < 7; n++) { HL[n] = 0;}
513     hid = HL[1]; for ( n = 2; n <= hlvl; n++) { hid = hid "." HL[n] ; }
514     return "<h" hlvl " id=\"" hid " - " HTML(htxt) "\">" inline( htxt ) \
515            "<a class=\"anchor\" href=\"" hid "\"></a></h" hlvl ">\n\n" \
516            _block( substr( block, len + 1) );
517
518   # Split paragraphs
519   } else if ( match( block, /(^|\n)[[:space:]]*(\n|$)/) ) {
520     len = RLENGTH; st = RSTART;
521     return _block( substr(block, 1, st - 1) ) "\n" \
522            _block( substr(block, st + len) );
523
524   # Horizontal rule
525   } else if ( match( block, /(^|\n) ? ? ?((\* *){3,}|(- *){3,}|(_ *){3,})($|\n)/) ) {
526     len = RLENGTH; st = RSTART;
527     return _block(substr(block, 1, st - 1)) "<hr />\n" _block(substr(block, st + len));
528
529   # Plain paragraph
530   } else {
531     return "<p>" inline(block) "</p>\n";
532   }
533 }
534
535 function _list( block, last, LOCAL, p) {
536   if ( ! length(block) ) return "";
537   gsub(/^([-+*]|[0-9]+\.|#\.)(  ? ? ?|\t)/, "", block)
538
539   # slice next list item from input
540   if ( match( block, /\n([-+*]|[0-9]+\.|#\.)[ \t]+[^\n]+/) ) {
541     p = substr( block, 1, RSTART);
542     block = substr( block, RSTART + 1);
543   } else {
544     p = block; block = "";
545   }
546   sub( /\n +([-+*]|[0-9]+\.|#\.)/, "\n&", p );
547
548   # if this should be a paragraph item
549   # either previous item (last) or current item (p) contains blank lines
550   if (match(last, /\n[[:space:]]*\n/) || match(p, /\n[[:space:]]*\n/) ) {
551     last = p; p = _block(p);
552   } else {
553     last = p; p = _block(p);
554     sub( /^<p>/, "", p );
555     sub( /<\/p>\n/, "", p );
556   }
557   sub( /\n$/, "", p );
558
559   # Task List (pandoc, custom)
560          if ( p ~ /^\[ \].*/ )       { return "<li class=\"task pending\"><input type=checkbox disabled />" \
561                                               substr(p, 4) "</li>\n" _list( block, last );
562   } else if ( p ~ /^\[-\].*/ )       { return "<li class=\"task negative\"><input type=checkbox disabled />" \
563                                               substr(p, 4) "</li>\n" _list( block, last );
564   } else if ( p ~ /^\[\?\].*/ )      { return "<li class=\"task unsure\"><input type=checkbox disabled />" \
565                                               substr(p, 4) "</li>\n" _list( block, last );
566   } else if ( p ~ /^\[\/\].*/ )      { return "<li class=\"task partial\"><input type=checkbox disabled />" \
567                                               substr(p, 4) "</li>\n" _list( block, last );
568   } else if ( p ~ /^\[[xX]\].*/ )    { return "<li class=\"task done\"><input type=checkbox disabled checked />" \
569                                             substr(p, 4) "</li>\n" _list( block, last );
570   } else if ( p ~ /^<p>\[ \].*/ )    { return "<li class=\"task pending\"><p><input type=checkbox disabled />" \
571                                               substr(p, 7) "</li>\n" _list( block, last );
572   } else if ( p ~ /^<p>\[-\].*/ )    { return "<li class=\"task negative\"><p><input type=checkbox disabled />" \
573                                               substr(p, 7) "</li>\n" _list( block, last );
574   } else if ( p ~ /^<p>\[\?\].*/ )   { return "<li class=\"task unsure\"><p><input type=checkbox disabled />" \
575                                               substr(p, 7) "</li>\n" _list( block, last );
576   } else if ( p ~ /^<p>\[\/\].*/ )   { return "<li class=\"task partial\"><p><input type=checkbox disabled />" \
577                                               substr(p, 7) "</li>\n" _list( block, last );
578   } else if ( p ~ /^<p>\[[xX]\].*/ ) { return "<li class=\"task done\"><p><input type=checkbox disabled checked />" \
579                                               substr(p, 7) "</li>\n" _list( block, last );
580   } else { return "<li>" p "</li>\n" _list( block, last ); }
581 }
582
583 BEGIN {
584   # Global Vars
585   file = ""; rl_href[""] = ""; rl_title[""] = "";
586   if (ENVIRON["MD_HTML"] == "true") { AllowHTML = "true"; }
587   HL[1] = 0; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
588
589   # Buffering of full file ist necessary, e.g. to find reference links
590   while (getline) { file = file $0 "\n"; }
591   # Clean up MS-DOS line breaks
592   gsub(/\r\n/, "\n", file);
593
594   # Fill array of reference links
595   f = file; rl_id;
596   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
597   # /(^|\n) ? ? ?\[([^]\n]+)\]: ([^ \t\n]+)(\n?[ \t]+("([^"]+)"|'([^']+)'|\(([^)]+)\)))?(\n|$)/
598   while ( match(f, re_reflink ) ) {
599     rl_id           = gensub( re_reflink, "\\2", 1, substr(f, RSTART, RLENGTH) );
600     rl_href[rl_id]  = gensub( re_reflink, "\\3", 1, substr(f, RSTART, RLENGTH) );
601     rl_title[rl_id] = gensub( re_reflink, "\\5", 1, substr(f, RSTART, RLENGTH) );
602     f = substr(f, RSTART + RLENGTH);
603     rl_title[rl_id] = substr( rl_title[rl_id], 2, length(rl_title[rl_id]) - 2 );
604     if ( rl_href[rl_id] ~ /<.*>/ ) rl_href[rl_id] = substr( rl_href[rl_id], 2, length(rl_href[rl_id]) - 2 );
605   }
606   # Clear reflinks from File
607   while( gsub(re_reflink, "\n", file ) );
608   # for (n in rl_href) { debug(n " | " rl_href[n] " | " rl_title[n] ); }
609
610   # Run Block Processing -> The Actual Markdown!
611   printf "%s", _block( file );
612 }