]> git.plutz.net Git - cgilite/blob - markdown.awk
md: horizontal rules
[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 # - [ ] 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   # Horizontal rule
211   } else if ( match( block, /(^|\n) ? ? ?((\* *){3,}|(- *){3,}|(_ *){3,})($|\n)/) ) {
212     len = RLENGTH; st = RSTART;
213     return _block(substr(block, 1, st - 1)) "<hr />\n" _block(substr(block, st + len));
214  
215   # Blockquote (leading >)
216   } else if ( match( block, /^> /) ) {
217     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
218     len = RLENGTH; st = RSTART;
219     return "<blockquote>\n" _block( gensub( /(^|\n)> /, "\n", "g", substr(block, 1, st - 1) ) ) "</blockquote>\n\n" \
220            _block( substr(block, st + len) );
221
222   # Line Blocks (pandoc)
223   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
224     len = RLENGTH; st = RSTART;
225     code = substr(block, 1, len);
226     gsub(/\n[[:space:]]+/, " ", code);
227     gsub(/\n\| /, "\n", code);
228     gsub(/^\| |\n$/, "", code);
229     return "<div class=\"line-block\">" gensub(/\n/, "<br />\n", "g", inline( code )) "</div>\n" \
230            _block( substr( block, len + 1) );
231
232   # Indented Code Block
233   } else if ( match(block, /^(    |\t)[^\n]+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
234     len = RLENGTH; st = RSTART;
235     code = substr(block, 1, len);
236     gsub(/(^|\n)(    |\t)/, "\n", code);
237     gsub(/^\n|\n+$/, "", code);
238     return "<pre><code>" HTML( code ) "</code></pre>\n" \
239            _block( substr( block, len + 1 ) );
240
241   # Fenced Code Block (pandoc)
242   } else if ( match( block, /^(~~~+|```+)/ ) ) {
243     guard = substr( block, 1, RLENGTH );
244     code = gensub(/^[^\n]+\n/, "", 1, block);
245     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
246       len = RLENGTH; st = RSTART;
247       return "<pre><code>" HTML( substr(code, 1, st - 1) ) "</code></pre>\n" \
248              _block( substr( code, st + len ) );
249     } else {
250       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
251       len = RLENGTH; st = RSTART;
252       return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
253              _block( substr(block, st + len) );
254     }
255
256   # Unordered list
257   } else if ( match( block, "^ ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
258                             "(([ \t]*\n)* ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
259                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
260                             "|[^\n]+(\n|$))*" ) ) {
261   list = substr( block, 1, RLENGTH);
262   block = substr( block, RLENGTH + 1);
263   indent = length( gensub(/[-+*][ \t]+[^\n]+.*$/, "", 1, list) );
264
265   gsub("(^|\n) {0," indent "}", "\n", list);
266   return "\n<ul>\n" _list( substr(list, 2) ) "</ul>\n" _block( block );
267
268   # Ordered list
269   } else if ( match( block, "^ ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
270                             "(([ \t]*\n)* ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
271                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
272                             "|[^\n]+(\n|$))*" ) ) {
273   list = substr( block, 1, RLENGTH);
274   block = substr( block, RLENGTH + 1);
275   indent = length( gensub(/([0-9]+|#)\.[ \t]+[^\n]+.*$/, "", 1, list) );
276
277   gsub("(^|\n) {0," indent "}", "\n", list);
278   return "\n<ol>\n" _list( substr(list, 2) ) "</ol>\n" _block( block );
279
280   # First Order Heading
281   } else if ( match( block, /^[^\n]+\n===+(\n|$)/ ) ) {
282     len = RLENGTH;
283     return "<h1>" inline( gensub( /\n.*$/, "", "g", block ) ) "</h1>\n\n" \
284            _block( substr( block, len + 1 ) );
285
286   # Second Order Heading
287   } else if ( match( block, /^[^\n]+\n---+(\n|$)/ ) ) {
288     len = RLENGTH;
289     return "<h2>" inline( gensub( /\n.*$/, "", "g", block ) ) "</h2>\n\n" \
290            _block( substr( block, len + 1) );
291
292   # Nth Order Heading
293   } else if ( match( block, /^#{1,6}[[:space:]]*[^\n]+([[:space:]]*#*)(\n|$)/ ) ) {
294     len = RLENGTH;
295     hlvl = length( gensub( /^(#{1,6}).*$/, "\\1", "g", block ) );
296     htxt = gensub( /[[:space:]]*#*$/, "", "1", gensub( /^#{1,6}[[:space:]]*([^\n]+)([[:space:]]*#*)\n.*$/, "\\1", "g", block ) )
297     return "<h" hlvl ">" inline( htxt ) "</h" hlvl ">\n\n" \
298            _block( substr( block, len + 1) );
299
300   # Plain paragraph
301   } else {
302     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
303     len = RLENGTH; st = RSTART;
304     return "<p>" inline( substr(block, 1, st - 1) ) "</p>\n" \
305            _block( substr(block, st + len) );
306   }
307 }
308
309 function _list( block, last, LOCAL, p) {
310   if ( ! length(block) ) return "";
311   gsub(/^([-+*]|[0-9]+\.|#\.)(  ? ? ?|\t)/, "", block)
312
313   # slice next list item from input
314   if ( match( block, /\n([-+*]|[0-9]+\.|#\.)[ \t]+[^\n]+/) ) {
315     p = substr( block, 1, RSTART);
316     block = substr( block, RSTART + 1);
317   } else {
318     p = block; block = "";
319   }
320   sub( /\n +([-+*]|[0-9]+\.|#\.)/, "\n&", p );
321
322   # if this should be a paragraph item
323   # either previous item (last) or current item (p) contains blank lines
324   if (match(last, /\n[[:space:]]*\n/) || match(p, /\n[[:space:]]*\n/) ) {
325     last = p; p = _block(p);
326   } else {
327     last = p; p = _block(p);
328     sub( /^<p>/, "", p );
329     sub( /<\/p>\n/, "", p );
330   }
331   sub( /\n$/, "", p );
332   return "<li>" p "</li>\n" _list( block, last );
333 }
334
335 BEGIN {
336   # Global Vars
337   file = ""; rl_href[""] = ""; rl_title[""] = "";
338
339   # Buffering of full file ist necessary, e.g. to find reference links
340   while (getline) { file = file $0 "\n"; }
341
342   # Fill array of reference links
343   f = file; rl_id;
344   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
345   # /(^|\n) ? ? ?\[([^]\n]+)\]: ([^ \t\n]+)(\n?[ \t]+("([^"]+)"|'([^']+)'|\(([^)]+)\)))?(\n|$)/
346   while ( match(f, re_reflink ) ) {
347     rl_id           = gensub( re_reflink, "\\2", 1, substr(f, RSTART, RLENGTH) );
348     rl_href[rl_id]  = gensub( re_reflink, "\\3", 1, substr(f, RSTART, RLENGTH) );
349     rl_title[rl_id] = gensub( re_reflink, "\\5", 1, substr(f, RSTART, RLENGTH) );
350     f = substr(f, RSTART + RLENGTH);
351     rl_title[rl_id] = substr( rl_title[rl_id], 2, length(rl_title[rl_id]) - 2 );
352     if ( rl_href[rl_id] ~ /<.*>/ ) rl_href[rl_id] = substr( rl_href[rl_id], 2, length(rl_href[rl_id]) - 2 );
353   }
354   # Clear reflinks from File
355   while( gsub(re_reflink, "\n", file ) );
356   # for (n in rl_href) { debug(n " | " rl_href[n] " | " rl_title[n] ); }
357
358   # Run Block Processing -> The Actual Markdown!
359   printf "%s", _block( file );
360 }