]> git.plutz.net Git - cgilite/blob - markdown.awk
todo items
[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 # - [ ] 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 = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\_])*"    # 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   #  ``code spans``
100   } else if ( match( line, /^`+/) ) {
101     len = RLENGTH
102     guard = substr( line, 1, len )
103     if ( match(line, guard ".*" guard) ) {
104       code = substr( line, len + 1, match( substr(line, len + 1), guard ) - 1)
105       len = 2 * length(guard) + length(code)
106       #  strip single surrounding white spaces
107       code = gensub( / (.*) /, "\\1", "1" , code)
108       #  escape HTML within code span
109       gsub( /&/, "\\&amp;", code ); gsub( /</, "\\&lt;", code ); gsub( />/, "\\&gt;", code );
110       return "<code>" code "</code>" inline( substr( line, len + 1 ) )
111     }
112
113   #  quick links ("automatic links" in md doc)
114   } else if ( match( line, /^<[a-zA-Z]+:\/\/([-\.[:alnum:]]+)(:[0-9]*)?(\/[^>]*)?>/ ) ) {
115     len = RLENGTH;
116     href = HTML( substr( line, 2, len - 2) );
117     return "<a href=\"" href "\">" href "</a>" inline( substr( line, len + 1) );
118
119   # inline links
120   } else if ( match(line, /^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/) ) {
121     len = RLENGTH;
122     text  = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\1", "g", line);
123     href  = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\2", "g", line);
124     title = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\4", "g", line);
125     if ( title ) {
126       return "<a href=\"" HTML(href) "\" title=\"" HTML(title) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
127     } else {
128       return "<a href=\"" HTML(href) "\">" inline( text ) "</a>" inline( substr( line, len + 1) );
129     }
130
131   # reference style links
132   } else if ( match(line, /^\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
133     len = RLENGTH;
134     text = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, line);
135       id = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, line);
136     if ( ! id ) id = text;
137     if ( rl_href[id] && rl_title[id] ) {
138       return "<a href=\"" rl_href[id] "\" title=\"" rl_title[id] "\">" inline(text) "</a>" inline( substr( line, len + 1) );
139     } else if ( rl_href[id] ) {
140       return "<a href=\"" rl_href[id] "\">" inline(text) "</a>" inline( substr( line, len + 1) );
141     } else {
142       return "" substr(line, 1, len) inline( substr(line, len + 1) );
143     }
144
145   #  ~~strikeout~~ (pandoc)
146   } else if ( match(line, /^~~([[:graph:]]|[[:graph:]]([^~]|~[^~])*[[:graph:]])~~/) ) {
147     len = RLENGTH;
148     return "<del>" inline( substr( line, 3, len - 4 ) ) "</del>" inline( substr( line, len + 1 ) );
149
150   #  ^superscript^ (pandoc)
151   } else if ( match(line, /^\^([^[:space:]^]|\\[ ^])+\^/) ) {
152     len = RLENGTH;
153     return "<sup>" inline( substr( line, 2, len - 2 ) ) "</sup>" inline( substr( line, len + 1 ) );
154
155   #  ~subscript~ (pandoc)
156   } else if ( match(line, /^~([^[:space:]~]|\\[ ~])+~/) ) {
157     len = RLENGTH;
158     return "<sub>" inline( substr( line, 2, len - 2 ) ) "</sub>" inline( substr( line, len + 1 ) );
159
160   #  __strong__
161   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__") ) {
162     len = RLENGTH;
163     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
164
165   #  **strong**
166   } else if ( match(line, "^\\*\\*(([^\\*[:space:]]|" iea ")|([^\\*[:space:]]|" iea ")(" na "|" iea ")*([^\\*[:space:]]|" iea "))\\*\\*") ) {
167     len = RLENGTH;
168     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
169
170   #  _em_
171   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_") ) {
172     len = RLENGTH;
173     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
174
175   #  *em*
176   } else if ( match(line, "^\\*(([^\\*[:space:]]|" isa ")|([^\\*[:space:]]|" isa ")(" na "|" isa ")*([^\\*[:space:]]|" isa "))\\*") ) {
177     len = RLENGTH;
178     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
179
180   #  continue walk over string
181   } else {
182     return substr(line, 1, 1) inline( substr(line, 2) );
183   }
184 }
185
186 function _block( block, LOCAL, st, len, hlvl, htxt, guard, code, indent ) {
187   gsub( /^\n+|\n+$/, "", block );
188
189   if ( block == "" ) {
190     return "";
191  
192   # Blockquote (leading >)
193   } else if ( match( block, /^> /) ) {
194     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
195     len = RLENGTH; st = RSTART;
196     return "<blockquote>\n" _block( gensub( /(^|\n)> /, "\n", "g", substr(block, 1, st - 1) ) ) "</blockquote>\n\n" \
197            _block( substr(block, st + len) );
198
199   # Line Blocks (pandoc)
200   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
201     len = RLENGTH; st = RSTART;
202     code = substr(block, 1, len);
203     gsub(/\n[[:space:]]+/, " ", code);
204     gsub(/\n\| /, "\n", code);
205     gsub(/^\| |\n$/, "", code);
206     return "<div class=\"line-block\">" gensub(/\n/, "<br />\n", "g", inline( code )) "</div>\n" \
207            _block( substr( block, len + 1) );
208
209   # Indented Code Block
210   } else if ( match(block, /^(    |\t)[^\n]+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
211     len = RLENGTH; st = RSTART;
212     code = substr(block, 1, len);
213     gsub(/(^|\n)(    |\t)/, "\n", code);
214     gsub(/^\n|\n+$/, "", code);
215     return "<pre><code>" HTML( code ) "</code></pre>\n" \
216            _block( substr( block, len + 1 ) );
217
218   # Fenced Code Block (pandoc)
219   } else if ( match( block, /^(~~~+|```+)/ ) ) {
220     guard = substr( block, 1, RLENGTH );
221     code = gensub(/^[^\n]+\n/, "", 1, block);
222     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
223       len = RLENGTH; st = RSTART;
224       return "<pre><code>" HTML( substr(code, 1, st - 1) ) "</code></pre>\n" \
225              _block( substr( code, st + len ) );
226     } else {
227       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
228       len = RLENGTH; st = RSTART;
229       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
230              _block( substr(block, st + len) );
231     }
232
233   # Unordered list
234   } else if ( match( block, "^ ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
235                             "(([ \t]*\n)* ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
236                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
237                             "|[^\n]+(\n|$))*" ) ) {
238   list = substr( block, 1, RLENGTH);
239   block = substr( block, RLENGTH + 1);
240   indent = length( gensub(/[-+*][ \t]+[^\n]+.*$/, "", 1, list) );
241
242   gsub("(^|\n) {0," indent "}", "\n", list);
243   return "\n<ul>\n" _list( substr(list, 2) ) "</ul>\n" _block( block );
244
245   # Ordered list
246   } else if ( match( block, "^ ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
247                             "(([ \t]*\n)* ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
248                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
249                             "|[^\n]+(\n|$))*" ) ) {
250   list = substr( block, 1, RLENGTH);
251   block = substr( block, RLENGTH + 1);
252   indent = length( gensub(/([0-9]+|#)\.[ \t]+[^\n]+.*$/, "", 1, list) );
253
254   gsub("(^|\n) {0," indent "}", "\n", list);
255   return "\n<ol>\n" _list( substr(list, 2) ) "</ol>\n" _block( block );
256
257   # First Order Heading
258   } else if ( match( block, /^[^\n]+\n===+(\n|$)/ ) ) {
259     len = RLENGTH;
260     return "<h1>" inline( gensub( /\n.*$/, "", "g", block ) ) "</h1>\n\n" \
261            _block( substr( block, len + 1 ) );
262
263   # Second Order Heading
264   } else if ( match( block, /^[^\n]+\n---+(\n|$)/ ) ) {
265     len = RLENGTH;
266     return "<h2>" inline( gensub( /\n.*$/, "", "g", block ) ) "</h2>\n\n" \
267            _block( substr( block, len + 1) );
268
269   # Nth Order Heading
270   } else if ( match( block, /^#{1,6}[[:space:]]*[^\n]+([[:space:]]*#*)(\n|$)/ ) ) {
271     len = RLENGTH;
272     hlvl = length( gensub( /^(#{1,6}).*$/, "\\1", "g", block ) );
273     htxt = gensub( /[[:space:]]*#*$/, "", "1", gensub( /^#{1,6}[[:space:]]*([^\n]+)([[:space:]]*#*)\n.*$/, "\\1", "g", block ) )
274     return "<h" hlvl ">" inline( htxt ) "</h" hlvl ">\n\n" \
275            _block( substr( block, len + 1) );
276
277   # Plain paragraph
278   } else {
279     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
280     len = RLENGTH; st = RSTART;
281     return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
282            _block( substr(block, st + len) );
283   }
284 }
285
286 function _list( block, last, LOCAL, p) {
287   if ( ! length(block) ) return "";
288   gsub(/^([-+*]|[0-9]+\.|#\.)(  ? ? ?|\t)/, "", block)
289
290   # slice next list item from input
291   if ( match( block, /\n([-+*]|[0-9]+\.|#\.)[ \t]+[^\n]+/) ) {
292     p = substr( block, 1, RSTART);
293     block = substr( block, RSTART + 1);
294   } else {
295     p = block; block = "";
296   }
297   sub( /\n +([-+*]|[0-9]+\.|#\.)/, "\n&", p );
298
299   # if this should be a paragraph item
300   # either previous item (last) or current item (p) contains blank lines
301   if (match(last, /\n[[:space:]]*\n/) || match(p, /\n[[:space:]]*\n/) ) {
302     last = p; p = _block(p);
303   } else {
304     last = p; p = _block(p);
305     sub( /^<p>/, "", p );
306     sub( /<\/p>\n/, "", p );
307   }
308   sub( /\n$/, "", p );
309   return "<li>" p "</li>\n" _list( block, last );
310 }
311
312 BEGIN {
313   # Global Vars
314   file = ""; rl_href[""] = ""; rl_title[""] = "";
315
316   # Buffering of full file ist necessary, e.g. to find reference links
317   while (getline) { file = file $0 "\n"; }
318
319   # Fill array of reference links
320   f = file; rl_id;
321   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
322   # /(^|\n) ? ? ?\[([^]\n]+)\]: ([^ \t\n]+)(\n?[ \t]+("([^"]+)"|'([^']+)'|\(([^)]+)\)))?(\n|$)/
323   while ( match(f, re_reflink ) ) {
324     rl_id           = gensub( re_reflink, "\\2", 1, substr(f, RSTART, RLENGTH) );
325     rl_href[rl_id]  = gensub( re_reflink, "\\3", 1, substr(f, RSTART, RLENGTH) );
326     rl_title[rl_id] = gensub( re_reflink, "\\5", 1, substr(f, RSTART, RLENGTH) );
327     f = substr(f, RSTART + RLENGTH);
328     rl_title[rl_id] = substr( rl_title[rl_id], 2, length(rl_title[rl_id]) - 2 );
329     if ( rl_href[rl_id] ~ /<.*>/ ) rl_href[rl_id] = substr( rl_href[rl_id], 2, length(rl_href[rl_id]) - 2 );
330   }
331   # Clear reflinks from File
332   while( gsub(re_reflink, "\n", file ) );
333   # for (n in rl_href) { debug(n " | " rl_href[n] " | " rl_title[n] ); }
334
335   # Run Block Processing -> The Actual Markdown!
336   printf "%s", _block( file );
337 }