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