]> git.plutz.net Git - cgilite/blob - markdown.awk
corrected paragraph splitting and hr/h2 distinction
[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 # ToDo:
9 # - HTML processing / escaping (according to environment flag)
10 # - em-dashes and arrows
11
12 # Supported Features / TODO:
13 # ==========================
14 # [x] done    [ ] todo    [-] not planned    ? unsure
15 #
16 # Basic Markdown - Block elements:
17 # -------------------------------
18 # - [x] Paragraphs
19 #   - [x] Double space line breaks
20 # - [x] Proper block element nesting
21 # - [x] Headings
22 # - [x] ATX-Style Headings
23 # - [x] Blockquotes
24 # - [x] Lists (ordered, unordered)
25 # - [x] Code blocks (using indention)
26 # - [x] Horizontal rules
27 # - [x] Verbatim HTML block (disabled by default)
28 #
29 # Basic Markdown - Inline elements:
30 # ---------------------------------
31 # - [x] Links
32 # - [x] Reference style links
33 # - [x] Emphasis *em*/**strong** (*Asterisk*, _Underscore_)
34 # - [x] `code`, also ``code containing `backticks` ``
35 # - [x] Images / reference style images
36 # - [x] <automatic links>
37 # - [x] backslash escapes
38 # - [x] Verbatim HTML inline (disabled by default)
39 # - [x] HTML escaping
40 #
41 # NOTE: Set the environment variable MD_HTML=true to enable verbatim HTML
42 #
43 # Extensions - Block elements:
44 # ----------------------------
45 # -  ?  Heading identifiers (php md, pandoc)
46 # - [x] Automatic heading identifiers (custom)
47 # - [x] Fenced code blocks (php md, pandoc)
48 #   - [x] Fenced code attributes
49 # - [ ] Tables
50 #   -  ?  Simple table (pandoc)
51 #   -  ?  Multiline table (pandoc)
52 #   -  ?  Grid table (pandoc)
53 #   -  ?  Pipe table (php md pandoc)
54 # - [x] Line blocks (pandoc)
55 # - [x] Task lists (pandoc)
56 # - [ ] Definition lists (php md, pandoc)
57 # - [-] Numbered example lists (pandoc)
58 # - [-] Metadata blocks (pandoc)
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 # - [-] TEX-Math (pandoc)
69 # -  ?  Footnotes (php md)
70 # -  ?  Abbreviations (php md)
71 # -  ?  "Curly quotes" (smartypants)
72 # - [ ] em-dashes (--) (smartypants old)
73 # -  ?  ... three-dot ellipsis (smartypants)
74 # - [-] en-dash (smartypants)
75 # - [ ] Automatic em-dash / en-dash
76 # - [ ] Automatic -> Arrows <-
77
78 function debug(text) { printf "\n---\n%s\n---\n", text > "/dev/stderr"; }
79
80 function HTML ( text ) {
81   gsub( /&/,  "\\&amp;",  text );
82   gsub( /</,  "\\&lt;",   text );
83   gsub( />/,  "\\&gt;",   text );
84   gsub( /"/,  "\\&quot;", text );
85   gsub( /'/,  "\\&#x27;", text );
86   gsub( /\\/, "\\&#x5C;", text );
87   return text;
88 }
89
90 function inline( line, LOCAL, len, code, href, guard ) {
91   nu = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\_]|_[[:alnum:]])*"    # not underline (except when escaped)
92   na = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\\\*])*"  # not asterisk (except when escaped)
93   ieu =  "_([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])_"                 # inner <em> (underline)
94   isu = "__([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])__"                # inner <strong> (underline)
95   iea =    "\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*"     # inner <em> (asterisk)
96   isa = "\\*\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*\\*"  # inner <strong> (asterisk)
97
98   if ( line ~ /^$/ ) {  # Recursion End
99     return "";
100
101   #  omit processing of escaped characters
102   } else if ( line ~ /^\\[]\\`\*_\{\}\(\)#\+-\.![]/) {
103     return substr(line, 2, 1) inline( substr(line, 3) );
104
105   # hard brakes
106   } else if ( match(line, /^  \n/) ) {
107     return "<br />\n" inline( substr(line, RLENGTH + 1) );
108
109   #  ``code spans``
110   } else if ( match( line, /^`+/) ) {
111     len = RLENGTH
112     guard = substr( line, 1, len )
113     if ( match(line, guard ".*" guard) ) {
114       code = substr( line, len + 1, match( substr(line, len + 1), guard ) - 1)
115       len = 2 * length(guard) + length(code)
116       #  strip single surrounding white spaces
117       code = gensub( / (.*) /, "\\1", "1" , code)
118       #  escape HTML within code span
119       gsub( /&/, "\\&amp;", code ); gsub( /</, "\\&lt;", code ); gsub( />/, "\\&gt;", code );
120       return "<code>" code "</code>" inline( substr( line, len + 1 ) )
121     }
122
123   #  quick links ("automatic links" in md doc)
124   } else if ( match( line, /^<[a-zA-Z]+:\/\/([-\.[:alnum:]]+)(:[0-9]*)?(\/[^>]*)?>/ ) ) {
125     len = RLENGTH;
126     href = HTML( substr( line, 2, len - 2) );
127     return "<a href=\"" href "\">" href "</a>" inline( substr( line, len + 1) );
128
129   # inline links
130   } else if ( match(line, /^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/) ) {
131     len = RLENGTH;
132     text  = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\1", "g", line);
133     href  = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\2", "g", line);
134     title = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\4", "g", line);
135     if ( title ) {
136       return "<a href=\"" HTML(href) "\" title=\"" HTML(title) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
137     } else {
138       return "<a href=\"" HTML(href) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
139     }
140
141   # reference style links
142   } else if ( match(line, /^\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
143     len = RLENGTH;
144     text = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, line);
145       id = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, line);
146     if ( ! id ) id = text;
147     if ( rl_href[id] && rl_title[id] ) {
148       return "<a href=\"" HTML(rl_href[id]) "\" title=\"" HTML(rl_title[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
149     } else if ( rl_href[id] ) {
150       return "<a href=\"" HTML(rl_href[id]) "\">" inline(text) "</a>" inline( substr( line, len + 1) );
151     } else {
152       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
153     }
154
155   # inline images
156   } else if ( match(line, /^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/) ) {
157     len = RLENGTH;
158     text  = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\1", "g", line);
159     href  = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\2", "g", line);
160     title = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\4", "g", line);
161     if ( title ) {
162       return "<img src=\"" HTML(href) "\" alt=\"" HTML(text) "\" title=\"" HTML(title) "\" />" inline( substr( line, len + 1) );
163     } else {
164       return "<img src=\"" HTML(href) "\" alt=\"" HTML(text) "\" />" inline( substr( line, len + 1) );
165     }
166
167   # reference style images
168   } else if ( match(line, /^!\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
169     len = RLENGTH;
170     text = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, line);
171       id = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, line);
172     if ( ! id ) id = text;
173     if ( rl_href[id] && rl_title[id] ) {
174       return "<img src=\"" HTML(rl_href[id]) "\" alt=\"" HTML(text) "\" title=\"" HTML(rl_title[id]) "\" />" inline( substr( line, len + 1) );
175     } else if ( rl_href[id] ) {
176       return "<img src=\"" HTML(rl_href[id]) "\" alt=\"" HTML(text) "\" />" inline( substr( line, len + 1) );
177     } else {
178       return "" HTML(substr(line, 1, len)) inline( substr(line, len + 1) );
179     }
180
181   #  ~~strikeout~~ (pandoc)
182   } else if ( match(line, /^~~([[:graph:]]|[[:graph:]]([^~]|~[^~])*[[:graph:]])~~/) ) {
183     len = RLENGTH;
184     return "<del>" inline( substr( line, 3, len - 4 ) ) "</del>" inline( substr( line, len + 1 ) );
185
186   #  ^superscript^ (pandoc)
187   } else if ( match(line, /^\^([^[:space:]^]|\\[ ^])+\^/) ) {
188     len = RLENGTH;
189     return "<sup>" inline( substr( line, 2, len - 2 ) ) "</sup>" inline( substr( line, len + 1 ) );
190
191   #  ~subscript~ (pandoc)
192   } else if ( match(line, /^~([^[:space:]~]|\\[ ~])+~/) ) {
193     len = RLENGTH;
194     return "<sub>" inline( substr( line, 2, len - 2 ) ) "</sub>" inline( substr( line, len + 1 ) );
195
196   # ignore embedded underscores (pandoc, php md)
197   } else if ( match(line, "^[[:alnum:]](__|_)") ) {
198     return HTML(substr( line, 1, RLENGTH)) inline( substr(line, RLENGTH + 1) );
199
200   #  __strong__$
201   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__$") ) {
202     len = RLENGTH;
203     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
204
205   #  __strong__
206   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__[[:space:][:punct:]]") ) {
207     len = RLENGTH;
208     return "<strong>" inline( substr( line, 3, len - 5 ) ) "</strong>" inline( substr( line, len) );
209
210   #  **strong**
211   } else if ( match(line, "^\\*\\*(([^\\*[:space:]]|" iea ")|([^\\*[:space:]]|" iea ")(" na "|" iea ")*([^\\*[:space:]]|" iea "))\\*\\*") ) {
212     len = RLENGTH;
213     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
214
215   #  _em_$
216   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_$") ) {
217     len = RLENGTH;
218     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
219
220   #  _em_
221   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_[[:space:][:punct:]]") ) {
222     len = RLENGTH;
223     return "<em>" inline( substr( line, 2, len - 3 ) ) "</em>" inline( substr( line, len ) );
224
225   #  *em*
226   } else if ( match(line, "^\\*(([^\\*[:space:]]|" isa ")|([^\\*[:space:]]|" isa ")(" na "|" isa ")*([^\\*[:space:]]|" isa "))\\*") ) {
227     len = RLENGTH;
228     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
229
230   # Macros
231   } else if ( AllowMacros && match( line, /^<<([^>]|>[^>])+>>/) ) {
232     len = RLENGTH;
233     return macro( substr( line, 3, len - 4 ) ) inline(substr(line, len + 1));
234
235   # Verbatim inline HTML
236   } 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:]]*\/?>)/) ) {
237     len = RLENGTH;
238     return substr( line, 1, len) inline(substr(line, len + 1));
239
240   # Literal HTML entities
241   } else if ( match( line, /^&([a-zA-Z]{2,32}|#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});/) ) {
242     len = RLENGTH;
243     return substr( line, 1, len ) inline(substr(line, len + 1));
244
245   # Escape lone HTML character
246   } else if ( match( line, /^[&<>"']/) ) {
247     return HTML(substr(line, 1, 1)) inline(substr(line, 2));
248
249   #  continue walk over string
250   } else {
251     return substr(line, 1, 1) inline( substr(line, 2) );
252   }
253 }
254
255 function _block( block, LOCAL, st, len, hlvl, htxt, guard, code, indent, attrib ) {
256   gsub( /^\n+|\n+$/, "", block );
257
258   if ( block == "" ) {
259     return "";
260
261   # HTML #2 #3 #4 $5
262   } else if ( AllowHTML && match( block, /(^|\n) ? ? ?(<!--([^-]|-[^-]|--[^>])*(-->|$)|<\?([^\?]|\?[^>])*(\?>|$)|<![A-Z][^>]*(>|$)|<!\[CDATA\[([^\]]|\][^\]]|\]\][^>])*(\]\]>|$))/) ) {
263     len = RLENGTH; st = RSTART;
264     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
265
266   # HTML #6
267   } 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|$)/) ) {
268     len = RLENGTH; st = RSTART;
269     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
270
271   # HTML #1
272   } else if ( AllowHTML && match( tolower(block), /(^|\n) ? ? ?<(script|pre|style)([[:space:]\n>]).*(<\/script>|<\/pre>|<\/style>|$)/) ) {
273     len = RLENGTH; st = RSTART;
274     match( tolower(substr(block, st, len)), /(<\/script>|<\/pre>|<\/style>)/);
275     len = RSTART + RLENGTH;
276     return _block(substr(block, 1, st - 1)) substr(block, st, len) _block(substr(block, st + len));
277
278   # HTML #7
279   } 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|$)/) ) {
280     len = RLENGTH; st = RSTART;
281     return substr(block, st, len) _block(substr(block, st + len));
282  
283   # Blockquote (leading >)
284   } else if ( match( block, /^> /) ) {
285     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
286     len = RLENGTH; st = RSTART;
287     return "<blockquote>\n" _block( gensub( /(^|\n)> /, "\n", "g", substr(block, 1, st - 1) ) ) "</blockquote>\n\n" \
288            _block( substr(block, st + len) );
289
290   # Line Blocks (pandoc)
291   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
292     len = RLENGTH; st = RSTART;
293     code = substr(block, 1, len);
294     gsub(/\n[[:space:]]+/, " ", code);
295     gsub(/\n\| /, "\n", code);
296     gsub(/^\| |\n$/, "", code);
297     return "<div class=\"line-block\">" gensub(/\n/, "<br />\n", "g", inline( code )) "</div>\n" \
298            _block( substr( block, len + 1) );
299
300   # Indented Code Block
301   } else if ( match(block, /^(    |\t)[^\n]+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
302     len = RLENGTH; st = RSTART;
303     code = substr(block, 1, len);
304     gsub(/(^|\n)(    |\t)/, "\n", code);
305     gsub(/^\n|\n+$/, "", code);
306     return "<pre><code>" HTML( code ) "</code></pre>\n" \
307            _block( substr( block, len + 1 ) );
308
309   # Fenced Divs (pandoc, custom)
310   } else if ( match( block, /^(:::+)/ ) ) {
311     guard = substr( block, 1, RLENGTH );
312     code = gensub(/^[^\n]+\n/, "", 1, block);
313     attrib = gensub(/^:::+[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\1", 1, block);
314     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
315     gsub(/(^ | $)/, "", attrib);
316     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
317       len = RLENGTH; st = RSTART;
318       return "<div class=\"" attrib "\">" _block( substr(code, 1, st - 1) ) "</div>\n" \
319              _block( substr( code, st + len ) );
320     } else {
321       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
322       len = RLENGTH; st = RSTART;
323       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
324              _block( substr(block, st + len) );
325     }
326
327   # Fenced Code Block (pandoc)
328   } else if ( match( block, /^(~~~+|```+)/ ) ) {
329     guard = substr( block, 1, RLENGTH );
330     code = gensub(/^[^\n]+\n/, "", 1, block);
331     attrib = gensub(/^:::+[ \t]*\{?[ \t]*([^\}\n]*)\}?[ \t]*\n.*$/, "\\1", 1, block);
332     gsub(/[^a-zA-Z0-9_-]+/, " ", attrib);
333     gsub(/(^ | $)/, "", attrib);
334     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
335       len = RLENGTH; st = RSTART;
336       return "<pre><code class=\"" attrib "\">" HTML( substr(code, 1, st - 1) ) "</code></pre>\n" \
337              _block( substr( code, st + len ) );
338     } else {
339       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
340       len = RLENGTH; st = RSTART;
341       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
342              _block( substr(block, st + len) );
343     }
344
345   # Unordered list
346   } else if ( match( block, "^ ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
347                             "(([ \t]*\n)* ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
348                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
349                             "|[^\n]+(\n|$))*" ) ) {
350   list = substr( block, 1, RLENGTH);
351   block = substr( block, RLENGTH + 1);
352   indent = length( gensub(/[-+*][ \t]+[^\n]+.*$/, "", 1, list) );
353
354   gsub("(^|\n) {0," indent "}", "\n", list);
355   return "\n<ul>\n" _list( substr(list, 2) ) "</ul>\n" _block( block );
356
357   # Ordered list
358   } else if ( match( block, "^ ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
359                             "(([ \t]*\n)* ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
360                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
361                             "|[^\n]+(\n|$))*" ) ) {
362   list = substr( block, 1, RLENGTH);
363   block = substr( block, RLENGTH + 1);
364   indent = length( gensub(/([0-9]+|#)\.[ \t]+[^\n]+.*$/, "", 1, list) );
365
366   gsub("(^|\n) {0," indent "}", "\n", list);
367   return "\n<ol>\n" _list( substr(list, 2) ) "</ol>\n" _block( block );
368
369   # First Order Heading
370   } else if ( match( block, /^[^\n]+\n===+(\n|$)/ ) ) {
371     len = RLENGTH;
372     HL[1]++; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
373     return "<h1 id=\"" HL[1] " - " HTML(gensub( /\n.*$/, "", "g", block )) "\">" inline( gensub( /\n.*$/, "", "g", block ) ) "</h1>\n\n" \
374            _block( substr( block, len + 1 ) );
375
376   # Second Order Heading
377   } else if ( match( block, /^[^\n]+\n---+(\n|$)/ ) ) {
378     len = RLENGTH;
379     HL[2]++; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
380     return "<h2 id=\"" HL[1] "." HL[2] " - " HTML(gensub( /\n.*$/, "", "g", block )) "\">" inline( gensub( /\n.*$/, "", "g", block ) ) "</h2>\n\n" \
381            _block( substr( block, len + 1) );
382
383   # Nth Order Heading
384   } else if ( match( block, /^#{1,6}[ \t]*[^\n]+([ \t]*#*)(\n|$)/ ) ) {
385     len = RLENGTH;
386     hlvl = length( gensub( /^(#{1,6}).*$/, "\\1", "g", block ) );
387     htxt = gensub(/^#{1,6}[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[^\n#])+)([ \t]*#*)(\n.*)?$/, "\\1", 1, block);
388     HL[hlvl]++; for ( n = hlvl + 1; n < 7; n++) { HL[n] = 0;}
389     hid = HL[1]; for ( n = 2; n <= hlvl; n++) { hid = hid "." HL[n] ; }
390     return "<h" hlvl " id=\"" hid " - " HTML(htxt) "\">" inline( htxt ) "</h" hlvl ">\n\n" \
391            _block( substr( block, len + 1) );
392
393   # Split paragraphs
394   } else if ( match( block, /(^|\n)[[:space:]]*(\n|$)/) ) {
395     len = RLENGTH; st = RSTART;
396     return _block( substr(block, 1, st - 1) ) "\n" \
397            _block( substr(block, st + len) );
398
399   # Horizontal rule
400   } else if ( match( block, /(^|\n) ? ? ?((\* *){3,}|(- *){3,}|(_ *){3,})($|\n)/) ) {
401     len = RLENGTH; st = RSTART;
402     return _block(substr(block, 1, st - 1)) "<hr />\n" _block(substr(block, st + len));
403
404   # Plain paragraph
405   } else {
406     return "<p>" inline(block) "</p>\n";
407   }
408 }
409
410 function _list( block, last, LOCAL, p) {
411   if ( ! length(block) ) return "";
412   gsub(/^([-+*]|[0-9]+\.|#\.)(  ? ? ?|\t)/, "", block)
413
414   # slice next list item from input
415   if ( match( block, /\n([-+*]|[0-9]+\.|#\.)[ \t]+[^\n]+/) ) {
416     p = substr( block, 1, RSTART);
417     block = substr( block, RSTART + 1);
418   } else {
419     p = block; block = "";
420   }
421   sub( /\n +([-+*]|[0-9]+\.|#\.)/, "\n&", p );
422
423   # if this should be a paragraph item
424   # either previous item (last) or current item (p) contains blank lines
425   if (match(last, /\n[[:space:]]*\n/) || match(p, /\n[[:space:]]*\n/) ) {
426     last = p; p = _block(p);
427   } else {
428     last = p; p = _block(p);
429     sub( /^<p>/, "", p );
430     sub( /<\/p>\n/, "", p );
431   }
432   sub( /\n$/, "", p );
433
434   # Task List (pandoc)
435        if ( p ~ /^\[ \].*/ )       { p = "<input type=checkbox disabled />" substr(p, 4); }
436   else if ( p ~ /^\[[xX]\].*/ )    { p = "<input type=checkbox disabled checked />" substr(p, 4); }
437   else if ( p ~ /^<p>\[ \].*/ )    { p = "<p><input type=checkbox disabled />" substr(p, 7); }
438   else if ( p ~ /^<p>\[[xX]\].*/ ) { p = "<p><input type=checkbox disabled checked />" substr(p, 7); }
439   return "<li>" p "</li>\n" _list( block, last );
440 }
441
442 BEGIN {
443   # Global Vars
444   file = ""; rl_href[""] = ""; rl_title[""] = "";
445   if (ENVIRON["MD_HTML"] == "true") { AllowHTML = "true"; }
446   HL[1] = 0; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
447
448   # Buffering of full file ist necessary, e.g. to find reference links
449   while (getline) { file = file $0 "\n"; }
450   # Clean up MS-DOS line breaks
451   gsub(/\r\n/, "\n", file);
452
453   # Fill array of reference links
454   f = file; rl_id;
455   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
456   # /(^|\n) ? ? ?\[([^]\n]+)\]: ([^ \t\n]+)(\n?[ \t]+("([^"]+)"|'([^']+)'|\(([^)]+)\)))?(\n|$)/
457   while ( match(f, re_reflink ) ) {
458     rl_id           = gensub( re_reflink, "\\2", 1, substr(f, RSTART, RLENGTH) );
459     rl_href[rl_id]  = gensub( re_reflink, "\\3", 1, substr(f, RSTART, RLENGTH) );
460     rl_title[rl_id] = gensub( re_reflink, "\\5", 1, substr(f, RSTART, RLENGTH) );
461     f = substr(f, RSTART + RLENGTH);
462     rl_title[rl_id] = substr( rl_title[rl_id], 2, length(rl_title[rl_id]) - 2 );
463     if ( rl_href[rl_id] ~ /<.*>/ ) rl_href[rl_id] = substr( rl_href[rl_id], 2, length(rl_href[rl_id]) - 2 );
464   }
465   # Clear reflinks from File
466   while( gsub(re_reflink, "\n", file ) );
467   # for (n in rl_href) { debug(n " | " rl_href[n] " | " rl_title[n] ); }
468
469   # Run Block Processing -> The Actual Markdown!
470   printf "%s", _block( file );
471 }