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