]> git.plutz.net Git - cgilite/blob - markdown.awk
md: allow hard line breaks; md extension: ignore embedded underscores
[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 # - [ ] 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 (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   #  ~~strikeout~~ (pandoc)
150   } else if ( match(line, /^~~([[:graph:]]|[[:graph:]]([^~]|~[^~])*[[:graph:]])~~/) ) {
151     len = RLENGTH;
152     return "<del>" inline( substr( line, 3, len - 4 ) ) "</del>" inline( substr( line, len + 1 ) );
153
154   #  ^superscript^ (pandoc)
155   } else if ( match(line, /^\^([^[:space:]^]|\\[ ^])+\^/) ) {
156     len = RLENGTH;
157     return "<sup>" inline( substr( line, 2, len - 2 ) ) "</sup>" inline( substr( line, len + 1 ) );
158
159   #  ~subscript~ (pandoc)
160   } else if ( match(line, /^~([^[:space:]~]|\\[ ~])+~/) ) {
161     len = RLENGTH;
162     return "<sub>" inline( substr( line, 2, len - 2 ) ) "</sub>" inline( substr( line, len + 1 ) );
163
164   # ignore embedded underscores (pandoc, php md)
165   } else if ( match(line, "^[[:alnum:]](__|_)") ) {
166     return substr( line, 1, RLENGTH) inline( substr(line, RLENGTH + 1) );
167
168   #  __strong__$
169   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__$") ) {
170     len = RLENGTH;
171     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
172
173   #  __strong__
174   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__[[:space:]]") ) {
175     len = RLENGTH;
176     return "<strong>" inline( substr( line, 3, len - 5 ) ) "</strong>" inline( substr( line, len) );
177
178   #  **strong**
179   } else if ( match(line, "^\\*\\*(([^\\*[:space:]]|" iea ")|([^\\*[:space:]]|" iea ")(" na "|" iea ")*([^\\*[:space:]]|" iea "))\\*\\*") ) {
180     len = RLENGTH;
181     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
182
183   #  _em_$
184   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_$") ) {
185     len = RLENGTH;
186     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
187
188   #  _em_
189   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_[[:space:]]") ) {
190     len = RLENGTH;
191     return "<em>" inline( substr( line, 2, len - 3 ) ) "</em>" inline( substr( line, len ) );
192
193   #  *em*
194   } else if ( match(line, "^\\*(([^\\*[:space:]]|" isa ")|([^\\*[:space:]]|" isa ")(" na "|" isa ")*([^\\*[:space:]]|" isa "))\\*") ) {
195     len = RLENGTH;
196     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
197
198   #  continue walk over string
199   } else {
200     return substr(line, 1, 1) inline( substr(line, 2) );
201   }
202 }
203
204 function _block( block, LOCAL, st, len, hlvl, htxt, guard, code, indent ) {
205   gsub( /^\n+|\n+$/, "", block );
206
207   if ( block == "" ) {
208     return "";
209  
210   # Blockquote (leading >)
211   } else if ( match( block, /^> /) ) {
212     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
213     len = RLENGTH; st = RSTART;
214     return "<blockquote>\n" _block( gensub( /(^|\n)> /, "\n", "g", substr(block, 1, st - 1) ) ) "</blockquote>\n\n" \
215            _block( substr(block, st + len) );
216
217   # Line Blocks (pandoc)
218   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
219     len = RLENGTH; st = RSTART;
220     code = substr(block, 1, len);
221     gsub(/\n[[:space:]]+/, " ", code);
222     gsub(/\n\| /, "\n", code);
223     gsub(/^\| |\n$/, "", code);
224     return "<div class=\"line-block\">" gensub(/\n/, "<br />\n", "g", inline( code )) "</div>\n" \
225            _block( substr( block, len + 1) );
226
227   # Indented Code Block
228   } else if ( match(block, /^(    |\t)[^\n]+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
229     len = RLENGTH; st = RSTART;
230     code = substr(block, 1, len);
231     gsub(/(^|\n)(    |\t)/, "\n", code);
232     gsub(/^\n|\n+$/, "", code);
233     return "<pre><code>" HTML( code ) "</code></pre>\n" \
234            _block( substr( block, len + 1 ) );
235
236   # Fenced Code Block (pandoc)
237   } else if ( match( block, /^(~~~+|```+)/ ) ) {
238     guard = substr( block, 1, RLENGTH );
239     code = gensub(/^[^\n]+\n/, "", 1, block);
240     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
241       len = RLENGTH; st = RSTART;
242       return "<pre><code>" HTML( substr(code, 1, st - 1) ) "</code></pre>\n" \
243              _block( substr( code, st + len ) );
244     } else {
245       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
246       len = RLENGTH; st = RSTART;
247       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
248              _block( substr(block, st + len) );
249     }
250
251   # Unordered list
252   } else if ( match( block, "^ ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
253                             "(([ \t]*\n)* ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
254                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
255                             "|[^\n]+(\n|$))*" ) ) {
256   list = substr( block, 1, RLENGTH);
257   block = substr( block, RLENGTH + 1);
258   indent = length( gensub(/[-+*][ \t]+[^\n]+.*$/, "", 1, list) );
259
260   gsub("(^|\n) {0," indent "}", "\n", list);
261   return "\n<ul>\n" _list( substr(list, 2) ) "</ul>\n" _block( block );
262
263   # Ordered list
264   } else if ( match( block, "^ ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
265                             "(([ \t]*\n)* ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
266                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
267                             "|[^\n]+(\n|$))*" ) ) {
268   list = substr( block, 1, RLENGTH);
269   block = substr( block, RLENGTH + 1);
270   indent = length( gensub(/([0-9]+|#)\.[ \t]+[^\n]+.*$/, "", 1, list) );
271
272   gsub("(^|\n) {0," indent "}", "\n", list);
273   return "\n<ol>\n" _list( substr(list, 2) ) "</ol>\n" _block( block );
274
275   # First Order Heading
276   } else if ( match( block, /^[^\n]+\n===+(\n|$)/ ) ) {
277     len = RLENGTH;
278     return "<h1>" inline( gensub( /\n.*$/, "", "g", block ) ) "</h1>\n\n" \
279            _block( substr( block, len + 1 ) );
280
281   # Second Order Heading
282   } else if ( match( block, /^[^\n]+\n---+(\n|$)/ ) ) {
283     len = RLENGTH;
284     return "<h2>" inline( gensub( /\n.*$/, "", "g", block ) ) "</h2>\n\n" \
285            _block( substr( block, len + 1) );
286
287   # Nth Order Heading
288   } else if ( match( block, /^#{1,6}[[:space:]]*[^\n]+([[:space:]]*#*)(\n|$)/ ) ) {
289     len = RLENGTH;
290     hlvl = length( gensub( /^(#{1,6}).*$/, "\\1", "g", block ) );
291     htxt = gensub( /[[:space:]]*#*$/, "", "1", gensub( /^#{1,6}[[:space:]]*([^\n]+)([[:space:]]*#*)\n.*$/, "\\1", "g", block ) )
292     return "<h" hlvl ">" inline( htxt ) "</h" hlvl ">\n\n" \
293            _block( substr( block, len + 1) );
294
295   # Plain paragraph
296   } else {
297     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
298     len = RLENGTH; st = RSTART;
299     return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
300            _block( substr(block, st + len) );
301   }
302 }
303
304 function _list( block, last, LOCAL, p) {
305   if ( ! length(block) ) return "";
306   gsub(/^([-+*]|[0-9]+\.|#\.)(  ? ? ?|\t)/, "", block)
307
308   # slice next list item from input
309   if ( match( block, /\n([-+*]|[0-9]+\.|#\.)[ \t]+[^\n]+/) ) {
310     p = substr( block, 1, RSTART);
311     block = substr( block, RSTART + 1);
312   } else {
313     p = block; block = "";
314   }
315   sub( /\n +([-+*]|[0-9]+\.|#\.)/, "\n&", p );
316
317   # if this should be a paragraph item
318   # either previous item (last) or current item (p) contains blank lines
319   if (match(last, /\n[[:space:]]*\n/) || match(p, /\n[[:space:]]*\n/) ) {
320     last = p; p = _block(p);
321   } else {
322     last = p; p = _block(p);
323     sub( /^<p>/, "", p );
324     sub( /<\/p>\n/, "", p );
325   }
326   sub( /\n$/, "", p );
327   return "<li>" p "</li>\n" _list( block, last );
328 }
329
330 BEGIN {
331   # Global Vars
332   file = ""; rl_href[""] = ""; rl_title[""] = "";
333
334   # Buffering of full file ist necessary, e.g. to find reference links
335   while (getline) { file = file $0 "\n"; }
336
337   # Fill array of reference links
338   f = file; rl_id;
339   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
340   # /(^|\n) ? ? ?\[([^]\n]+)\]: ([^ \t\n]+)(\n?[ \t]+("([^"]+)"|'([^']+)'|\(([^)]+)\)))?(\n|$)/
341   while ( match(f, re_reflink ) ) {
342     rl_id           = gensub( re_reflink, "\\2", 1, substr(f, RSTART, RLENGTH) );
343     rl_href[rl_id]  = gensub( re_reflink, "\\3", 1, substr(f, RSTART, RLENGTH) );
344     rl_title[rl_id] = gensub( re_reflink, "\\5", 1, substr(f, RSTART, RLENGTH) );
345     f = substr(f, RSTART + RLENGTH);
346     rl_title[rl_id] = substr( rl_title[rl_id], 2, length(rl_title[rl_id]) - 2 );
347     if ( rl_href[rl_id] ~ /<.*>/ ) rl_href[rl_id] = substr( rl_href[rl_id], 2, length(rl_href[rl_id]) - 2 );
348   }
349   # Clear reflinks from File
350   while( gsub(re_reflink, "\n", file ) );
351   # for (n in rl_href) { debug(n " | " rl_href[n] " | " rl_title[n] ); }
352
353   # Run Block Processing -> The Actual Markdown!
354   printf "%s", _block( file );
355 }