added LICENSE files
[bills-tools.git] / calc / calc
blobfbfa5fa457e2a14d982bf253c8b6dece7ecb6d34
1 #!/usr/bin/env rc
3 # calc, (c) Oct, 2010, by Bill Burdick
4 # licensed with the ZLIB license (see the LICENSE file)
6 # assign var value -- find var in window and replace its old value with the new one
7 # variables are words made of letters, numbers, and/or _,  followed by '=' and, optionally,  a number
8 fn assign {
9         if (echo -n '/(^|[^a-zA-Z0-9_])'$1' *= */+#0;/[0-9.e+\-]*/'|9p write acme/$winid/addr >[2] /dev/null) {
10                 echo -n 'dot=addr'|9p write acme/$winid/ctl
11                 echo -n $2 | 9p write acme/$winid/data
12         }
13         if not echo 'Could not find variable: "'$1'"'
16 # copy calc commands from window into /tmp/cmd
17 9p read acme/$winid/body|sed -e '/^#!/,$p;d'>/tmp/cmd
18 chmod a+x /tmp/cmd
19 rm -f /tmp/cmd.errs
20 9p read acme/$winid/body |
21                 # extract variables and values from window
22         sed -n -e '/^#!/q;s/([a-zA-Z0-9_]+) *= *([0-9.e+\-]*)/\n\1=\2\n/g;h;:v;s/\n(.|\n)*//;s/^[a-zA-Z0-9_]+=$/&0/;/^[a-zA-Z0-9_]+=[0-9.e+\-]*/p;g;/\n/!d;s/[^\n]*\n//;h;bv' |
23                 # pipe vars (VAR=VALUE) to command
24         /tmp/cmd |
25                 # parse vars from commmand and convert to "assign" calls (above function)
26         awk '{loc=index($0, "=");print "assign (" substr($0, 1, loc - 1) ") (" substr($0, loc + 1) ")"}' |
27                 # pipe assign commands to rc to plug the values back into the window
28         rc
29 if (test -s /tmp/cmd.errs) 9p write acme/$winid/errors < /tmp/cmd.errs
30 exit 0