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