]> git.plutz.net Git - shellwiki/blob - macros/toc
Merge commit 'cfc3dbcd2e724953a001d0ad189df08072295d62'
[shellwiki] / macros / toc
1 #!/bin/awk -f
2 #!/opt/busybox/awk -f
3
4 # Table of Content generator
5 # For finding Headlines within a markdown document one needs to be context
6 # aware. I.e. Headlines within verbatim blocks must be ignored, etc.
7 #
8 # Basically this program is a slightly stripped down version onf the main
9 # markdown parser.
10 # Most of the inline parser is also included to allow stylig of headlines.
11
12 # TODO: Accept Arguments for controlling toc depth
13 # TODO Maybe: Somehow enable section TOCs
14
15 function debug(text) { printf "\n---\n%s\n---\n", text > "/dev/stderr"; }
16
17 function HTML ( text ) {
18   gsub( /&/,  "\\&",  text );
19   gsub( /</,  "\\&lt;",   text );
20   gsub( />/,  "\\&gt;",   text );
21   gsub( /"/,  "\\&quot;", text );
22   gsub( /'/,  "\\&#x27;", text );
23   gsub( /\\/, "\\&#x5C;", text );
24   return text;
25 }
26
27 function inline( line, LOCAL, len, code, href, guard ) {
28   nu = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\_]|_[[:alnum:]])*"    # not underline (except when escaped)
29   na = "(\\\\\\\\|\\\\[^\\\\]|[^\\\\\\*])*"  # not asterisk (except when escaped)
30   ieu =  "_([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])_"                 # inner <em> (underline)
31   isu = "__([^_[:space:]]|[^_[:space:]]" nu "[^_[:space:]])__"                # inner <strong> (underline)
32   iea =    "\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*"     # inner <em> (asterisk)
33   isa = "\\*\\*([^\\*[:space:]]|[^\\*[:space:]]" na "[^\\*[:space:]])\\*\\*"  # inner <strong> (asterisk)
34
35   if ( line ~ /^$/ ) {  # Recursion End
36     return "";
37
38   #  omit processing of escaped characters
39   } else if ( line ~ /^\\[]\\`\*_\{\}\(\)#\+-\.![]/) {
40     return substr(line, 2, 1) inline( substr(line, 3) );
41
42   # hard brakes <TOC MODIFIED>
43   } else if ( match(line, /^  \n/) ) {
44     return inline( substr(line, RLENGTH + 1) );
45
46   #  ``code spans``
47   } else if ( match( line, /^`+/) ) {
48     len = RLENGTH
49     guard = substr( line, 1, len )
50     if ( match(line, guard ".*" guard) ) {
51       code = substr( line, len + 1, match( substr(line, len + 1), guard ) - 1)
52       len = 2 * length(guard) + length(code)
53       #  strip single surrounding white spaces
54       code = gensub( / (.*) /, "\\1", "1" , code)
55       #  escape HTML within code span
56       gsub( /&/, "\\&amp;", code ); gsub( /</, "\\&lt;", code ); gsub( />/, "\\&gt;", code );
57       return "<code>" code "</code>" inline( substr( line, len + 1 ) )
58     }
59
60   #  quick links ("automatic links" in md doc) <TOC MODIFIED>
61   } else if ( match( line, /^<[a-zA-Z]+:\/\/([-\.[:alnum:]]+)(:[0-9]*)?(\/[^>]*)?>/ ) ) {
62     len = RLENGTH;
63     href = HTML( substr( line, 2, len - 2) );
64     return "<span class=\"a\">" href "</span>" inline( substr( line, len + 1) );
65
66   # inline links <TOC MODIFIED>
67   } else if ( match(line, /^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/) ) {
68     len = RLENGTH;
69     text  = gensub(/^\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\1", "g", line);
70     return "<span class=\"a\">" inline( text ) "</span>" inline( substr( line, len + 1) );
71
72   # reference style links <TOC MODIFIED>
73   } else if ( match(line, /^\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
74     len = RLENGTH;
75     text = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, line);
76     #   id = gensub(/^\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, line);
77     return "<span class=\"a\">" inline(text) "</span>" inline( substr( line, len + 1) );
78
79   # inline images <TOC MODIFIED>
80   } else if ( match(line, /^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/) ) {
81     len = RLENGTH;
82     text  = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\1", "g", line);
83     # href  = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\2", "g", line);
84     title = gensub(/^!\[([^]]+)\]\(([^"\)]+)([ \t]+"([^"]+)")?\)/, "\\4", "g", line);
85     if ( title ) {
86       return "<span class=\"img\">" HTML(title) "</span>" inline( substr( line, len + 1) );
87     } else {
88       return "<span class=\"img\">" HTML(text) "</span>" inline( substr( line, len + 1) );
89     }
90
91   # reference style images <TOC MODIFIED>
92   } else if ( match(line, /^!\[([^]]+)\] ?\[([^]]*)\]/ ) ) {
93     len = RLENGTH;
94     text = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\1", 1, line);
95     #  id = gensub(/^!\[([^\n]+)\] ?\[([^\n]*)\].*/, "\\2", 1, line);
96     return "<span class=\"img\">" HTML(text) "</span>" inline( substr( line, len + 1) );
97
98   #  ~~strikeout~~ (pandoc)
99   } else if ( match(line, /^~~([[:graph:]]|[[:graph:]]([^~]|~[^~])*[[:graph:]])~~/) ) {
100     len = RLENGTH;
101     return "<del>" inline( substr( line, 3, len - 4 ) ) "</del>" inline( substr( line, len + 1 ) );
102
103   #  ^superscript^ (pandoc)
104   } else if ( match(line, /^\^([^[:space:]^]|\\[ ^])+\^/) ) {
105     len = RLENGTH;
106     return "<sup>" inline( substr( line, 2, len - 2 ) ) "</sup>" inline( substr( line, len + 1 ) );
107
108   #  ~subscript~ (pandoc)
109   } else if ( match(line, /^~([^[:space:]~]|\\[ ~])+~/) ) {
110     len = RLENGTH;
111     return "<sub>" inline( substr( line, 2, len - 2 ) ) "</sub>" inline( substr( line, len + 1 ) );
112
113   # ignore embedded underscores (pandoc, php md)
114   } else if ( match(line, "^[[:alnum:]](__|_)") ) {
115     return substr( line, 1, RLENGTH) inline( substr(line, RLENGTH + 1) );
116
117   #  __strong__$
118   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__$") ) {
119     len = RLENGTH;
120     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
121
122   #  __strong__
123   } else if ( match(line, "^__(([^_[:space:]]|" ieu ")|([^_[:space:]]|" ieu ")(" nu "|" ieu ")*([^_[:space:]]|" ieu "))__[[:space:][:punct:]]") ) {
124     len = RLENGTH;
125     return "<strong>" inline( substr( line, 3, len - 5 ) ) "</strong>" inline( substr( line, len) );
126
127   #  **strong**
128   } else if ( match(line, "^\\*\\*(([^\\*[:space:]]|" iea ")|([^\\*[:space:]]|" iea ")(" na "|" iea ")*([^\\*[:space:]]|" iea "))\\*\\*") ) {
129     len = RLENGTH;
130     return "<strong>" inline( substr( line, 3, len - 4 ) ) "</strong>" inline( substr( line, len + 1 ) );
131
132   #  _em_$
133   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_$") ) {
134     len = RLENGTH;
135     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
136
137   #  _em_
138   } else if ( match(line, "^_(([^_[:space:]]|" isu ")|([^_[:space:]]|" isu ")(" nu "|" isu ")*([^_[:space:]]|" isu "))_[[:space:][:punct:]]") ) {
139     len = RLENGTH;
140     return "<em>" inline( substr( line, 2, len - 3 ) ) "</em>" inline( substr( line, len ) );
141
142   #  *em*
143   } else if ( match(line, "^\\*(([^\\*[:space:]]|" isa ")|([^\\*[:space:]]|" isa ")(" na "|" isa ")*([^\\*[:space:]]|" isa "))\\*") ) {
144     len = RLENGTH;
145     return "<em>" inline( substr( line, 2, len - 2 ) ) "</em>" inline( substr( line, len + 1 ) );
146
147   # # Macros  <TOC MODIFIED: never allow recursion>
148   # } else if ( AllowMacros && match( line, /^<<([^>]|>[^>])+>>/) ) {
149   #   len = RLENGTH;
150   #   return macro( substr( line, 3, len - 4 ) ) inline(substr(line, len + 1));
151
152   # Verbatim inline HTML
153   } else if ( AllowHTML && match( line, /^(<!--([^-]|-[^-]|--[^>])*-->|<\?([^\?]|\?[^>])*\?>|<![A-Z][^>]*>|<!\[CDATA\[([^\]]|\][^\]]|\]\][^>])*\]\]>|<\/[A-Za-z][A-Za-z0-9-]*[[:space:]]*>|<[A-Za-z][A-Za-z0-9-]*([[:space:]]+[A-Za-z_:][A-Za-z0-9_\.:-]*([[:space:]]*=[[:space:]]*([[:space:]"'=<>`]+|"[^"]*"|'[^']*'))?)*[[:space:]]*\/?>)/) ) {
154     len = RLENGTH;
155     return substr( line, 1, len) inline(substr(line, len + 1));
156
157   # Literal HTML entities
158   } else if ( match( line, /^&([a-zA-Z]{2,32}|#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});/) ) {
159     len = RLENGTH;
160     return substr( line, 1, len ) inline(substr(line, len + 1));
161
162   # Escape lone HTML character
163   } else if ( match( line, /^[&<>"']/) ) {
164     return HTML(substr(line, 1, 1)) inline(substr(line, 2));
165
166   #  continue walk over string
167   } else {
168     return substr(line, 1, 1) inline( substr(line, 2) );
169   }
170 }
171
172 function _block( block, LOCAL, st, len, hlvl, htxt, guard, code, indent ) {
173   gsub( /^\n+|\n+$/, "", block );
174
175   if ( block == "" ) {
176     return "";
177
178   # HTML #2 #3 #4 $5
179   } else if ( AllowHTML && match( block, /(^|\n) ? ? ?(<!--([^-]|-[^-]|--[^>])*(-->|$)|<\?([^\?]|\?[^>])*(\?>|$)|<![A-Z][^>]*(>|$)|<!\[CDATA\[([^\]]|\][^\]]|\]\][^>])*(\]\]>|$))/) ) {
180     len = RLENGTH; st = RSTART;
181     return _block(substr(block, 1, st - 1)) _block(substr(block, st + len));
182
183   # HTML #6
184   } else if ( AllowHTML && match( tolower(block), /(^|\n) ? ? ?<\/?(address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[123456]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)([[:space:]\n>]|\/>)([^\n]|\n[ \t]*[^\n])*(\n[[:space:]]*\n|$)/) ) {
185     len = RLENGTH; st = RSTART;
186     return _block(substr(block, 1, st - 1)) _block(substr(block, st + len));
187
188   # HTML #1
189   } else if ( AllowHTML && match( tolower(block), /(^|\n) ? ? ?<(script|pre|style)([[:space:]\n>]).*(<\/script>|<\/pre>|<\/style>|$)/) ) {
190     len = RLENGTH; st = RSTART;
191     match( tolower(substr(block, st, len)), /(<\/script>|<\/pre>|<\/style>)/);
192     len = RSTART + RLENGTH;
193     return _block(substr(block, 1, st - 1)) _block(substr(block, st + len));
194
195   # HTML #7
196   } else if ( AllowHTML && match( block, /^ ? ? ?(<\/[A-Za-z][A-Za-z0-9-]*[[:space:]]*>|<[A-Za-z][A-Za-z0-9-]*([[:space:]]+[A-Za-z_:][A-Za-z0-9_\.:-]*([[:space:]]*=[[:space:]]*([[:space:]"'=<>`]+|"[^"]*"|'[^']*'))?)*[[:space:]]*\/?>)([[:space:]]*\n)([^\n]|\n[ \t]*[^\n])*(\n[[:space:]]*\n|$)/) ) {
197     len = RLENGTH; st = RSTART;
198     return _block(substr(block, st + len));
199  
200   # Blockquote (leading >)
201   } else if ( match( block, /^> /) ) {
202     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match(block, /$/);
203     len = RLENGTH; st = RSTART;
204     return _block( substr(block, st + len) );
205
206   # Line Blocks (pandoc)
207   } else if ( match(block, /^\| [^\n]*(\n|$)(\| [^\n]*(\n|$)|[ \t]+[^\n[:space:]][^\n]*(\n|$))*/) ) {
208     len = RLENGTH; st = RSTART;
209     return _block( substr( block, len + 1) );
210
211   # Indented Code Block
212   } else if ( match(block, /^(    |\t)[^\n]+(\n|$)((    |\t)[^\n]+(\n|$)|[ \t]*(\n|$))*/) ) {
213     len = RLENGTH; st = RSTART;
214     return _block( substr( block, len + 1 ) );
215
216   # Fenced Code Block (pandoc)
217   } else if ( match( block, /^(~~~+|```+)/ ) ) {
218     guard = substr( block, 1, RLENGTH );
219     code = gensub(/^[^\n]+\n/, "", 1, block);
220     if ( match(code, "(^|\n)" guard "+(\n|$)" ) ) {
221       len = RLENGTH; st = RSTART;
222       return _block( substr( code, st + len ) );
223     } else {
224       match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
225       len = RLENGTH; st = RSTART;
226       return _block( substr(block, st + len) );
227     }
228
229   # Unordered list
230   } else if ( match( block, "^ ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
231                             "(([ \t]*\n)* ? ? ?[-+*][ \t]+[^\n]+(\n|$)" \
232                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
233                             "|[^\n]+(\n|$))*" ) ) {
234   block = substr( block, RLENGTH + 1);
235   return _block( block );
236
237   # Ordered list
238   } else if ( match( block, "^ ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
239                             "(([ \t]*\n)* ? ? ?([0-9]+|#)\\.[ \t]+[^\n]+(\n|$)" \
240                             "|([ \t]*\n)*( ? ? ?\t|  +)[^\n]+(\n|$)" \
241                             "|[^\n]+(\n|$))*" ) ) {
242   block = substr( block, RLENGTH + 1);
243   return _block( block );
244
245   # First Order Heading
246   } else if ( match( block, /^[^\n]+\n===+(\n|$)/ ) ) {
247     len = RLENGTH;
248     HL[1]++; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
249     return "<a class=\"toc h1\" href=\"#" HL[1] " - " HTML(gensub( /\n.*$/, "", "g", block )) "\">" inline( gensub( /\n.*$/, "", "g", block ) ) "</a>\n" \
250            _block( substr( block, len + 1 ) );
251
252   # Second Order Heading
253   } else if ( match( block, /^[^\n]+\n---+(\n|$)/ ) ) {
254     len = RLENGTH;
255     HL[2]++; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
256     return "<a class=\"toc h2\" href=\"#" HL[1] "." HL[2] " - " HTML(gensub( /\n.*$/, "", "g", block )) "\">" inline( gensub( /\n.*$/, "", "g", block ) ) "</a>\n" \
257            _block( substr( block, len + 1) );
258
259   # Nth Order Heading
260   } else if ( match( block, /^#{1,6}[ \t]*[^\n]+([ \t]*#*)(\n|$)/ ) ) {
261     len = RLENGTH;
262     hlvl = length( gensub( /^(#{1,6}).*$/, "\\1", "g", block ) );
263     htxt = gensub(/^#{1,6}[ \t]*(([^ \t\n]+|[ \t]+[^ \t\n#]|[ \t]+#+[^\n#])+)([ \t]*#*)(\n.*)?$/, "\\1", 1, block);
264     HL[hlvl]++; for ( n = hlvl + 1; n < 7; n++) { HL[n] = 0;}
265     hid = HL[1]; for ( n = 2; n <= hlvl; n++) { hid = hid "." HL[n] ; }
266     return "<a class=\"toc h" hlvl  "\" href=\"#" hid " - " HTML(htxt) "\">" inline( htxt ) "</a>\n" \
267            _block( substr( block, len + 1) );
268
269   # Horizontal rule
270   } else if ( match( block, /(^|\n) ? ? ?((\* *){3,}|(- *){3,}|(_ *){3,})($|\n)/) ) {
271     len = RLENGTH; st = RSTART;
272     return _block(substr(block, 1, st - 1)) _block(substr(block, st + len));
273
274   # Plain paragraph
275   } else {
276     match( block, /(^|\n)[[:space:]]*(\n|$)/ ) || match( block, /$/ );
277     len = RLENGTH; st = RSTART;
278     return _block( substr(block, st + len) );
279   }
280 }
281
282 BEGIN {
283   # Global Vars
284   file = ""; rl_href[""] = ""; rl_title[""] = "";
285   if (ENVIRON["MD_HTML"] == "true") { AllowHTML = "true"; }
286   HL[1] = 0; HL[2] = 0; HL[3] = 0; HL[4] = 0; HL[5] = 0; HL[6] = 0;
287
288   # Buffering of full file ist necessary, e.g. to find reference links
289   while (getline) { file = file $0 "\n"; }
290   # Clean up MS-DOS line breaks
291   gsub(/\r\n/, "\n", file);
292
293   # Clear reflinks from File
294   re_reflink = "(^|\n) ? ? ?\\[([^]\n]+)\\]: ([^ \t\n]+)(\n?[ \t]+(\"([^\"]+)\"|'([^']+)'|\\(([^)]+)\\)))?(\n|$)";
295   while( gsub(re_reflink, "\n", file ) );
296
297   # Run Block Processing -> The Actual Markdown!
298   printf "%s", "<div class=\"macro toc\">\n" _block( file ) "</div>";
299 }