summaryrefslogtreecommitdiff
path: root/lisp/calc/calc-prog.el
blob: 411f55a24e6381b317bbb922538788916af17eff (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
;;; calc-prog.el --- user programmability functions for Calc

;; Copyright (C) 1990-1993, 2001-2012 Free Software Foundation, Inc.

;; Author: David Gillespie <daveg@synaptics.com>
;; Maintainer: Jay Belanger <jay.p.belanger@gmail.com>

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;;; Code:

;; This file is autoloaded from calc-ext.el.

(require 'calc-ext)
(require 'calc-macs)

;; Declare functions which are defined elsewhere.
(declare-function edmacro-format-keys "edmacro" (macro &optional verbose))
(declare-function edmacro-parse-keys "edmacro" (string &optional need-vector))
(declare-function math-read-expr-level "calc-aent" (exp-prec &optional exp-term))


(defun calc-equal-to (arg)
  (interactive "P")
  (calc-wrapper
   (if (and (integerp arg) (> arg 2))
       (calc-enter-result arg "eq" (cons 'calcFunc-eq (calc-top-list-n arg)))
     (calc-binary-op "eq" 'calcFunc-eq arg))))

(defun calc-remove-equal (arg)
  (interactive "P")
  (calc-wrapper
   (calc-unary-op "rmeq" 'calcFunc-rmeq arg)))

(defun calc-not-equal-to (arg)
  (interactive "P")
  (calc-wrapper
   (if (and (integerp arg) (> arg 2))
       (calc-enter-result arg "neq" (cons 'calcFunc-neq (calc-top-list-n arg)))
     (calc-binary-op "neq" 'calcFunc-neq arg))))

(defun calc-less-than (arg)
  (interactive "P")
  (calc-wrapper
   (calc-binary-op "lt" 'calcFunc-lt arg)))

(defun calc-greater-than (arg)
  (interactive "P")
  (calc-wrapper
   (calc-binary-op "gt" 'calcFunc-gt arg)))

(defun calc-less-equal (arg)
  (interactive "P")
  (calc-wrapper
   (calc-binary-op "leq" 'calcFunc-leq arg)))

(defun calc-greater-equal (arg)
  (interactive "P")
  (calc-wrapper
   (calc-binary-op "geq" 'calcFunc-geq arg)))

(defun calc-in-set (arg)
  (interactive "P")
  (calc-wrapper
   (calc-binary-op "in" 'calcFunc-in arg)))

(defun calc-logical-and (arg)
  (interactive "P")
  (calc-wrapper
   (calc-binary-op "land" 'calcFunc-land arg 1)))

(defun calc-logical-or (arg)
  (interactive "P")
  (calc-wrapper
   (calc-binary-op "lor" 'calcFunc-lor arg 0)))

(defun calc-logical-not (arg)
  (interactive "P")
  (calc-wrapper
   (calc-unary-op "lnot" 'calcFunc-lnot arg)))

(defun calc-logical-if ()
  (interactive)
  (calc-wrapper
   (calc-enter-result 3 "if" (cons 'calcFunc-if (calc-top-list-n 3)))))





(defun calc-timing (n)
  (interactive "P")
  (calc-wrapper
   (calc-change-mode 'calc-timing n nil t)
   (message (if calc-timing
		"Reporting timing of slow commands in Trail"
	      "Not reporting timing of commands"))))

(defun calc-pass-errors ()
  (interactive)
  ;; The following two cases are for the new, optimizing byte compiler
  ;; or the standard 18.57 byte compiler, respectively.
  (condition-case err
      (let ((place (aref (nth 2 (nth 2 (symbol-function 'calc-do))) 15)))
	(or (memq (car-safe (car-safe place)) '(error xxxerror))
	    (setq place (aref (nth 2 (nth 2 (symbol-function 'calc-do))) 27)))
	(or (memq (car (car place)) '(error xxxerror))
	    (error "foo"))
	(setcar (car place) 'xxxerror))
    (error (error "The calc-do function has been modified; unable to patch"))))

(defun calc-user-define ()
  (interactive)
  (message "Define user key: z-")
  (let ((key (read-char)))
    (if (= (calc-user-function-classify key) 0)
	(error "Can't redefine \"?\" key"))
    (let ((func (intern (completing-read (concat "Set key z "
						 (char-to-string key)
						 " to command: ")
					 obarray
					 'commandp
					 t
					 "calc-"))))
      (let* ((kmap (calc-user-key-map))
	     (old (assq key kmap)))
	(if old
	    (setcdr old func)
	  (setcdr kmap (cons (cons key func) (cdr kmap))))))))

(defun calc-user-undefine ()
  (interactive)
  (message "Undefine user key: z-")
  (let ((key (read-char)))
    (if (= (calc-user-function-classify key) 0)
	(error "Can't undefine \"?\" key"))
    (let* ((kmap (calc-user-key-map)))
      (delq (or (assq key kmap)
		(assq (upcase key) kmap)
		(assq (downcase key) kmap)
		(error "No such user key is defined"))
	    kmap))))


;; math-integral-cache-state is originally declared in calcalg2.el,
;; it is used in calc-user-define-variable.
(defvar math-integral-cache-state)

;; calc-user-formula-alist is local to calc-user-define-formula,
;; calc-user-define-composition and calc-finish-formula-edit,
;; but is used by calc-fix-user-formula.
(defvar calc-user-formula-alist)

(defun calc-user-define-formula ()
  (interactive)
  (calc-wrapper
   (let* ((form (calc-top 1))
	  (math-arglist nil)
	  (is-lambda (and (eq (car-safe form) 'calcFunc-lambda)
			  (>= (length form) 2)))
	  odef key keyname cmd cmd-base cmd-base-default
          func calc-user-formula-alist is-symb)
     (if is-lambda
	 (setq math-arglist (mapcar (function (lambda (x) (nth 1 x)))
			       (nreverse (cdr (reverse (cdr form)))))
	       form (nth (1- (length form)) form))
       (calc-default-formula-arglist form)
       (setq math-arglist (sort math-arglist 'string-lessp)))
     (message "Define user key: z-")
     (setq key (read-char))
     (if (= (calc-user-function-classify key) 0)
	 (error "Can't redefine \"?\" key"))
     (setq key (and (not (memq key '(13 32))) key)
	   keyname (and key
			(if (or (and (<= ?0 key) (<= key ?9))
				(and (<= ?a key) (<= key ?z))
				(and (<= ?A key) (<= key ?Z)))
			    (char-to-string key)
			  (format "%03d" key)))
	   odef (assq key (calc-user-key-map)))
     (unless keyname
       (setq keyname (format "%05d" (abs (% (random) 10000)))))
     (while
	 (progn
	   (setq cmd-base-default (concat "User-" keyname))
           (setq cmd (completing-read
                      (concat "Define M-x command name (default calc-"
                              cmd-base-default
                              "): ")
                      obarray 'commandp nil
                      (if (and odef (symbolp (cdr odef)))
                          (symbol-name (cdr odef))
                        "calc-")))
           (if (or (string-equal cmd "")
                   (string-equal cmd "calc-"))
               (setq cmd (concat "calc-User-" keyname)))
           (setq cmd-base (and (string-match "\\`calc-\\(.+\\)\\'" cmd)
			       (math-match-substring cmd 1)))
           (setq cmd (intern cmd))
	   (and cmd
		(fboundp cmd)
		odef
		(not
		 (y-or-n-p
		  (if (get cmd 'calc-user-defn)
		      (concat "Replace previous definition for "
			      (symbol-name cmd) "? ")
		    "That name conflicts with a built-in Emacs function.  Replace this function? "))))))
     (while
	 (progn
           (setq cmd-base-default
                 (if cmd-base
                     (if (string-match
                          "\\`User-.+" cmd-base)
                         (concat
                          "User"
                          (substring cmd-base 5))
                       cmd-base)
                   (concat "User" keyname)))
	   (setq func
                 (concat "calcFunc-"
                         (completing-read
                          (concat "Define algebraic function name (default "
                                  cmd-base-default "): ")
                          (mapcar (lambda (x) (substring x 9))
                                  (all-completions "calcFunc-"
                                                   obarray))
                          (lambda (x)
                            (fboundp
                             (intern (concat "calcFunc-" x))))
                          nil)))
           (setq func
                 (if (string-equal func "calcFunc-")
                     (intern (concat "calcFunc-" cmd-base-default))
                   (intern func)))
	   (and func
		(fboundp func)
		(not (fboundp cmd))
		odef
		(not
		 (y-or-n-p
		  (if (get func 'calc-user-defn)
		      (concat "Replace previous definition for "
			      (symbol-name func) "? ")
		    "That name conflicts with a built-in Emacs function.  Replace this function? "))))))

     (if (not func)
	 (setq func (intern (concat "calcFunc-User"
				    (or keyname
					(and cmd (symbol-name cmd))
					(format "%05d" (% (random) 10000)))))))

     (if is-lambda
	 (setq calc-user-formula-alist math-arglist)
       (while
	   (progn
	     (setq calc-user-formula-alist
                   (read-from-minibuffer "Function argument list: "
                                         (if math-arglist
                                             (prin1-to-string math-arglist)
                                           "()")
                                         minibuffer-local-map
                                         t))
	     (and (not (calc-subsetp calc-user-formula-alist math-arglist))
		  (not (y-or-n-p
			"Okay for arguments that don't appear in formula to be ignored? "))))))
     (setq is-symb (and calc-user-formula-alist
			func
			(y-or-n-p
			 "Leave it symbolic for non-constant arguments? ")))
     (setq calc-user-formula-alist
           (mapcar (function (lambda (x)
                               (or (cdr (assq x '((nil . arg-nil)
                                                  (t . arg-t))))
                                   x))) calc-user-formula-alist))
     (if cmd
	 (progn
	   (require 'calc-macs)
	   (fset cmd
		 (list 'lambda
		       '()
		       '(interactive)
		       (list 'calc-wrapper
			     (list 'calc-enter-result
				   (length calc-user-formula-alist)
				   (let ((name (symbol-name (or func cmd))))
				     (and (string-match
					   "\\([^-][^-]?[^-]?[^-]?\\)[^-]*\\'"
					   name)
					  (math-match-substring name 1)))
				   (list 'cons
					 (list 'quote func)
					 (list 'calc-top-list-n
					       (length calc-user-formula-alist)))))))
	   (put cmd 'calc-user-defn t)))
     (let ((body (list 'math-normalize (calc-fix-user-formula form))))
       (fset func
	     (append
	      (list 'lambda calc-user-formula-alist)
	      (and is-symb
		   (mapcar (function (lambda (v)
				       (list 'math-check-const v t)))
			   calc-user-formula-alist))
	      (list body))))
     (put func 'calc-user-defn form)
     (setq math-integral-cache-state nil)
     (if key
	 (let* ((kmap (calc-user-key-map))
		(old (assq key kmap)))
	   (if old
	       (setcdr old cmd)
	     (setcdr kmap (cons (cons key cmd) (cdr kmap)))))))
   (message "")))

(defvar math-arglist)		    ; dynamically bound in all callers
(defun calc-default-formula-arglist (form)
  (if (consp form)
      (if (eq (car form) 'var)
	  (if (or (memq (nth 1 form) math-arglist)
		  (math-const-var form))
	      ()
	    (setq math-arglist (cons (nth 1 form) math-arglist)))
	(calc-default-formula-arglist-step (cdr form)))))

(defun calc-default-formula-arglist-step (l)
  (and l
       (progn
	 (calc-default-formula-arglist (car l))
	 (calc-default-formula-arglist-step (cdr l)))))

(defun calc-subsetp (a b)
  (or (null a)
      (and (memq (car a) b)
	   (calc-subsetp (cdr a) b))))

(defun calc-fix-user-formula (f)
  (if (consp f)
      (let (temp)
	(cond ((and (eq (car f) 'var)
		    (memq (setq temp (or (cdr (assq (nth 1 f) '((nil . arg-nil)
								(t . arg-t))))
					 (nth 1 f)))
			  calc-user-formula-alist))
	       temp)
	      ((or (math-constp f) (eq (car f) 'var))
	       (list 'quote f))
	      ((and (eq (car f) 'calcFunc-eval)
		    (= (length f) 2))
	       (list 'let '((calc-simplify-mode nil))
		     (list 'math-normalize (calc-fix-user-formula (nth 1 f)))))
	      ((and (eq (car f) 'calcFunc-evalsimp)
		    (= (length f) 2))
	       (list 'math-simplify (calc-fix-user-formula (nth 1 f))))
	      ((and (eq (car f) 'calcFunc-evalextsimp)
		    (= (length f) 2))
	       (list 'math-simplify-extended
		     (calc-fix-user-formula (nth 1 f))))
	      (t
	       (cons 'list
		     (cons (list 'quote (car f))
			   (mapcar 'calc-fix-user-formula (cdr f)))))))
    f))

(defun calc-user-define-composition ()
  (interactive)
  (calc-wrapper
   (if (eq calc-language 'unform)
       (error "Can't define formats for unformatted mode"))
   (let* ((comp (calc-top 1))
	  (func (intern
                 (concat "calcFunc-"
                         (completing-read "Define format for which function: "
                                          (mapcar (lambda (x) (substring x 9))
                                                  (all-completions "calcFunc-"
                                                                   obarray))
                                          (lambda (x)
                                            (fboundp
                                             (intern (concat "calcFunc-" x))))))))
	  (comps (get func 'math-compose-forms))
	  entry entry2
	  (math-arglist nil)
	  (calc-user-formula-alist nil))
     (if (math-zerop comp)
	 (if (setq entry (assq calc-language comps))
	     (put func 'math-compose-forms (delq entry comps)))
       (calc-default-formula-arglist comp)
       (setq math-arglist (sort math-arglist 'string-lessp))
       (while
	   (progn
	     (setq calc-user-formula-alist
                   (read-from-minibuffer "Composition argument list: "
                                         (if math-arglist
                                             (prin1-to-string math-arglist)
                                           "()")
                                         minibuffer-local-map
                                         t))
	     (and (not (calc-subsetp calc-user-formula-alist math-arglist))
		  (y-or-n-p
		   "Okay for arguments that don't appear in formula to be invisible? "))))
       (or (setq entry (assq calc-language comps))
	   (put func 'math-compose-forms
		(cons (setq entry (list calc-language)) comps)))
       (or (setq entry2 (assq (length calc-user-formula-alist) (cdr entry)))
	   (setcdr entry
		   (cons (setq entry2
                               (list (length calc-user-formula-alist))) (cdr entry))))
       (setcdr entry2
               (list 'lambda calc-user-formula-alist (calc-fix-user-formula comp))))
     (calc-pop-stack 1)
     (calc-do-refresh))))


(defun calc-user-define-kbd-macro (arg)
  (interactive "P")
  (or last-kbd-macro
      (error "No keyboard macro defined"))
  (message "Define last kbd macro on user key: z-")
  (let ((key (read-char)))
    (if (= (calc-user-function-classify key) 0)
	(error "Can't redefine \"?\" key"))
    (let ((cmd (intern (completing-read "Full name for new command: "
					obarray
					'commandp
					nil
					(concat "calc-User-"
						(if (or (and (>= key ?a)
							     (<= key ?z))
							(and (>= key ?A)
							     (<= key ?Z))
							(and (>= key ?0)
							     (<= key ?9)))
						    (char-to-string key)
						  (format "%03d" key)))))))
      (and (fboundp cmd)
	   (not (let ((f (symbol-function cmd)))
		  (or (stringp f)
		      (and (consp f)
			   (eq (car-safe (nth 3 f))
			       'calc-execute-kbd-macro)))))
	   (error "Function %s is already defined and not a keyboard macro"
		  cmd))
      (put cmd 'calc-user-defn t)
      (fset cmd (if (< (prefix-numeric-value arg) 0)
		    last-kbd-macro
		  (list 'lambda
			'(arg)
			'(interactive "P")
			(list 'calc-execute-kbd-macro
			      (vector (key-description last-kbd-macro)
				      last-kbd-macro)
			      'arg
			      (format "z%c" key)))))
      (let* ((kmap (calc-user-key-map))
	     (old (assq key kmap)))
	(if old
	    (setcdr old cmd)
	  (setcdr kmap (cons (cons key cmd) (cdr kmap))))))))


(defun calc-edit-user-syntax ()
  (interactive)
  (calc-wrapper
   (let ((lang calc-language))
     (calc-edit-mode (list 'calc-finish-user-syntax-edit (list 'quote lang))
		     t
		     (format "Editing %s-Mode Syntax Table. "
			     (cond ((null lang) "Normal")
				   ((eq lang 'tex) "TeX")
                                   ((eq lang 'latex) "LaTeX")
				   (t (capitalize (symbol-name lang))))))
     (calc-write-parse-table (cdr (assq lang calc-user-parse-tables))
			     lang)))
  (calc-show-edit-buffer))

(defvar calc-original-buffer)

(defun calc-finish-user-syntax-edit (lang)
  (let ((tab (calc-read-parse-table calc-original-buffer lang))
	(entry (assq lang calc-user-parse-tables)))
    (if tab
	(setcdr (or entry
		    (car (setq calc-user-parse-tables
			       (cons (list lang) calc-user-parse-tables))))
		tab)
      (if entry
	  (setq calc-user-parse-tables
		(delq entry calc-user-parse-tables)))))
  (switch-to-buffer calc-original-buffer))

;; The variable calc-lang is local to calc-write-parse-table, but is
;; used by calc-write-parse-table-part which is called by
;; calc-write-parse-table.  The variable is also local to
;; calc-read-parse-table, but is used by calc-fix-token-name which
;; is called (indirectly) by calc-read-parse-table.
(defvar calc-lang)

(defun calc-write-parse-table (tab calc-lang)
  (let ((p tab))
    (while p
      (calc-write-parse-table-part (car (car p)))
      (insert ":= "
	      (let ((math-format-hash-args t))
		(math-format-flat-expr (cdr (car p)) 0))
	      "\n")
      (setq p (cdr p)))))

(defun calc-write-parse-table-part (p)
  (while p
    (cond ((stringp (car p))
	   (let ((s (car p)))
	     (if (and (string-match "\\`\\\\dots\\>" s)
		      (not (memq calc-lang '(tex latex))))
		 (setq s (concat ".." (substring s 5))))
	     (if (or (and (string-match
			   "[a-zA-Z0-9\"{}]\\|\\`:=\\'\\|\\`#\\|\\`%%" s)
			  (string-match "[^a-zA-Z0-9\\]" s))
		     (and (assoc s '((")") ("]") (">")))
			  (not (cdr p))))
		 (insert (prin1-to-string s) " ")
	       (insert s " "))))
	  ((integerp (car p))
	   (insert "#")
	   (or (= (car p) 0)
	       (insert "/" (int-to-string (car p))))
	   (insert " "))
	  ((and (eq (car (car p)) '\?) (equal (car (nth 2 (car p))) "$$"))
	   (insert (car (nth 1 (car p))) " "))
	  (t
	   (insert "{ ")
	   (calc-write-parse-table-part (nth 1 (car p)))
	   (insert "}" (symbol-name (car (car p))))
	   (if (nth 2 (car p))
	       (calc-write-parse-table-part (list (car (nth 2 (car p)))))
	     (insert " "))))
    (setq p (cdr p))))

(defun calc-read-parse-table (calc-buf calc-lang)
  (let ((tab nil))
    (while (progn
	     (skip-chars-forward "\n\t ")
	     (not (eobp)))
      (if (looking-at "%%")
	  (end-of-line)
	(let ((pt (point))
	      (p (calc-read-parse-table-part ":=[\n\t ]+" ":=")))
	  (or (stringp (car p))
	      (and (integerp (car p))
		   (stringp (nth 1 p)))
	      (progn
		(goto-char pt)
		(error "Malformed syntax rule")))
	  (let ((pos (point)))
	    (end-of-line)
	    (let* ((str (buffer-substring pos (point)))
		   (exp (with-current-buffer calc-buf
			  (let ((calc-user-parse-tables nil)
				(calc-language nil)
				(math-expr-opers (math-standard-ops))
				(calc-hashes-used 0))
			    (math-read-expr
			     (if (string-match ",[ \t]*\\'" str)
				 (substring str 0 (match-beginning 0))
			       str))))))
	      (if (eq (car-safe exp) 'error)
		  (progn
		    (goto-char (+ pos (nth 1 exp)))
		    (error (nth 2 exp))))
	      (setq tab (nconc tab (list (cons p exp)))))))))
    tab))

(defun calc-fix-token-name (name &optional unquoted)
  (cond ((string-match "\\`\\.\\." name)
	 (concat "\\dots" (substring name 2)))
	((and (equal name "{") (memq calc-lang '(tex latex eqn)))
	 "(")
	((and (equal name "}") (memq calc-lang '(tex latex eqn)))
	 ")")
	((and (equal name "&") (memq calc-lang '(tex latex)))
	 ",")
	((equal name "#")
	 (search-backward "#")
	 (error "Token '#' is reserved"))
	((and unquoted (string-match "#" name))
	 (error "Tokens containing '#' must be quoted"))
	((not (string-match "[^ ]" name))
	 (search-backward "\"" nil t)
	 (error "Blank tokens are not allowed"))
	(t name)))

(defun calc-read-parse-table-part (term eterm)
  (let ((part nil)
	(quoted nil))
    (while (progn
	     (skip-chars-forward "\n\t ")
	     (if (eobp) (error "Expected '%s'" eterm))
	     (not (looking-at term)))
      (cond ((looking-at "%%")
	     (end-of-line))
	    ((looking-at "{[\n\t ]")
	     (forward-char 2)
	     (let ((p (calc-read-parse-table-part "}" "}")))
	       (or (looking-at "[+*?]")
		   (error "Expected '+', '*', or '?'"))
	       (let ((sym (intern (buffer-substring (point) (1+ (point))))))
		 (forward-char 1)
		 (looking-at "[^\n\t ]*")
		 (let ((sep (buffer-substring (point) (match-end 0))))
		   (goto-char (match-end 0))
		   (and (eq sym '\?) (> (length sep) 0)
			(not (equal sep "$")) (not (equal sep "."))
			(error "Separator not allowed with { ... }?"))
		   (if (string-match "\\`\"" sep)
		       (setq sep (read-from-string sep)))
                   (if (> (length sep) 0)
                       (setq sep (calc-fix-token-name sep)))
		   (setq part (nconc part
				     (list (list sym p
						 (and (> (length sep) 0)
						      (cons sep p))))))))))
	    ((looking-at "}")
	     (error "Too many }'s"))
	    ((looking-at "\"")
	     (setq quoted (calc-fix-token-name (read (current-buffer)))
		   part (nconc part (list quoted))))
	    ((looking-at "#\\(\\(/[0-9]+\\)?\\)[\n\t ]")
	     (setq part (nconc part (list (if (= (match-beginning 1)
						 (match-end 1))
					      0
					    (string-to-number
					     (buffer-substring
					      (1+ (match-beginning 1))
					      (match-end 1)))))))
	     (goto-char (match-end 0)))
	    ((looking-at ":=[\n\t ]")
	     (error "Misplaced ':='"))
	    (t
	     (looking-at "[^\n\t ]*")
	     (let ((end (match-end 0)))
	       (setq part (nconc part (list (calc-fix-token-name
					     (buffer-substring
					      (point) end) t))))
	       (goto-char end)))))
    (goto-char (match-end 0))
    (let ((len (length part)))
      (while (and (> len 1)
		  (let ((last (nthcdr (setq len (1- len)) part)))
		    (and (assoc (car last) '((")") ("]") (">")))
			 (not (eq (car last) quoted))
			 (setcar last
				 (list '\? (list (car last)) '("$$"))))))))
    part))

(defun calc-user-define-invocation ()
  (interactive)
  (or last-kbd-macro
      (error "No keyboard macro defined"))
  (setq calc-invocation-macro last-kbd-macro)
  (message "Use `C-x * Z' to invoke this macro"))

(defun calc-user-define-edit ()
  (interactive)  ; but no calc-wrapper!
  (message "Edit definition of command: z-")
  (let* (cmdname
         (key (read-char))
	 (def (or (assq key (calc-user-key-map))
		  (assq (upcase key) (calc-user-key-map))
		  (assq (downcase key) (calc-user-key-map))
		  (error "No command defined for that key")))
	 (cmd (cdr def)))
    (when (symbolp cmd)
      (setq cmdname (symbol-name cmd))
      (setq cmd (symbol-function cmd)))
    (cond ((or (stringp cmd)
	       (and (consp cmd)
		    (eq (car-safe (nth 3 cmd)) 'calc-execute-kbd-macro)))
           (let* ((mac (elt (nth 1 (nth 3 cmd)) 1))
                  (str (edmacro-format-keys mac t))
                  (kys (nth 3 (nth 3 cmd))))
             (calc-edit-mode
              (list 'calc-edit-macro-finish-edit cmdname kys)
              t (format (concat
                         "Editing keyboard macro (%s, bound to %s).\n"
                         "Original keys: %s \n")
                        cmdname kys (elt (nth 1 (nth 3 cmd)) 0)))
             (insert str "\n")
             (calc-edit-format-macro-buffer)
             (calc-show-edit-buffer)))
	  (t (let* ((func (calc-stack-command-p cmd))
		    (defn (and func
			       (symbolp func)
			       (get func 'calc-user-defn)))
                    (kys (concat "z" (char-to-string (car def))))
                    (intcmd (symbol-name (cdr def)))
                    (algcmd (if func (substring (symbol-name func) 9) "")))
	       (if (and defn (calc-valid-formula-func func))
		   (let ((niceexpr (math-format-nice-expr defn (frame-width))))
		     (calc-wrapper
		      (calc-edit-mode
                       (list 'calc-finish-formula-edit (list 'quote func))
                       nil
                       (format (concat
                                "Editing formula (%s, %s, bound to %s).\n"
                                "Original formula: %s\n")
                               intcmd algcmd kys niceexpr))
		      (insert  (math-showing-full-precision
                                niceexpr)
                               "\n"))
		     (calc-show-edit-buffer))
		 (error "That command's definition cannot be edited")))))))

;; Formatting the macro buffer

(defvar calc-edit-top)

(defun calc-edit-macro-repeats ()
  (goto-char calc-edit-top)
  (while
      (re-search-forward "^\\([0-9]+\\)\\*" nil t)
    (let ((num (string-to-number (match-string 1)))
          (line (buffer-substring (point) (line-end-position))))
      (goto-char (line-beginning-position))
      (kill-line 1)
      (while (> num 0)
        (insert line "\n")
        (setq num (1- num))))))

(defun calc-edit-macro-adjust-buffer ()
  (calc-edit-macro-repeats)
  (goto-char calc-edit-top)
  (while (re-search-forward "^RET$" nil t)
    (delete-char 1))
  (goto-char calc-edit-top)
  (while (and (re-search-forward "^$" nil t)
              (not (= (point) (point-max))))
    (delete-char 1)))

(defun calc-edit-macro-command ()
  "Return the command on the current line in a Calc macro editing buffer."
  (let ((beg (line-beginning-position))
        (end (save-excursion
               (if (search-forward ";;" (line-end-position) 1)
                   (forward-char -2))
               (skip-chars-backward " \t")
               (point))))
    (buffer-substring beg end)))

(defun calc-edit-macro-command-type ()
  "Return the type of command on the current line in a Calc macro editing buffer."
  (let ((beg (save-excursion
               (if (search-forward ";;" (line-end-position) t)
                   (progn
                     (skip-chars-forward " \t")
                     (point)))))
        (end (save-excursion
               (goto-char (line-end-position))
               (skip-chars-backward " \t")
               (point))))
    (if beg
        (buffer-substring beg end)
      "")))

(defun calc-edit-macro-combine-alg-ent ()
  "Put an entire algebraic entry on a single line."
  (let ((line (calc-edit-macro-command))
        (type (calc-edit-macro-command-type))
        curline
        match)
    (goto-char (line-beginning-position))
    (kill-line 1)
    (setq curline (calc-edit-macro-command))
    (while (and curline
                (not (string-equal "RET" curline))
                (not (setq match (string-match "<return>" curline))))
      (setq line (concat line curline))
      (kill-line 1)
      (setq curline (calc-edit-macro-command)))
    (when match
      (kill-line 1)
      (setq line (concat line (substring curline 0 match))))
    (setq line (replace-regexp-in-string "SPC" " SPC "
                  (replace-regexp-in-string " " "" line)))
    (insert line "\t\t\t")
    (if (> (current-column) 24)
        (delete-char -1))
    (insert ";; " type "\n")
    (if match
        (insert "RET\t\t\t;; calc-enter\n"))))

(defun calc-edit-macro-combine-ext-command ()
  "Put an entire extended command on a single line."
  (let ((cmdbeg (calc-edit-macro-command))
        (line "")
        (type (calc-edit-macro-command-type))
        curline
        match)
    (goto-char (line-beginning-position))
    (kill-line 1)
    (setq curline (calc-edit-macro-command))
    (while (and curline
                (not (string-equal "RET" curline))
                (not (setq match (string-match "<return>" curline))))
      (setq line (concat line curline))
      (kill-line 1)
      (setq curline (calc-edit-macro-command)))
    (when match
      (kill-line 1)
      (setq line (concat line (substring curline 0 match))))
    (setq line (replace-regexp-in-string " " "" line))
    (insert cmdbeg " " line "\t\t\t")
    (if (> (current-column) 24)
        (delete-char -1))
    (insert ";; " type "\n")
    (if match
        (insert "RET\t\t\t;; calc-enter\n"))))

(defun calc-edit-macro-combine-var-name ()
  "Put an entire variable name on a single line."
  (let ((line (calc-edit-macro-command))
        curline
        match)
    (goto-char (line-beginning-position))
    (kill-line 1)
    (if (member line '("0" "1" "2" "3" "4" "5" "6" "7" "8" "9"))
          (insert line "\t\t\t;; calc quick variable\n")
      (setq curline (calc-edit-macro-command))
      (while (and curline
                  (not (string-equal "RET" curline))
                  (not (setq match (string-match "<return>" curline))))
        (setq line (concat line curline))
        (kill-line 1)
        (setq curline (calc-edit-macro-command)))
      (when match
        (kill-line 1)
        (setq line (concat line (substring curline 0 match))))
      (setq line (replace-regexp-in-string " " "" line))
      (insert line "\t\t\t")
      (if (> (current-column) 24)
          (delete-char -1))
      (insert ";; calc variable\n")
      (if match
          (insert "RET\t\t\t;; calc-enter\n")))))

(defun calc-edit-macro-combine-digits ()
  "Put an entire sequence of digits on a single line."
  (let ((line (calc-edit-macro-command))
        curline)
    (goto-char (line-beginning-position))
    (kill-line 1)
    (while (string-equal (calc-edit-macro-command-type) "calcDigit-start")
      (setq line (concat line (calc-edit-macro-command)))
      (kill-line 1))
    (insert line "\t\t\t")
    (if (> (current-column) 24)
        (delete-char -1))
    (insert ";; calc digits\n")))

(defun calc-edit-format-macro-buffer ()
  "Rewrite the Calc macro editing buffer."
  (calc-edit-macro-adjust-buffer)
  (goto-char calc-edit-top)
  (let ((type (calc-edit-macro-command-type)))
    (while (not (string-equal type ""))
      (cond
       ((or
         (string-equal type "calc-algebraic-entry")
         (string-equal type "calc-auto-algebraic-entry"))
        (calc-edit-macro-combine-alg-ent))
       ((string-equal type "calc-execute-extended-command")
        (calc-edit-macro-combine-ext-command))
       ((string-equal type "calcDigit-start")
        (calc-edit-macro-combine-digits))
       ((or
         (string-equal type "calc-store")
         (string-equal type "calc-store-into")
         (string-equal type "calc-store-neg")
         (string-equal type "calc-store-plus")
         (string-equal type "calc-store-minus")
         (string-equal type "calc-store-div")
         (string-equal type "calc-store-times")
         (string-equal type "calc-store-power")
         (string-equal type "calc-store-concat")
         (string-equal type "calc-store-inv")
         (string-equal type "calc-store-dec")
         (string-equal type "calc-store-incr")
         (string-equal type "calc-store-exchange")
         (string-equal type "calc-unstore")
         (string-equal type "calc-recall")
         (string-equal type "calc-let")
         (string-equal type "calc-permanent-variable"))
        (forward-line 1)
        (calc-edit-macro-combine-var-name))
       ((or
         (string-equal type "calc-copy-variable")
         (string-equal type "calc-copy-special-constant")
         (string-equal type "calc-declare-variable"))
        (forward-line 1)
        (calc-edit-macro-combine-var-name)
        (calc-edit-macro-combine-var-name))
       (t (forward-line 1)))
      (setq type (calc-edit-macro-command-type))))
  (goto-char calc-edit-top))

;; Finish editing the macro

(defun calc-edit-macro-pre-finish-edit ()
  (goto-char calc-edit-top)
  (while (re-search-forward "\\(^\\| \\)RET\\($\\|\t\\| \\)" nil t)
    (search-backward "RET")
    (delete-char 3)
    (insert "<return>")))

(defun calc-edit-macro-finish-edit (cmdname key)
  "Finish editing a Calc macro.
Redefine the corresponding command."
  (interactive)
  (let ((cmd (intern cmdname)))
    (calc-edit-macro-pre-finish-edit)
    (let* ((str (buffer-substring calc-edit-top (point-max)))
           (mac (edmacro-parse-keys str t)))
      (if (= (length mac) 0)
          (fmakunbound cmd)
        (fset cmd
              (list 'lambda '(arg)
                    '(interactive "P")
                    (list 'calc-execute-kbd-macro
                          (vector (key-description mac)
                                  mac)
                          'arg key)))))))

(defun calc-finish-formula-edit (func)
  (let ((buf (current-buffer))
	(str (buffer-substring calc-edit-top (point-max)))
	(start (point))
	(body (calc-valid-formula-func func)))
    (set-buffer calc-original-buffer)
    (let ((val (math-read-expr str)))
      (if (eq (car-safe val) 'error)
	  (progn
	    (set-buffer buf)
	    (goto-char (+ start (nth 1 val)))
	    (error (nth 2 val))))
      (setcar (cdr body)
	      (let ((calc-user-formula-alist (nth 1 (symbol-function func))))
		(calc-fix-user-formula val)))
      (put func 'calc-user-defn val))))

(defun calc-valid-formula-func (func)
  (let ((def (symbol-function func)))
    (and (consp def)
	 (eq (car def) 'lambda)
	 (progn
	   (setq def (cdr (cdr def)))
	   (while (and def
		       (not (eq (car (car def)) 'math-normalize)))
	     (setq def (cdr def)))
	   (car def)))))


(defun calc-get-user-defn ()
  (interactive)
  (calc-wrapper
   (message "Get definition of command: z-")
   (let* ((key (read-char))
	  (def (or (assq key (calc-user-key-map))
		   (assq (upcase key) (calc-user-key-map))
		   (assq (downcase key) (calc-user-key-map))
		   (error "No command defined for that key")))
	  (cmd (cdr def)))
     (if (symbolp cmd)
	 (setq cmd (symbol-function cmd)))
     (cond ((stringp cmd)
	    (message "Keyboard macro: %s" cmd))
	   (t (let* ((func (calc-stack-command-p cmd))
		     (defn (and func
				(symbolp func)
				(get func 'calc-user-defn))))
		(if defn
		    (progn
		      (and (calc-valid-formula-func func)
			   (setq defn (append '(calcFunc-lambda)
					      (mapcar 'math-build-var-name
						      (nth 1 (symbol-function
							      func)))
					      (list defn))))
		      (calc-enter-result 0 "gdef" defn))
		  (error "That command is not defined by a formula"))))))))


(defun calc-user-define-permanent ()
  (interactive)
  (calc-wrapper
   (message "Record in %s the command: z-" calc-settings-file)
   (let* ((key (read-char))
	  (def (or (assq key (calc-user-key-map))
		   (assq (upcase key) (calc-user-key-map))
		   (assq (downcase key) (calc-user-key-map))
		   (and (eq key ?\')
			(cons nil
                              (intern
                               (concat "calcFunc-"
                                       (completing-read
                                        (format "Record in %s the algebraic function: "
                                                calc-settings-file)
                                        (mapcar (lambda (x) (substring x 9))
                                                (all-completions "calcFunc-"
                                                                 obarray))
                                        (lambda (x)
                                          (fboundp
                                           (intern (concat "calcFunc-" x))))
                                        t)))))
                   (and (eq key ?\M-x)
			(cons nil
			      (intern (completing-read
				       (format "Record in %s the command: "
					       calc-settings-file)
				       obarray 'fboundp nil "calc-"))))
		   (error "No command defined for that key"))))
     (set-buffer (find-file-noselect (substitute-in-file-name
				      calc-settings-file)))
     (goto-char (point-max))
     (let* ((cmd (cdr def))
	    (fcmd (and cmd (symbolp cmd) (symbol-function cmd)))
	    (func nil)
	    (pt (point))
	    (fill-column 70)
	    (fill-prefix nil)
	    str q-ok)
       (insert "\n;;; Definition stored by Calc on " (current-time-string)
	       "\n(put 'calc-define '"
	       (if (symbolp cmd) (symbol-name cmd) (format "key%d" key))
	       " '(progn\n")
       (if (and fcmd
		(eq (car-safe fcmd) 'lambda)
		(get cmd 'calc-user-defn))
	   (let ((pt (point)))
	     (and (eq (car-safe (nth 3 fcmd)) 'calc-execute-kbd-macro)
		  (vectorp (nth 1 (nth 3 fcmd)))
		  (progn (and (fboundp 'edit-kbd-macro)
			      (edit-kbd-macro nil))
			 (fboundp 'edmacro-parse-keys))
		  (setq q-ok t)
		  (aset (nth 1 (nth 3 fcmd)) 1 nil))
	     (insert (setq str (prin1-to-string
				(cons 'defun (cons cmd (cdr fcmd)))))
		     "\n")
	     (or (and (string-match "\"" str) (not q-ok))
		 (fill-region pt (point)))
	     (indent-rigidly pt (point) 2)
	     (delete-region pt (1+ pt))
	     (insert " (put '" (symbol-name cmd)
		     " 'calc-user-defn '"
		     (prin1-to-string (get cmd 'calc-user-defn))
		     ")\n")
	     (setq func (calc-stack-command-p cmd))
	     (let ((ffunc (and func (symbolp func) (symbol-function func)))
		   (pt (point)))
	       (and ffunc
		    (eq (car-safe ffunc) 'lambda)
		    (get func 'calc-user-defn)
		    (progn
		      (insert (setq str (prin1-to-string
					 (cons 'defun (cons func
							    (cdr ffunc)))))
			      "\n")
		      (or (and (string-match "\"" str) (not q-ok))
			  (fill-region pt (point)))
		      (indent-rigidly pt (point) 2)
		      (delete-region pt (1+ pt))
		      (setq pt (point))
		      (insert "(put '" (symbol-name func)
			      " 'calc-user-defn '"
			      (prin1-to-string (get func 'calc-user-defn))
			      ")\n")
		      (fill-region pt (point))
		      (indent-rigidly pt (point) 2)
		      (delete-region pt (1+ pt))))))
	 (and (stringp fcmd)
	      (insert " (fset '" (prin1-to-string cmd)
		      " " (prin1-to-string fcmd) ")\n")))
       (or func (setq func (and cmd (symbolp cmd) (fboundp cmd) cmd)))
       (if (get func 'math-compose-forms)
	   (let ((pt (point)))
	     (insert "(put '" (symbol-name cmd)
		     " 'math-compose-forms '"
		     (prin1-to-string (get func 'math-compose-forms))
		     ")\n")
	     (fill-region pt (point))
	     (indent-rigidly pt (point) 2)
	     (delete-region pt (1+ pt))))
       (if (car def)
	   (insert " (define-key calc-mode-map "
		   (prin1-to-string (concat "z" (char-to-string key)))
		   " '"
		   (prin1-to-string cmd)
		   ")\n")))
     (insert "))\n")
     (save-buffer))))

(defun calc-stack-command-p (cmd)
  (if (and cmd (symbolp cmd))
      (and (fboundp cmd)
	   (calc-stack-command-p (symbol-function cmd)))
    (and (consp cmd)
	 (eq (car cmd) 'lambda)
	 (setq cmd (or (assq 'calc-wrapper cmd)
		       (assq 'calc-slow-wrapper cmd)))
	 (setq cmd (assq 'calc-enter-result cmd))
	 (memq (car (nth 3 cmd)) '(cons list))
	 (eq (car (nth 1 (nth 3 cmd))) 'quote)
	 (nth 1 (nth 1 (nth 3 cmd))))))


(defun calc-call-last-kbd-macro (arg)
  (interactive "P")
  (and defining-kbd-macro
       (error "Can't execute anonymous macro while defining one"))
  (or last-kbd-macro
      (error "No kbd macro has been defined"))
  (calc-execute-kbd-macro last-kbd-macro arg))

(defun calc-execute-kbd-macro (mac arg &rest prefix)
  (if calc-keep-args-flag
      (calc-keep-args))
  (if (and (vectorp mac) (> (length mac) 0) (stringp (aref mac 0)))
      (setq mac (or (aref mac 1)
		    (aset mac 1 (progn (and (fboundp 'edit-kbd-macro)
					    (edit-kbd-macro nil))
				       (edmacro-parse-keys (aref mac 0)))))))
  (if (< (prefix-numeric-value arg) 0)
      (execute-kbd-macro mac (- (prefix-numeric-value arg)))
    (if calc-executing-macro
	(execute-kbd-macro mac arg)
      (calc-slow-wrapper
       (let ((old-stack-whole (copy-sequence calc-stack))
	     (old-stack-top calc-stack-top)
	     (old-buffer-size (buffer-size))
	     (old-refresh-count calc-refresh-count))
	 (unwind-protect
	     (let ((calc-executing-macro mac))
	       (execute-kbd-macro mac arg))
	   (calc-select-buffer)
	   (let ((new-stack (reverse calc-stack))
		 (old-stack (reverse old-stack-whole)))
	     (while (and new-stack old-stack
			 (equal (car new-stack) (car old-stack)))
	       (setq new-stack (cdr new-stack)
		     old-stack (cdr old-stack)))
	     (or (equal prefix '(nil))
		 (calc-record-list (if (> (length new-stack) 1)
				       (mapcar 'car new-stack)
				     '(""))
				   (or (car prefix) "kmac")))
	     (calc-record-undo (list 'set 'saved-stack-top old-stack-top))
	     (and old-stack
		  (calc-record-undo (list 'pop 1 (mapcar 'car old-stack))))
	     (let ((calc-stack old-stack-whole)
		   (calc-stack-top 0))
	       (calc-cursor-stack-index (length old-stack)))
	     (if (and (= old-buffer-size (buffer-size))
		      (= old-refresh-count calc-refresh-count))
		 (let ((buffer-read-only nil))
		   (delete-region (point) (point-max))
		   (while new-stack
		     (calc-record-undo (list 'push 1))
		     (insert (math-format-stack-value (car new-stack)) "\n")
		     (setq new-stack (cdr new-stack)))
		   (calc-renumber-stack))
	       (while new-stack
		 (calc-record-undo (list 'push 1))
		 (setq new-stack (cdr new-stack)))
	       (calc-refresh))
	     (calc-record-undo (list 'set 'saved-stack-top 0)))))))))

(defun calc-push-list-in-macro (vals m sels)
  (let ((entry (list (car vals) 1 (car sels)))
	(mm (+ (or m 1) calc-stack-top)))
    (if (> mm 1)
	(setcdr (nthcdr (- mm 2) calc-stack)
		(cons entry (nthcdr (1- mm) calc-stack)))
      (setq calc-stack (cons entry calc-stack)))))

(defun calc-pop-stack-in-macro (n mm)
  (if (> mm 1)
      (setcdr (nthcdr (- mm 2) calc-stack)
	      (nthcdr (+ n mm -1) calc-stack))
    (setq calc-stack (nthcdr n calc-stack))))


(defun calc-kbd-if ()
  (interactive)
  (calc-wrapper
   (let ((cond (calc-top-n 1)))
     (calc-pop-stack 1)
     (if (math-is-true cond)
	 (if defining-kbd-macro
	     (message "If true..."))
       (if defining-kbd-macro
	   (message "Condition is false; skipping to Z: or Z] ..."))
       (calc-kbd-skip-to-else-if t)))))

(defun calc-kbd-else-if ()
  (interactive)
  (calc-kbd-if))

(defun calc-kbd-skip-to-else-if (else-okay)
  (let ((count 0)
	ch)
    (while (>= count 0)
      (setq ch (read-char))
      (if (= ch -1)
	  (error "Unterminated Z[ in keyboard macro"))
      (if (= ch ?Z)
	  (progn
	    (setq ch (read-char))
	    (cond ((= ch ?\[)
		   (setq count (1+ count)))
		  ((= ch ?\])
		   (setq count (1- count)))
		  ((= ch ?\:)
		   (and (= count 0)
			else-okay
			(setq count -1)))
		  ((eq ch 7)
		   (keyboard-quit))))))
    (and defining-kbd-macro
	 (if (= ch ?\:)
	     (message "Else...")
	   (message "End-if...")))))

(defun calc-kbd-end-if ()
  (interactive)
  (if defining-kbd-macro
      (message "End-if...")))

(defun calc-kbd-else ()
  (interactive)
  (if defining-kbd-macro
      (message "Else; skipping to Z] ..."))
  (calc-kbd-skip-to-else-if nil))


(defun calc-kbd-repeat ()
  (interactive)
  (let (count)
    (calc-wrapper
     (setq count (math-trunc (calc-top-n 1)))
     (or (Math-integerp count)
	 (error "Count must be an integer"))
     (if (Math-integer-negp count)
	 (setq count 0))
     (or (integerp count)
	 (setq count 1000000))
     (calc-pop-stack 1))
    (calc-kbd-loop count)))

(defun calc-kbd-for (dir)
  (interactive "P")
  (let (init final)
    (calc-wrapper
     (setq init (calc-top-n 2)
	   final (calc-top-n 1))
     (or (and (math-anglep init) (math-anglep final))
	 (error "Initial and final values must be real numbers"))
     (calc-pop-stack 2))
    (calc-kbd-loop nil init final (and dir (prefix-numeric-value dir)))))

(defun calc-kbd-loop (rpt-count &optional initial final dir)
  (interactive "P")
  (setq rpt-count (if rpt-count (prefix-numeric-value rpt-count) 1000000))
  (let* ((count 0)
	 (parts nil)
	 (body "")
	 (open last-command-event)
	 (counter initial)
	 ch)
    (or executing-kbd-macro
	(message "Reading loop body..."))
    (while (>= count 0)
      (setq ch (read-char))
      (if (= ch -1)
	  (error "Unterminated Z%c in keyboard macro" open))
      (if (= ch ?Z)
	  (progn
	    (setq ch (read-char)
		  body (concat body "Z" (char-to-string ch)))
	    (cond ((memq ch '(?\< ?\( ?\{))
		   (setq count (1+ count)))
		  ((memq ch '(?\> ?\) ?\}))
		   (setq count (1- count)))
		  ((and (= ch ?/)
			(= count 0))
		   (setq parts (nconc parts (list (concat (substring body 0 -2)
							  "Z]")))
			 body ""))
		  ((eq ch 7)
		   (keyboard-quit))))
	(setq body (concat body (char-to-string ch)))))
    (if (/= ch (cdr (assq open '( (?\< . ?\>) (?\( . ?\)) (?\{ . ?\}) ))))
	(error "Mismatched Z%c and Z%c in keyboard macro" open ch))
    (or executing-kbd-macro
	(message "Looping..."))
    (setq body (concat (substring body 0 -2) "Z]"))
    (and (not executing-kbd-macro)
	 (= rpt-count 1000000)
	 (null parts)
	 (null counter)
	 (progn
	   (message "Warning: Infinite loop! Not executing")
	   (setq rpt-count 0)))
    (or (not initial) dir
	(setq dir (math-compare final initial)))
    (calc-wrapper
     (while (> rpt-count 0)
       (let ((part parts))
	 (if counter
	     (if (cond ((eq dir 0) (Math-equal final counter))
		       ((eq dir 1) (Math-lessp final counter))
		       ((eq dir -1) (Math-lessp counter final)))
		 (setq rpt-count 0)
	       (calc-push counter)))
	 (while (and part (> rpt-count 0))
	   (execute-kbd-macro (car part))
	   (if (math-is-true (calc-top-n 1))
	       (setq rpt-count 0)
	     (setq part (cdr part)))
	   (calc-pop-stack 1))
	 (if (> rpt-count 0)
	     (progn
	       (execute-kbd-macro body)
	       (if counter
		   (let ((step (calc-top-n 1)))
		     (calc-pop-stack 1)
		     (setq counter (calcFunc-add counter step)))
		 (setq rpt-count (1- rpt-count))))))))
    (or executing-kbd-macro
	(message "Looping...done"))))

(defun calc-kbd-end-repeat ()
  (interactive)
  (error "Unbalanced Z> in keyboard macro"))

(defun calc-kbd-end-for ()
  (interactive)
  (error "Unbalanced Z) in keyboard macro"))

(defun calc-kbd-end-loop ()
  (interactive)
  (error "Unbalanced Z} in keyboard macro"))

(defun calc-kbd-break ()
  (interactive)
  (calc-wrapper
   (let ((cond (calc-top-n 1)))
     (calc-pop-stack 1)
     (if (math-is-true cond)
	 (error "Keyboard macro aborted")))))


(defvar calc-kbd-push-level 0)

;; The variables var-q0 through var-q9 are the "quick" variables.
(defvar var-q0 nil)
(defvar var-q1 nil)
(defvar var-q2 nil)
(defvar var-q3 nil)
(defvar var-q4 nil)
(defvar var-q5 nil)
(defvar var-q6 nil)
(defvar var-q7 nil)
(defvar var-q8 nil)
(defvar var-q9 nil)

(defun calc-kbd-push (arg)
  (interactive "P")
  (calc-wrapper
   (let* ((defs (and arg (> (prefix-numeric-value arg) 0)))
	  (var-q0 var-q0)
	  (var-q1 var-q1)
	  (var-q2 var-q2)
	  (var-q3 var-q3)
	  (var-q4 var-q4)
	  (var-q5 var-q5)
	  (var-q6 var-q6)
	  (var-q7 var-q7)
	  (var-q8 var-q8)
	  (var-q9 var-q9)
	  (calc-internal-prec (if defs 12 calc-internal-prec))
	  (calc-word-size (if defs 32 calc-word-size))
	  (calc-angle-mode (if defs 'deg calc-angle-mode))
	  (calc-simplify-mode (if defs nil calc-simplify-mode))
	  (calc-algebraic-mode (if arg nil calc-algebraic-mode))
	  (calc-incomplete-algebraic-mode (if arg nil
					    calc-incomplete-algebraic-mode))
	  (calc-symbolic-mode (if defs nil calc-symbolic-mode))
	  (calc-matrix-mode (if defs nil calc-matrix-mode))
	  (calc-prefer-frac (if defs nil calc-prefer-frac))
	  (calc-complex-mode (if defs nil calc-complex-mode))
	  (calc-infinite-mode (if defs nil calc-infinite-mode))
	  (count 0)
	  (body "")
	  ch)
     (if (or executing-kbd-macro defining-kbd-macro)
	 (progn
	   (if defining-kbd-macro
	       (message "Reading body..."))
	   (while (>= count 0)
	     (setq ch (read-char))
	     (if (= ch -1)
		 (error "Unterminated Z` in keyboard macro"))
	     (if (= ch ?Z)
		 (progn
		   (setq ch (read-char)
			 body (concat body "Z" (char-to-string ch)))
		   (cond ((eq ch ?\`)
			  (setq count (1+ count)))
			 ((eq ch ?\')
			  (setq count (1- count)))
			 ((eq ch 7)
			  (keyboard-quit))))
	       (setq body (concat body (char-to-string ch)))))
	   (if defining-kbd-macro
	       (message "Reading body...done"))
	   (let ((calc-kbd-push-level 0))
	     (execute-kbd-macro (substring body 0 -2))))
       (let ((calc-kbd-push-level (1+ calc-kbd-push-level)))
	 (message "Saving modes; type Z' to restore")
	 (recursive-edit))))))

(defun calc-kbd-pop ()
  (interactive)
  (if (> calc-kbd-push-level 0)
      (progn
	(message "Mode settings restored")
	(exit-recursive-edit))
    (error "Unbalanced Z' in keyboard macro")))


;; (defun calc-kbd-report (msg)
;;   (interactive "sMessage: ")
;;   (calc-wrapper
;;    (math-working msg (calc-top-n 1))))

(defun calc-kbd-query ()
  (interactive)
  (let ((defining-kbd-macro nil)
        (executing-kbd-macro nil)
        (msg (calc-top 1)))
    (if (not (eq (car-safe msg) 'vec))
        (error "No prompt string provided")
      (setq msg (math-vector-to-string msg))
      (calc-wrapper
       (calc-pop-stack 1)
       (calc-alg-entry nil (and (not (equal msg "")) msg))))))

;;;; Logical operations.

(defun calcFunc-eq (a b &rest more)
  (if more
      (let* ((args (cons a (cons b (copy-sequence more))))
	     (res 1)
	     (p args)
	     p2)
	(while (and (cdr p) (not (eq res 0)))
	  (setq p2 p)
	  (while (and (setq p2 (cdr p2)) (not (eq res 0)))
	    (setq res (math-two-eq (car p) (car p2)))
	    (if (eq res 1)
		(setcdr p (delq (car p2) (cdr p)))))
	  (setq p (cdr p)))
	(if (eq res 0)
	    0
	  (if (cdr args)
	      (cons 'calcFunc-eq args)
	    1)))
    (or (math-two-eq a b)
	(if (and (or (math-looks-negp a) (math-zerop a))
		 (or (math-looks-negp b) (math-zerop b)))
	    (list 'calcFunc-eq (math-neg a) (math-neg b))
	  (list 'calcFunc-eq a b)))))

(defun calcFunc-neq (a b &rest more)
  (if more
      (let* ((args (cons a (cons b more)))
	     (res 0)
	     (all t)
	     (p args)
	     p2)
	(while (and (cdr p) (not (eq res 1)))
	  (setq p2 p)
	  (while (and (setq p2 (cdr p2)) (not (eq res 1)))
	    (setq res (math-two-eq (car p) (car p2)))
	    (or res (setq all nil)))
	  (setq p (cdr p)))
	(if (eq res 1)
	    0
	  (if all
	      1
	    (cons 'calcFunc-neq args))))
    (or (cdr (assq (math-two-eq a b) '((0 . 1) (1 . 0))))
	(if (and (or (math-looks-negp a) (math-zerop a))
		 (or (math-looks-negp b) (math-zerop b)))
	    (list 'calcFunc-neq (math-neg a) (math-neg b))
	  (list 'calcFunc-neq a b)))))

(defun math-two-eq (a b)
  (if (eq (car-safe a) 'vec)
      (if (eq (car-safe b) 'vec)
	  (if (= (length a) (length b))
	      (let ((res 1))
		(while (and (setq a (cdr a) b (cdr b)) (not (eq res 0)))
		  (if res
		      (setq res (math-two-eq (car a) (car b)))
		    (if (eq (math-two-eq (car a) (car b)) 0)
			(setq res 0))))
		res)
	    0)
	(if (Math-objectp b)
	    0
	  nil))
    (if (eq (car-safe b) 'vec)
	(if (Math-objectp a)
	    0
	  nil)
      (let ((res (math-compare a b)))
	(if (= res 0)
	    1
	  (if (and (= res 2) (not (and (Math-scalarp a) (Math-scalarp b))))
	      nil
	    0))))))

(defun calcFunc-lt (a b)
  (let ((res (math-compare a b)))
    (if (= res -1)
	1
      (if (= res 2)
	  (if (and (or (math-looks-negp a) (math-zerop a))
		   (or (math-looks-negp b) (math-zerop b)))
	      (list 'calcFunc-gt (math-neg a) (math-neg b))
	    (list 'calcFunc-lt a b))
	0))))

(defun calcFunc-gt (a b)
  (let ((res (math-compare a b)))
    (if (= res 1)
	1
      (if (= res 2)
	  (if (and (or (math-looks-negp a) (math-zerop a))
		   (or (math-looks-negp b) (math-zerop b)))
	      (list 'calcFunc-lt (math-neg a) (math-neg b))
	    (list 'calcFunc-gt a b))
	0))))

(defun calcFunc-leq (a b)
  (let ((res (math-compare a b)))
    (if (= res 1)
	0
      (if (= res 2)
	  (if (and (or (math-looks-negp a) (math-zerop a))
		   (or (math-looks-negp b) (math-zerop b)))
	      (list 'calcFunc-geq (math-neg a) (math-neg b))
	    (list 'calcFunc-leq a b))
	1))))

(defun calcFunc-geq (a b)
  (let ((res (math-compare a b)))
    (if (= res -1)
	0
      (if (= res 2)
	  (if (and (or (math-looks-negp a) (math-zerop a))
		   (or (math-looks-negp b) (math-zerop b)))
	      (list 'calcFunc-leq (math-neg a) (math-neg b))
	    (list 'calcFunc-geq a b))
	1))))

(defun calcFunc-rmeq (a)
  (if (math-vectorp a)
      (math-map-vec 'calcFunc-rmeq a)
    (if (assq (car-safe a) calc-tweak-eqn-table)
	(if (and (eq (car-safe (nth 2 a)) 'var)
		 (math-objectp (nth 1 a)))
	    (nth 1 a)
	  (nth 2 a))
      (if (eq (car-safe a) 'calcFunc-assign)
	  (nth 2 a)
	(if (eq (car-safe a) 'calcFunc-evalto)
	    (nth 1 a)
	  (list 'calcFunc-rmeq a))))))

(defun calcFunc-land (a b)
  (cond ((Math-zerop a)
	 a)
	((Math-zerop b)
	 b)
	((math-is-true a)
	 b)
	((math-is-true b)
	 a)
	(t (list 'calcFunc-land a b))))

(defun calcFunc-lor (a b)
  (cond ((Math-zerop a)
	 b)
	((Math-zerop b)
	 a)
	((math-is-true a)
	 a)
	((math-is-true b)
	 b)
	(t (list 'calcFunc-lor a b))))

(defun calcFunc-lnot (a)
  (if (Math-zerop a)
      1
    (if (math-is-true a)
	0
      (let ((op (and (= (length a) 3)
		     (assq (car a) calc-tweak-eqn-table))))
	(if op
	    (cons (nth 2 op) (cdr a))
	  (list 'calcFunc-lnot a))))))

(defun calcFunc-if (c e1 e2)
  (if (Math-zerop c)
      e2
    (if (and (math-is-true c) (not (Math-vectorp c)))
	e1
      (or (and (Math-vectorp c)
	       (math-constp c)
	       (let ((ee1 (if (Math-vectorp e1)
			      (if (= (length c) (length e1))
				  (cdr e1)
				(calc-record-why "*Dimension error" e1))
			    (list e1)))
		     (ee2 (if (Math-vectorp e2)
			      (if (= (length c) (length e2))
				  (cdr e2)
				(calc-record-why "*Dimension error" e2))
			    (list e2))))
		 (and ee1 ee2
		      (cons 'vec (math-if-vector (cdr c) ee1 ee2)))))
	  (list 'calcFunc-if c e1 e2)))))

(defun math-if-vector (c e1 e2)
  (and c
       (cons (if (Math-zerop (car c)) (car e2) (car e1))
	     (math-if-vector (cdr c)
			     (or (cdr e1) e1)
			     (or (cdr e2) e2)))))

(defun math-normalize-logical-op (a)
  (or (and (eq (car a) 'calcFunc-if)
	   (= (length a) 4)
	   (let ((a1 (math-normalize (nth 1 a))))
	     (if (Math-zerop a1)
		 (math-normalize (nth 3 a))
	       (if (Math-numberp a1)
		   (math-normalize (nth 2 a))
		 (if (and (Math-vectorp (nth 1 a))
			  (math-constp (nth 1 a)))
		     (calcFunc-if (nth 1 a)
				  (math-normalize (nth 2 a))
				  (math-normalize (nth 3 a)))
		   (let ((calc-simplify-mode 'none))
		     (list 'calcFunc-if a1
			   (math-normalize (nth 2 a))
			   (math-normalize (nth 3 a)))))))))
      a))

(defun calcFunc-in (a b)
  (or (and (eq (car-safe b) 'vec)
	   (let ((bb b))
	     (while (and (setq bb (cdr bb))
			 (not (if (memq (car-safe (car bb)) '(vec intv))
				  (eq (calcFunc-in a (car bb)) 1)
				(Math-equal a (car bb))))))
	     (if bb 1 (and (math-constp a) (math-constp bb) 0))))
      (and (eq (car-safe b) 'intv)
	   (let ((res (math-compare a (nth 2 b))) res2)
	     (cond ((= res -1)
		    0)
		   ((and (= res 0)
			 (or (/= (nth 1 b) 2)
			     (Math-lessp (nth 2 b) (nth 3 b))))
		    (if (memq (nth 1 b) '(2 3)) 1 0))
		   ((= (setq res2 (math-compare a (nth 3 b))) 1)
		    0)
		   ((and (= res2 0)
			 (or (/= (nth 1 b) 1)
			     (Math-lessp (nth 2 b) (nth 3 b))))
		    (if (memq (nth 1 b) '(1 3)) 1 0))
		   ((/= res 1)
		    nil)
		   ((/= res2 -1)
		    nil)
		   (t 1))))
      (and (Math-equal a b)
	   1)
      (and (math-constp a) (math-constp b)
	   0)
      (list 'calcFunc-in a b)))

(defun calcFunc-typeof (a)
  (cond ((Math-integerp a) 1)
	((eq (car a) 'frac) 2)
	((eq (car a) 'float) 3)
	((eq (car a) 'hms) 4)
	((eq (car a) 'cplx) 5)
	((eq (car a) 'polar) 6)
	((eq (car a) 'sdev) 7)
	((eq (car a) 'intv) 8)
	((eq (car a) 'mod) 9)
	((eq (car a) 'date) (if (Math-integerp (nth 1 a)) 10 11))
	((eq (car a) 'var)
	 (if (memq (nth 2 a) '(var-inf var-uinf var-nan)) 12 100))
	((eq (car a) 'vec) (if (math-matrixp a) 102 101))
	(t (math-calcFunc-to-var (car a)))))

(defun calcFunc-integer (a)
  (if (Math-integerp a)
      1
    (if (Math-objvecp a)
	0
      (list 'calcFunc-integer a))))

(defun calcFunc-real (a)
  (if (Math-realp a)
      1
    (if (Math-objvecp a)
	0
      (list 'calcFunc-real a))))

(defun calcFunc-constant (a)
  (if (math-constp a)
      1
    (if (Math-objvecp a)
	0
      (list 'calcFunc-constant a))))

(defun calcFunc-refers (a b)
  (if (math-expr-contains a b)
      1
    (if (eq (car-safe a) 'var)
	(list 'calcFunc-refers a b)
      0)))

(defun calcFunc-negative (a)
  (if (math-looks-negp a)
      1
    (if (or (math-zerop a)
	    (math-posp a))
	0
      (list 'calcFunc-negative a))))

(defun calcFunc-variable (a)
  (if (eq (car-safe a) 'var)
      1
    (if (Math-objvecp a)
	0
      (list 'calcFunc-variable a))))

(defun calcFunc-nonvar (a)
  (if (eq (car-safe a) 'var)
      (list 'calcFunc-nonvar a)
    1))

(defun calcFunc-istrue (a)
  (if (math-is-true a)
      1
    0))



;;;; User-programmability.

;;; Compiling Lisp-like forms to use the math library.

(defun math-do-defmath (func args body)
  (require 'calc-macs)
  (let* ((fname (intern (concat "calcFunc-" (symbol-name func))))
	 (doc (if (stringp (car body))
		  (prog1 (list (car body))
		    (setq body (cdr body)))))
	 (clargs (mapcar 'math-clean-arg args))
	 (inter (if (and (consp (car body))
			 (eq (car (car body)) 'interactive))
		    (prog1 (car body)
		      (setq body (cdr body))))))
    (setq body (math-define-function-body body clargs))
    `(progn
       ,(if inter
	    (if (or (> (length inter) 2)
		    (integerp (nth 1 inter)))
		(let ((hasprefix nil) (hasmulti nil))
		  (when (stringp (nth 1 inter))
		    (cond ((equal (nth 1 inter) "p")
			   (setq hasprefix t))
			  ((equal (nth 1 inter) "m")
			   (setq hasmulti t))
			  (t (error
			      "Can't handle interactive code string \"%s\""
			      (nth 1 inter))))
		    (setq inter (cdr inter)))
		  (unless (integerp (nth 1 inter))
		    (error "Expected an integer in interactive specification"))
		  `(defun ,(intern (concat "calc-" (symbol-name func)))
		     ,(if (or hasprefix hasmulti) '(&optional n) ())
		     ,@doc
		     (interactive ,@(if (or hasprefix hasmulti) '("P")))
		     (calc-slow-wrapper
		      ,@(if hasmulti
			    `((setq n (if n
					  (prefix-numeric-value n)
					,(nth 1 inter)))))
		      (calc-enter-result
		       ,(if hasmulti 'n (nth 1 inter))
		       ,(nth 2 inter)
		       ,(if hasprefix
			    `(append '(,fname)
				     (calc-top-list-n ,(nth 1 inter))
				     (and n
					  (list
					   (math-normalize
					    (prefix-numeric-value n)))))
			  `(cons ',fname
				 (calc-top-list-n
				  ,(if hasmulti
				       'n
				     (nth 1 inter)))))))))
	      `(defun ,(intern (concat "calc-" (symbol-name func))) ,clargs
		 ,@doc
		 ,inter
		 (calc-wrapper ,@body))))
       (defun ,fname ,clargs
	 ,@doc
	 ,@(math-do-arg-list-check args nil nil)
	 ,@body))))

(defun math-clean-arg (arg)
  (if (consp arg)
      (math-clean-arg (nth 1 arg))
    arg))

(defun math-do-arg-check (arg var is-opt is-rest)
  (if is-opt
      (let ((chk (math-do-arg-check arg var nil nil)))
	(list (cons 'and
		    (cons var
			  (if (cdr chk)
			      `((progn ,@chk))
			    chk)))))
    (when (consp arg)
      (let* ((rest (math-do-arg-check (nth 1 arg) var is-opt is-rest))
	     (qual (car arg))
	     (qual-name (symbol-name qual))
	     (chk (intern (concat "math-check-" qual-name))))
	(if (fboundp chk)
	    (append rest
		    (if is-rest
			`((setq ,var (mapcar ',chk ,var)))
		      `((setq ,var (,chk ,var)))))
	  (if (fboundp (setq chk (intern (concat "math-" qual-name))))
	      (append rest
		      (if is-rest
			  `((mapcar #'(lambda (x)
					(or (,chk x)
					    (math-reject-arg x ',qual)))
				    ,var))
			`((or (,chk ,var)
			      (math-reject-arg ,var ',qual)))))
	    (if (and (string-match "\\`not-\\(.*\\)\\'" qual-name)
		     (fboundp (setq chk (intern
					 (concat "math-"
						 (math-match-substring
						  qual-name 1))))))
		(append rest
			(if is-rest
			    `((mapcar #'(lambda (x)
					  (and (,chk x)
					       (math-reject-arg x ',qual)))
				      ,var))
			  `((and
			     (,chk ,var)
			     (math-reject-arg ,var ',qual)))))
	      (error "Unknown qualifier `%s'" qual-name))))))))

(defun math-do-arg-list-check (args is-opt is-rest)
  (cond ((null args) nil)
	((consp (car args))
	 (append (math-do-arg-check (car args)
				    (math-clean-arg (car args))
				    is-opt is-rest)
		 (math-do-arg-list-check (cdr args) is-opt is-rest)))
	((eq (car args) '&optional)
	 (math-do-arg-list-check (cdr args) t nil))
	((eq (car args) '&rest)
	 (math-do-arg-list-check (cdr args) nil t))
	(t (math-do-arg-list-check (cdr args) is-opt is-rest))))

(defconst math-prim-funcs
  '( (~= . math-nearly-equal)
     (% . math-mod)
     (lsh . calcFunc-lsh)
     (ash . calcFunc-ash)
     (logand . calcFunc-and)
     (logandc2 . calcFunc-diff)
     (logior . calcFunc-or)
     (logxor . calcFunc-xor)
     (lognot . calcFunc-not)
     (equal . equal)   ; need to leave these ones alone!
     (eq . eq)
     (and . and)
     (or . or)
     (if . if)
     (^ . math-pow)
     (expt . math-pow)
   ))

(defconst math-prim-vars
  '( (nil . nil)
     (t . t)
     (&optional . &optional)
     (&rest . &rest)
   ))

(defun math-define-function-body (body env)
  (let ((body (math-define-body body env)))
    (if (math-body-refers-to body 'math-return)
	`((catch 'math-return ,@body))
      body)))

;; The variable math-exp-env is local to math-define-body, but is
;; used by math-define-exp, which is called (indirectly) by
;; by math-define-body.
(defvar math-exp-env)

(defun math-define-body (body math-exp-env)
  (math-define-list body))

(defun math-define-list (body &optional quote)
  (cond ((null body)
	 nil)
	((and (eq (car body) ':)
	      (stringp (nth 1 body)))
	 (cons (let* ((math-read-expr-quotes t)
		      (exp (math-read-plain-expr (nth 1 body) t)))
		 (math-define-exp exp))
	       (math-define-list (cdr (cdr body)))))
	(quote
	 (cons (cond ((consp (car body))
		      (math-define-list (cdr body) t))
		     (t
		      (car body)))
	       (math-define-list (cdr body))))
	(t
	 (cons (math-define-exp (car body))
	       (math-define-list (cdr body))))))

(defun math-define-exp (exp)
  (cond ((consp exp)
	 (let ((func (car exp)))
	   (cond ((memq func '(quote function))
		  (if (and (consp (nth 1 exp))
			   (eq (car (nth 1 exp)) 'lambda))
		      (cons 'quote
			    (math-define-lambda (nth 1 exp) math-exp-env))
		    exp))
		 ((memq func '(let let* for foreach))
		  (let ((head (nth 1 exp))
			(body (cdr (cdr exp))))
		    (if (memq func '(let let*))
			()
		      (setq func (cdr (assq func '((for . math-for)
						   (foreach . math-foreach)))))
		      (if (not (listp (car head)))
			  (setq head (list head))))
		    (macroexpand
		     (cons func
			   (cons (math-define-let head)
				 (math-define-body body
						   (nconc
						    (math-define-let-env head)
						    math-exp-env)))))))
		 ((and (memq func '(setq setf))
		       (math-complicated-lhs (cdr exp)))
		  (if (> (length exp) 3)
		      (cons 'progn (math-define-setf-list (cdr exp)))
		    (math-define-setf (nth 1 exp) (nth 2 exp))))
		 ((eq func 'condition-case)
		  (cons func
			(cons (nth 1 exp)
			      (math-define-body (cdr (cdr exp))
						(cons (nth 1 exp)
						      math-exp-env)))))
		 ((eq func 'cond)
		  (cons func
			(math-define-cond (cdr exp))))
		 ((and (consp func)   ; ('spam a b) == force use of plain spam
		       (eq (car func) 'quote))
		  (cons func (math-define-list (cdr exp))))
		 ((symbolp func)
		  (let ((args (math-define-list (cdr exp)))
			(prim (assq func math-prim-funcs)))
		    (cond (prim
			   (cons (cdr prim) args))
			  ((eq func 'floatp)
			   (list 'eq (car args) '(quote float)))
			  ((eq func '+)
			   (math-define-binop 'math-add 0
					      (car args) (cdr args)))
			  ((eq func '-)
			   (if (= (length args) 1)
			       (cons 'math-neg args)
			     (math-define-binop 'math-sub 0
						(car args) (cdr args))))
			  ((eq func '*)
			   (math-define-binop 'math-mul 1
					      (car args) (cdr args)))
			  ((eq func '/)
			   (math-define-binop 'math-div 1
					      (car args) (cdr args)))
			  ((eq func 'min)
			   (math-define-binop 'math-min 0
					      (car args) (cdr args)))
			  ((eq func 'max)
			   (math-define-binop 'math-max 0
					      (car args) (cdr args)))
			  ((eq func '<)
			   (if (and (math-numberp (nth 1 args))
				    (math-zerop (nth 1 args)))
			       (list 'math-negp (car args))
			     (cons 'math-lessp args)))
			  ((eq func '>)
			   (if (and (math-numberp (nth 1 args))
				    (math-zerop (nth 1 args)))
			       (list 'math-posp (car args))
			     (list 'math-lessp (nth 1 args) (nth 0 args))))
			  ((eq func '<=)
			   (list 'not
				 (if (and (math-numberp (nth 1 args))
					  (math-zerop (nth 1 args)))
				     (list 'math-posp (car args))
				   (list 'math-lessp
					 (nth 1 args) (nth 0 args)))))
			  ((eq func '>=)
			   (list 'not
				 (if (and (math-numberp (nth 1 args))
					  (math-zerop (nth 1 args)))
				     (list 'math-negp (car args))
				   (cons 'math-lessp args))))
			  ((eq func '=)
			   (if (and (math-numberp (nth 1 args))
				    (math-zerop (nth 1 args)))
			       (list 'math-zerop (nth 0 args))
			     (if (and (integerp (nth 1 args))
				      (/= (% (nth 1 args) 10) 0))
				 (cons 'math-equal-int args)
			       (cons 'math-equal args))))
			  ((eq func '/=)
			   (list 'not
				 (if (and (math-numberp (nth 1 args))
					  (math-zerop (nth 1 args)))
				     (list 'math-zerop (nth 0 args))
				   (if (and (integerp (nth 1 args))
					    (/= (% (nth 1 args) 10) 0))
				       (cons 'math-equal-int args)
				     (cons 'math-equal args)))))
			  ((eq func '1+)
			   (list 'math-add (car args) 1))
			  ((eq func '1-)
			   (list 'math-add (car args) -1))
			  ((eq func 'not)   ; optimize (not (not x)) => x
			   (if (eq (car-safe args) func)
			       (car (nth 1 args))
			     (cons func args)))
			  ((and (eq func 'elt) (cdr (cdr args)))
			   (math-define-elt (car args) (cdr args)))
			  (t
			   (macroexpand
			    (let* ((name (symbol-name func))
				   (cfunc (intern (concat "calcFunc-" name)))
				   (mfunc (intern (concat "math-" name))))
			      (cond ((fboundp cfunc)
				     (cons cfunc args))
				    ((fboundp mfunc)
				     (cons mfunc args))
				    ((or (fboundp func)
					 (string-match "\\`calcFunc-.*" name))
				     (cons func args))
				    (t
				     (cons cfunc args)))))))))
		 (t (cons func (math-define-list (cdr exp))))))) ;;args
	((symbolp exp)
	 (let ((prim (assq exp math-prim-vars))
	       (name (symbol-name exp)))
	   (cond (prim
		  (cdr prim))
		 ((memq exp math-exp-env)
		  exp)
		 ((string-match "-" name)
		  exp)
		 (t
		  (intern (concat "var-" name))))))
	((integerp exp)
	 (if (or (<= exp -1000000) (>= exp 1000000))
	     (list 'quote (math-normalize exp))
	   exp))
	(t exp)))

(defun math-define-cond (forms)
  (and forms
       (cons (math-define-list (car forms))
	     (math-define-cond (cdr forms)))))

(defun math-complicated-lhs (body)
  (and body
       (or (not (symbolp (car body)))
	   (math-complicated-lhs (cdr (cdr body))))))

(defun math-define-setf-list (body)
  (and body
       (cons (math-define-setf (nth 0 body) (nth 1 body))
	     (math-define-setf-list (cdr (cdr body))))))

(defun math-define-setf (place value)
  (setq place (math-define-exp place)
	value (math-define-exp value))
  (cond ((symbolp place)
	 (list 'setq place value))
	((eq (car-safe place) 'nth)
	 (list 'setcar (list 'nthcdr (nth 1 place) (nth 2 place)) value))
	((eq (car-safe place) 'elt)
	 (list 'setcar (list 'nthcdr (nth 2 place) (nth 1 place)) value))
	((eq (car-safe place) 'car)
	 (list 'setcar (nth 1 place) value))
	((eq (car-safe place) 'cdr)
	 (list 'setcdr (nth 1 place) value))
	(t
	 (error "Bad place form for setf: %s" place))))

(defun math-define-binop (op ident arg1 rest)
  (if rest
      (math-define-binop op ident
			 (list op arg1 (car rest))
			 (cdr rest))
    (or arg1 ident)))

(defun math-define-let (vlist)
  (and vlist
       (cons (if (consp (car vlist))
		 (cons (car (car vlist))
		       (math-define-list (cdr (car vlist))))
	       (car vlist))
	     (math-define-let (cdr vlist)))))

(defun math-define-let-env (vlist)
  (and vlist
       (cons (if (consp (car vlist))
		 (car (car vlist))
	       (car vlist))
	     (math-define-let-env (cdr vlist)))))

(defun math-define-lambda (exp exp-env)
  (nconc (list (nth 0 exp)   ; 'lambda
	       (nth 1 exp))  ; arg list
	 (math-define-function-body (cdr (cdr exp))
				    (append (nth 1 exp) exp-env))))

(defun math-define-elt (seq idx)
  (if idx
      (math-define-elt (list 'elt seq (car idx)) (cdr idx))
    seq))



;;; Useful programming macros.

(defmacro math-while (head &rest body)
  (let ((body (cons 'while (cons head body))))
    (if (math-body-refers-to body 'math-break)
	(cons 'catch (cons '(quote math-break) (list body)))
      body)))
;; (put 'math-while 'lisp-indent-hook 1)

(defmacro math-for (head &rest body)
  (let ((body (if head
		  (math-handle-for head body)
		(cons 'while (cons t body)))))
    (if (math-body-refers-to body 'math-break)
	(cons 'catch (cons '(quote math-break) (list body)))
      body)))
;; (put 'math-for 'lisp-indent-hook 1)

(defun math-handle-for (head body)
  (let* ((var (nth 0 (car head)))
	 (init (nth 1 (car head)))
	 (limit (nth 2 (car head)))
	 (step (or (nth 3 (car head)) 1))
	 (body (if (cdr head)
		   (list (math-handle-for (cdr head) body))
		 body))
	 (all-ints (and (integerp init) (integerp limit) (integerp step)))
	 (const-limit (or (integerp limit)
			  (and (eq (car-safe limit) 'quote)
			       (math-realp (nth 1 limit)))))
	 (const-step (or (integerp step)
			 (and (eq (car-safe step) 'quote)
			      (math-realp (nth 1 step)))))
	 (save-limit (if const-limit limit (make-symbol "<limit>")))
	 (save-step (if const-step step (make-symbol "<step>"))))
    (cons 'let
	  (cons (append (if const-limit nil (list (list save-limit limit)))
			(if const-step nil (list (list save-step step)))
			(list (list var init)))
		(list
		 (cons 'while
		       (cons (if all-ints
				 (if (> step 0)
				     (list '<= var save-limit)
				   (list '>= var save-limit))
			       (list 'not
				     (if const-step
					 (if (or (math-posp step)
						 (math-posp
						  (cdr-safe step)))
					     (list 'math-lessp
						   save-limit
						   var)
					   (list 'math-lessp
						 var
						 save-limit))
				       (list 'if
					     (list 'math-posp
						   save-step)
					     (list 'math-lessp
						   save-limit
						   var)
					     (list 'math-lessp
						   var
						   save-limit)))))
			     (append body
				     (list (list 'setq
						 var
						 (list (if all-ints
							   '+
							 'math-add)
						       var
						       save-step)))))))))))

(defmacro math-foreach (head &rest body)
  (let ((body (math-handle-foreach head body)))
    (if (math-body-refers-to body 'math-break)
	(cons 'catch (cons '(quote math-break) (list body)))
      body)))
;; (put 'math-foreach 'lisp-indent-hook 1)

(defun math-handle-foreach (head body)
  (let ((var (nth 0 (car head)))
	(data (nth 1 (car head)))
	(body (if (cdr head)
		  (list (math-handle-foreach (cdr head) body))
		body)))
    (cons 'let
	  (cons (list (list var data))
		(list
		 (cons 'while
		       (cons var
			     (append body
				     (list (list 'setq
						 var
						 (list 'cdr var)))))))))))


(defun math-body-refers-to (body thing)
  (or (equal body thing)
      (and (consp body)
	   (or (math-body-refers-to (car body) thing)
	       (math-body-refers-to (cdr body) thing)))))

(defun math-break (&optional value)
  (throw 'math-break value))

(defun math-return (&optional value)
  (throw 'math-return value))





(defun math-composite-inequalities (x op)
  (if (memq (nth 1 op) '(calcFunc-eq calcFunc-neq))
      (if (eq (car x) (nth 1 op))
	  (append x (list (math-read-expr-level (nth 3 op))))
	(throw 'syntax "Syntax error"))
    (list 'calcFunc-in
	  (nth 2 x)
	  (if (memq (nth 1 op) '(calcFunc-lt calcFunc-leq))
	      (if (memq (car x) '(calcFunc-lt calcFunc-leq))
		  (math-make-intv
		   (+ (if (eq (car x) 'calcFunc-leq) 2 0)
		      (if (eq (nth 1 op) 'calcFunc-leq) 1 0))
		   (nth 1 x) (math-read-expr-level (nth 3 op)))
		(throw 'syntax "Syntax error"))
	    (if (memq (car x) '(calcFunc-gt calcFunc-geq))
		(math-make-intv
		 (+ (if (eq (nth 1 op) 'calcFunc-geq) 2 0)
		    (if (eq (car x) 'calcFunc-geq) 1 0))
		 (math-read-expr-level (nth 3 op)) (nth 1 x))
	      (throw 'syntax "Syntax error"))))))

(provide 'calc-prog)

;;; calc-prog.el ends here