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