]> git.plutz.net Git - shellwiki/blob - md_macros.awk
Merge commit 'cfc3dbcd2e724953a001d0ad189df08072295d62'
[shellwiki] / md_macros.awk
1 #!/bin/awk -f
2 #!/opt/busybox/awk -f
3
4 function sh_escape(arg){
5   return "'" gensub(/'/, "'\"'\"'", "g", arg) "'";
6 }
7
8 function argsplit(line, args, LOCAL, c, n, ctx) {
9   ctx="space"; n=0;
10
11   while ( length(line) > 0 ) {
12     c = substr(line, 1, 1);
13     line = substr(line, 2);
14     if (ctx == "space" )
15            if (c ~ /[ \t]/) ctx = "space";
16       else if (c ~ /\\/) { n++; ctx = "escbare"; }
17       else if (c ~ /"/)  { n++; ctx = "dquot"; }
18       else if (c ~ /'/)  { n++; ctx = "squot"; }
19       else   { n++; args[n] = c; ctx = "bare"; }
20     else if (ctx == "bare")
21            if (c ~ /[ \t]/) ctx = "space";
22       else if (c ~ /\\/)  ctx = "escbare";
23       else if (c ~ /"/)   ctx = "dquot";
24       else if (c ~ /'/)   ctx = "squot";
25       else args[n] = args[n] c;
26     else if (ctx == "dquot")
27            if (c ~ /"/)  ctx = "bare";
28       else if (c ~ /\\/) ctx = "escdquot";
29       else args[n] = args[n] c;
30     else if (ctx == "squot")
31       if (c ~ /'/)  ctx = "bare";
32       else args[n] = args[n] c;
33     else if (ctx == "escbare") {
34       args[n] = args[n] c;
35       ctx = "bare";
36     }
37     else if (ctx == "escdquot") {
38       args[n] = args[n] c;
39       ctx = "dquot";
40     }
41   }
42
43
44 function macro(call, LOCAL, line, files, n, args) {
45   "cd " sh_escape(ENVIRON["MD_MACROS"]) "; printf '%s/' *" |getline line;
46   split(line, files, "/");
47   for (n in files) { files[files[n]] = ""; delete files[n]; }
48   delete files[""];
49
50   argsplit(call, args);
51   call="";
52
53   for (n = 1; n in args; n++) call = call sh_escape(args[n]) " ";
54
55   if (args[1] in files) {
56     RS=""; ORS=""; line="";
57     "printf '%s' " sh_escape(file) " | " sh_escape(ENVIRON["MD_MACROS"]) "/" call | getline line;
58     return line;
59   } else {
60     return HTML("<<" call ">>");
61   }
62 }
63
64 BEGIN {
65   if (ENVIRON["MD_MACROS"]) { AllowMacros = "true"; }
66 }