]> git.plutz.net Git - cgilite/blob - markdown.awk
md: image embedding, completing support for basic markdown
[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 #
28 # Basic Markdown - Inline elements:
29 # ---------------------------------
30 # - [x] Links
31 # - [x] Reference style links
32 # - [x] Emphasis *em*/**strong** (*Asterisk*, _Underscore_)
33 # - [x] `code`, also ``code containing `backticks` ``
34 # - [x] Images / reference style images
35 # - [x] <automatic links>
36 # - [x] backslash escapes
37 #
38 # Extensions - Block elements:
39 # ----------------------------
40 # -  ?  Heading identifiers (php md, pandoc)
41 # - [x] Fenced code blocks (php md, pandoc)
42 #   - [-] Fenced code attributes
43 # - [ ] Tables
44 #   -  ?  Simple table (pandoc)
45 #   -  ?  Multiline table (pandoc)
46 #   -  ?  Grid table (pandoc)
47 #   -  ?  Pipe table (php md pandoc)
48 # - [x] Line blocks (pandoc)
49 # - [ ] Task lists (pandoc)
50 # - [ ] Definition lists (php md, pandoc)
51 # - [-] Numbered example lists (pandoc)
52 # - [-] Metadata blocks (pandoc)
53 # - [-] Fenced Divs (pandoc)
54 #
55 # Extensions - Inline elements:
56 # ----------------------------
57 # - [x] Ignore embedded_underscores (php md, pandoc)
58 # - [x] ~~strikeout~~ (pandoc)
59 # - [x] ^Superscript^ ~Subscript~ (pandoc)
60 # - [-] Bracketed spans (pandoc)
61 #   - [-] Inline attributes (pandoc)
62 # - [-] TEX-Math (pandoc)
63 # -  ?  Footnotes (php md)
64 # -  ?  Abbreviations (php md)
65 # -  ?  "Curly quotes" (smartypants)
66 # - [ ] em-dashes (--) (smartypants old)
67 # -  ?  ... three-dot ellipsis (smartypants)
68 # - [-] en-dash (smartypants)
69 # - [ ] Automatic em-dash / en-dash
70 # - [ ] Automatic -> Arrows <-
71
72 function debug(text) { printf "\n---\n%s\n---\n", text > "/dev/stderr"; }
73
74 function HTML ( text ) {
75   gsub( /&/,  "\\&amp;",  text );
76   gsub( /</,  "\\&lt;",   text );
77   gsub( />/,  "\\&gt;",   text );
78   gsub( /"/,  "\\&quot;", text );
79   gsub( /'/,  "\\&#x27;", text );
80   gsub( /\\/, "\\&#x5C;", text );
81   return text;
82 }
83
84 function inline( line, LOCAL, len, code, href, guard ) {
85   nu = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\_]|_[[:alnum:]])*"    # not underline (except when escaped)
86   na = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\\\*])*"  # not asterisk (except when escaped)
87   ieu =  "_([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])_"                 # inner <em> (underline)
88   isu = "__([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])__"                # inner <strong> (underline)
89   iea =    "\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*"     # inner <em> (asterisk)
90   isa = "\\*\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*\\*"  # inner <strong> (asterisk)
91
92   if ( line ~ /^$/ ) {  # Recursion End
93     return "";
94
95   #  omit processing of escaped characters
96   } else if ( line ~ /^\\[]\\`\*_\{\}\(\)#\+-\.![]/) {
97     return substr(line, 2, 1) inline( substr(line, 3) );
98
99   # hard brakes
100   } else if ( match(line, /^  \n/) ) {
101     return "<br />\n" inline( substr(line, RLENGTH + 1) );
102
103   #  ``code spans``
104   } else if ( match( line, /^`+/) ) {
105     len = RLENGTH
106     guard = substr( line, 1, len )
107     if ( match(line, guard ".*" guard) ) {
108       code = substr( line, len + 1, match( substr(line, len + 1), guard ) - 1)
109       len = 2 * length(guard) + length(code)
110       #  strip single surrounding white spaces
111       code = gensub( / (.*) /, "\\1", "1" , code)
112       #  escape HTML within code span
113       gsub( /&/, "\\&amp;", code ); gsub( /</, "\\&lt;", code ); gsub( />/, "\\&gt;", code );
114       return "<code>" code "</code>" inline( substr( line, len + 1 ) )
115     }
116
117   #  quick links ("automatic links" in md doc)
118   } else if ( match( line, /^<[a-zA-Z]+:\/\/([-\.[:alnum:]]+)(:[0-9]*)?(\/[^>]*)?>/ ) ) {
119     len = RLENGTH;
120     href = HTML( substr( line, 2, len - 2) );
121     return "<a href=\"" href "\">" href "</a>" inline( substr( line, len + 1) );
122
123   # inline links
124   } else if ( match(line, /^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/) ) {
125     len = RLENGTH;
126     text  = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\1", "g", line);
127     href  = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\2", "g", line);
128     title = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\4", "g", line);
129     if ( title ) {
130       return "<a href=\"" HTML(href) "\" title=\"" HTML(title) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
131     } else {
132       return "<a href=\"" HTML(href) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
133     }
134
135   # reference style links
136   } else if ( match(line, /^\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
137     len = RLENGTH;
138     text = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, line);
139       id = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, line);
140     if ( ! id ) id = text;
141     if ( rl_href[id] && rl_title[id] ) {
142       return "<a href=\"" rl_href[id] "\" title=\"" rl_title[id] "\">" inline(text) "</a>" inline( substr( line, len + 1) );
143     } else if ( rl_href[id] ) {
144       return "<a href=\"" rl_href[id] "\">" inline(text) "</a>" inline( substr( line, len + 1) );
145     } else {
146       return "" substr(line, 1, len) inline( substr(line, len + 1) );
147     }
148
149   # inline images
150   } else if ( match(line, /^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/) ) {
151     len = RLENGTH;
152     text  = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\1", "g", line);
153     href  = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\2", "g", line);
154     title = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\4", "g", line);
155     if ( title ) {
156       return "<img src=\"" HTML(href) "\" alt=\"" HTML(text) "\" title=\"" HTML(title) "\" />" inline( substr( line, len + 1) );
157     } else {
158       return "<img src=\"" HTML(href) "\" alt=\"" HTML(text) "\" />" inline( substr( line, len + 1) );
159     }
160
161   # reference style images
162   } else if ( match(line, /^!\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
163     len = RLENGTH;
164     text = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, line);
165       id = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, line);
166     if ( ! id ) id = text;
167     if ( rl_href[id] && rl_title[id] ) {
168       return "<img src=\"" rl_href[id] "\" alt=\"" HTML(text) "\" title=\"" rl_title[id] "\" />" inline( substr( line, len + 1) );
169     } else if ( rl_href[id] ) {
170       return "<img src=\"" rl_href[id] "\" alt=\"" HTML(text) "\" />" inline( substr( line, len + 1) );
171     } else {
172       return "" substr(line, 1, len) inline( substr(line, len + 1) );
173     }
174
175   #  ~~strikeout~~ (pandoc)
176   } else if ( match(line, /^~~([[:graph:]]|[[:graph:]]([^~]|~[^~])*[[:graph:]])~~/) ) {
177     len = RLENGTH;
178     return "<del>" inline( substr( line, 3, len - 4 ) ) "</del>" inline( substr( line, len + 1 ) );
179
180   #  ^superscript^ (pandoc)
181   } else if ( match(line, /^\^([^[:space:]^]|\\[ ^])+\^/) ) {
182     len = RLENGTH;
183     return "<sup>" inline( substr( line, 2, len - 2 ) ) "</sup>" inline( substr( line, len + 1 ) );
184
185   #  ~subscript~ (pandoc)
186   } else if ( match(line, /^~([^[:space:]~]|\\[ ~])+~/) ) {
187     len = RLENGTH;
188     return "<sub>" inline( substr( line, 2, len - 2 ) ) "</sub>" inline( substr( line, len + 1 ) );
189
190   # ignore embedded underscores (pandoc, php md)
191   } else if ( match(line, "^[[:alnum:]](__|_)") ) {
192     return substr( line, 1, RLENGTH) inline( substr(line, RLENGTH + 1) );
193
194   #  __strong__$
195   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__$") ) {
196     len = RLENGTH;
197     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
198
199   #  __strong__
200   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__[[:space:]]") ) {
201     len = RLENGTH;
202     return "<strong>" inline( substr( line, 3, len - 5 ) ) "</strong>" inline( substr( line, len) );
203
204   #  **strong**
205   } else if ( match(line, "^\\*\\*(([^\\*[:space:]]|" iea ")|([^\\*[:space:]]|" iea ")(" na "|" iea ")*([^\\*[:space:]]|" iea "))\\*\\*") ) {
206     len = RLENGTH;
207     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
208
209   #  _em_$
210   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_$") ) {
211     len = RLENGTH;
212     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
213
214   #  _em_
215   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_[[:space:]]") ) {
216     len = RLENGTH;
217     return "<em>" inline( substr( line, 2, len - 3 ) ) "</em>" inline( substr( line, len ) );
218
219   #  *em*
220   } else if ( match(line, "^\\*(([^\\*[:space:]]|" isa ")|([^\\*[:space:]]|" isa ")(" na "|" isa ")*([^\\*[:space:]]|" isa "))\\*") ) {
221     len = RLENGTH;
222     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
223
224   #  continue walk over string
225   } else {
226     return substr(line, 1, 1) inline( substr(line, 2) );
227   }
228 }
229
230 function _block( block, LOCAL, st, len, hlvl, htxt, guard, code, indent ) {
231   gsub( /^\n+|\n+$/, "", block );
232
233   if ( block == "" ) {
234     return "";
235
236   # Horizontal rule
237   } else if ( match( block, /(^|\n) ? ? ?((\* *){3,}|(- *){3,}|(_ *){3,})($|\n)/) ) {
238     len = RLENGTH; st = RSTART;
239     return _block(substr(block, 1, st - 1)) "<hr />\n" _block(substr(block, st + len));
240  
241   # Blockquote (leading >)
242   } else if ( match( block, /^> /) ) {
243     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
244     len = RLENGTH; st = RSTART;
245     return "<blockquote>\n" _block( gensub( /(^|\n)> /, "\n", "g", substr(block, 1, st - 1) ) ) "</blockquote>\n\n" \
246            _block( substr(block, st + len) );
247
248   # Line Blocks (pandoc)
249   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
250     len = RLENGTH; st = RSTART;
251     code = substr(block, 1, len);
252     gsub(/\n[[:space:]]+/, " ", code);
253     gsub(/\n\| /, "\n", code);
254     gsub(/^\| |\n$/, "", code);
255     return "<div class=\"line-block\">" gensub(/\n/, "<br />\n", "g", inline( code )) "</div>\n" \
256            _block( substr( block, len + 1) );
257
258   # Indented Code Block
259   } else if ( match(block, /^(    |\t)[^\n]+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
260     len = RLENGTH; st = RSTART;
261     code = substr(block, 1, len);
262     gsub(/(^|\n)(    |\t)/, "\n", code);
263     gsub(/^\n|\n+$/, "", code);
264     return "<pre><code>" HTML( code ) "</code></pre>\n" \
265            _block( substr( block, len + 1 ) );
266
267   # Fenced Code Block (pandoc)
268   } else if ( match( block, /^(~~~+|```+)/ ) ) {
269     guard = substr( block, 1, RLENGTH );
270     code = gensub(/^[^\n]+\n/, "", 1, block);
271     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
272       len = RLENGTH; st = RSTART;
273       return "<pre><code>" HTML( substr(code, 1, st - 1) ) "</code></pre>\n" \
274              _block( substr( code, st + len ) );
275     } else {
276       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
277       len = RLENGTH; st = RSTART;
278       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
279              _block( substr(block, st + len) );
280     }
281
282   # Unordered list
283   } else if ( match( block, "^ ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
284                             "(([ \t]*\n)* ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
285                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
286                             "|[^\n]+(\n|$))*" ) ) {
287   list = substr( block, 1, RLENGTH);
288   block = substr( block, RLENGTH + 1);
289   indent = length( gensub(/[-+*][ \t]+[^\n]+.*$/, "", 1, list) );
290
291   gsub("(^|\n) {0," indent "}", "\n", list);
292   return "\n<ul>\n" _list( substr(list, 2) ) "</ul>\n" _block( block );
293
294   # Ordered list
295   } else if ( match( block, "^ ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
296                             "(([ \t]*\n)* ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
297                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
298                             "|[^\n]+(\n|$))*" ) ) {
299   list = substr( block, 1, RLENGTH);
300   block = substr( block, RLENGTH + 1);
301   indent = length( gensub(/([0-9]+|#)\.[ \t]+[^\n]+.*$/, "", 1, list) );
302
303   gsub("(^|\n) {0," indent "}", "\n", list);
304   return "\n<ol>\n" _list( substr(list, 2) ) "</ol>\n" _block( block );
305
306   # First Order Heading
307   } else if ( match( block, /^[^\n]+\n===+(\n|$)/ ) ) {
308     len = RLENGTH;
309     return "<h1>" inline( gensub( /\n.*$/, "", "g", block ) ) "</h1>\n\n" \
310            _block( substr( block, len + 1 ) );
311
312   # Second Order Heading
313   } else if ( match( block, /^[^\n]+\n---+(\n|$)/ ) ) {
314     len = RLENGTH;
315     return "<h2>" inline( gensub( /\n.*$/, "", "g", block ) ) "</h2>\n\n" \
316            _block( substr( block, len + 1) );
317
318   # Nth Order Heading
319   } else if ( match( block, /^#{1,6}[[:space:]]*[^\n]+([[:space:]]*#*)(\n|$)/ ) ) {
320     len = RLENGTH;
321     hlvl = length( gensub( /^(#{1,6}).*$/, "\\1", "g", block ) );
322     htxt = gensub( /[[:space:]]*#*$/, "", "1", gensub( /^#{1,6}[[:space:]]*([^\n]+)([[:space:]]*#*)\n.*$/, "\\1", "g", block ) )
323     return "<h" hlvl ">" inline( htxt ) "</h" hlvl ">\n\n" \
324            _block( substr( block, len + 1) );
325
326   # Plain paragraph
327   } else {
328     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
329     len = RLENGTH; st = RSTART;
330     return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
331            _block( substr(block, st + len) );
332   }
333 }
334
335 function _list( block, last, LOCAL, p) {
336   if ( ! length(block) ) return "";
337   gsub(/^([-+*]|[0-9]+\.|#\.)(  ? ? ?|\t)/, "", block)
338
339   # slice next list item from input
340   if ( match( block, /\n([-+*]|[0-9]+\.|#\.)[ \t]+[^\n]+/) ) {
341     p = substr( block, 1, RSTART);
342     block = substr( block, RSTART + 1);
343   } else {
344     p = block; block = "";
345   }
346   sub( /\n +([-+*]|[0-9]+\.|#\.)/, "\n&", p );
347
348   # if this should be a paragraph item
349   # either previous item (last) or current item (p) contains blank lines
350   if (match(last, /\n[[:space:]]*\n/) || match(p, /\n[[:space:]]*\n/) ) {
351     last = p; p = _block(p);
352   } else {
353     last = p; p = _block(p);
354     sub( /^<p>/, "", p );
355     sub( /<\/p>\n/, "", p );
356   }
357   sub( /\n$/, "", p );
358   return "<li>" p "</li>\n" _list( block, last );
359 }
360
361 BEGIN {
362   # Global Vars
363   file = ""; rl_href[""] = ""; rl_title[""] = "";
364
365   # Buffering of full file ist necessary, e.g. to find reference links
366   while (getline) { file = file $0 "\n"; }
367
368   # Fill array of reference links
369   f = file; rl_id;
370   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
371   # /(^|\n) ? ? ?\[([^]\n]+)\]: ([^ \t\n]+)(\n?[ \t]+("([^"]+)"|'([^']+)'|\(([^)]+)\)))?(\n|$)/
372   while ( match(f, re_reflink ) ) {
373     rl_id           = gensub( re_reflink, "\\2", 1, substr(f, RSTART, RLENGTH) );
374     rl_href[rl_id]  = gensub( re_reflink, "\\3", 1, substr(f, RSTART, RLENGTH) );
375     rl_title[rl_id] = gensub( re_reflink, "\\5", 1, substr(f, RSTART, RLENGTH) );
376     f = substr(f, RSTART + RLENGTH);
377     rl_title[rl_id] = substr( rl_title[rl_id], 2, length(rl_title[rl_id]) - 2 );
378     if ( rl_href[rl_id] ~ /<.*>/ ) rl_href[rl_id] = substr( rl_href[rl_id], 2, length(rl_href[rl_id]) - 2 );
379   }
380   # Clear reflinks from File
381   while( gsub(re_reflink, "\n", file ) );
382   # for (n in rl_href) { debug(n " | " rl_href[n] " | " rl_title[n] ); }
383
384   # Run Block Processing -> The Actual Markdown!
385   printf "%s", _block( file );
386 }