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