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